Start numeric variable with null value in Python

Asked

Viewed 1,636 times

0

Browsing the Python Brasil site, I decided to do exercise 1 of the Repetition Structure list:

"Make a program that asks for a note, between zero and ten. Display a message if the value is invalid and continues to ask until the user enters a valid value."

nota = ""
while nota < 0 or nota > 10:
    nota = float(input("Digite uma nota de 0 a 10: "))
    print "Nota inválida, digite apenas uma nota de 0 a 10."

print("Nota: %.1f" %nota)

After trying to solve, I also found this solution developed in Python2 when rewriting it to Python 3 I came across the problem: Py3 does not compare the while when the global variable note has value null

# Python 3
nota = float(None)
while nota < 0 or nota > 10:
    nota = float(input("Digite uma nota de 0 a 10: "))
    print('Nota inválida, digite apenas uma nota de 0 a 10.')

print('Nota: {:.1f}'.format(nota))

How to solve this problem still using Python 3?

3 answers

0

I was able to solve the problem by requesting the note before the while and inside the body of while requesting again, in case the value is outside the specified range.

nota = float(input("Digite uma nota de 0 a 10: "))
while nota < 0 or nota > 10:

    print('Nota inválida, digite apenas uma nota de 0 a 10.')
    nota = float(input("Digite uma nota de 0 a 10: "))

print('Nota: {:.1f}'.format(nota))

But still my doubt regarding the variable with null value reverberates. Can anyone explain to me how this works in Python 3?

0


I particularly don’t like the solution of reading the value before the loop and reading it again inside the loop. These are lines of equal code, which become two places to edit if the application changes and the code becomes redundant. Like not times how to know how many iterations it will take to read a valid value, nothing fairer than creating a loop infinity. We also do not know if the user’s read value will be numerical, so we must pay attention to the exception that can be triggered by the initializer of float when trying to convert the value. And given that we will treat an exception, nothing better than to fire the same exception if the value is not in the desired range, thus managing to concentrate the treatment of error in just one place.

Take 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 on Repl.it

The block else of try will be executed only if no exception is triggered, indicating that the value read is numeric and is in the desired range, stopping the loop; otherwise, the loop continues to be executed, until read a valid value.


In your code, the error occurs by trying to convert a null value into float. This makes no sense in Python: either it is a null value or it is a float. What you could start with is a value that you are sure is invalid for the range, ensuring that the loop be executed.

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 on Repl.it

By initializing the variable with 0, you guarantee that the loop will be executed by reading the user’s value, but falls into what I commented at the beginning of the answer: you will need to do the same condition within the loop by repeating code. The capture of the exception is paramount for the correct functioning of the program, because the way it is, if the user enters a text, his program will end with the release of the exception. With the block try/except you prevent that.

  • Anderson, thank you for your answers. I really liked the error handling. I just got a little confused with the line: if not 0 < note < 10: It seems that 0 cannot be less than note and note cannot be less than 10. Could you please explain to me a little bit more about this structure? Or how it’s called this for me to research more about it?

  • @Lucasbraga In Python, the expression 0 < nota < 10 is equivalent to 0 < nota and nota < 10, which produces the same result as nota > 0 and nota < 10, ie, returns true if nota belongs to the range and False, otherwise. Making if not 0 < nota < 10 I’m checking whether the value of nota does not belong to the range.

  • The detailed explanation of how it works can be found in this question: https://answall.com/q/241769/5878. Although the question appears to be different, the answers address exactly this situation.

-1

I removed the while variable and the program reproduced correctly, asking for a note and giving the value of what I typed, it was like this:

nota = float(input("Digite uma nota de 0 a 10: "))
while nota < 0 or nota > 10:

print('Nota inválida, digite apenas uma nota de 0 a 10.')

print('Nota: {:.1f}'.format(nota))
  • I thank Leandro, but in its code the program only works if the user type the note between the established range(0 to 10) otherwise the program is in infinite loop and does not let the user try to type again.

Browser other questions tagged

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