I particularly do not like the solution to read the value before the loop and read it back into the loop. They are equal code lines, which become two places to edit if the application changes and the code becomes redundant. Since you do not know how many iterations it will take to read a valid value, nothing is fairer than creating an infinite loop . We also do not know if the read value of the user will be numeric, so we must pay attention to the exception that can be triggered by the float
initializer when trying to convert the value. And given that we're going to treat an exception, nothing better than triggering the same exception if the value is not in the desired range, thus managing to focus the error treatment on just one place.
See an example:
while True:
try:
nota = float(input("Digite uma nota entre 0 e 10: "))
if not 0 < nota < 10:
raise ValueError("A nota deve ser um valor entre 0 e 10")
except ValueError as error:
print(error)
else:
break
See working at Repl.it
The block else
of try
will be executed only if no exception is triggered, indicating that the read value is numeric and is in the desired interval, stopping the loop; otherwise, the loop continues to execute until it reads a valid value.
In your code, the error occurs because you try to convert a null value to float . This does not make sense in Python: either it's a null value or it's a float . What you could do is start with a value that you are sure is invalid for the range, ensuring that the loop runs.
nota = 0
while not 0 < nota < 10:
nota = float(input("Digite uma nota de 0 a 10: "))
if not 0 < nota < 10:
print('Nota inválida, digite apenas uma nota de 0 a 10.')
print('Nota: {:.1f}'.format(nota))
See working at Repl.it
Initializing the variable with 0, you guarantee that the loop will be executed by reading the value of the user, however it falls on what I commented at the beginning of the answer: you will need to do the same condition inside the loop, repeating code. Exception capture is paramount to the correct operation of the program, because the way it is, if the user types a text, his program will end with the exception thrown. With block try/except
you prevent this.