Accept only numerics in input

Asked

Viewed 7,124 times

7

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 this validation code to, if the user enters string (a,b,c,d,e,f...) or special character, it shows error and re-requests the integer.

4 answers

19


Just you treat the exception that is fired 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 on Repl.it

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

  • Anderson you are the guy, thank you very much solved instantly.

2

So there are other ways to do it. One of them is to use input as string and reconhcer the type of value read. 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 prior to 3, it may be necessary to use raw_input in place of input.

1

nota = -1
while nota < 0 or nota > 10:
    try:
        nota = int(input("Informe a nota entre 0 e 10: "))
        print("A nota foi:", nota)
        break
    except:
        print("Valor inválido")
        continue

The command continue makes it back to the beginning of the loop.

  • 1

    In this case, if the exception is triggered, the value of nota is not changed, then the loop will continue even without the continue. It would only make sense there if there was more code after the Try/except block.

  • 1

    And maybe do it while not 0 < nota < 10 is more readable than while nota < 0 or nota > 10, but this is more for the same opinion.

0

Another interesting way to resolve this issue, with Python 3.8 or higher is using the concepts of Assignment Expressions, approached by PEP 572.

With these concepts we can greatly reduce the number of lines in the code. This way the code can stay:

while not (nota := input(f'Nota entre "0" e "10": ')).isdigit() or (nota := int(nota)) < 0 or nota > 10:
    print('Valor INVÁLIDO!')

print(nota)

Note that the block while checking three situations:

  1. Checks whether the expression assigned to the variable note is not a digit;
  2. Checks whether the expression assigned to the variable note and converted into whole is less than 0;
  3. Checks whether the expression assigned to the variable note and converted into whole is greater than 10.

Case one of the three block checks while be it True we will receive the message: Valor INVÁLIDO! and we will again be prompted a grade between "0" and "10".

Now, in case the three block checks while are False, the repeat loop will be closed, the value of the typed note will be displayed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.