Accept only numeric input

5
nota = -1
while nota < 0 or nota > 10:
    nota = int(input("Informe a nota entre 0 e 10: "))
    if nota < 0 or nota > 10:
        print("Valor inválido")

I need to include in this validation code for, if the user types string (a, b, c, d, e, f ...) or special character, it shows error and requests the integer again.     

asked by anonymous 09.10.2017 / 21:28

2 answers

16

Just treat the exception that is thrown by int when the conversion fails:

while True:
    try:
        nota = int(input("Informe a nota entre 0 e 10: "))
        if not 0 <= nota <= 10:
            raise ValueError("Nota fora do range permitido")
    except ValueError as e:
        print("Valor inválido:", e)
    else:
        break

print(nota)

See working at Repl.it

while True ensures that the reading will be performed until break is executed; try/except catches the exception triggered by int , which is ValueError , displaying the error message; if the exception is not raised, the else block is executed by stopping the loop.

    
09.10.2017 / 21:32
1

So there are other ways to do it. One is to use the input as a string and recognize the type of the read value. This can be done like this:

nota = -1
while nota < 0 or nota > 10:
    nota = input("Informe a nota entre 0 e 10: ")
    if nota.isdigit():
        if nota < 0 or nota > 10:
            print("Valor inválido")
    else:
        print("Não parece ser um número")

Here has a reference to isdigit.

For python versions earlier than 3, you may need to use raw_input instead of input .

    
22.12.2017 / 02:52