[Tutor] ValueError
Peter Otten
__peter__ at web.de
Tue May 3 14:01:03 CEST 2011
Johnson Tran wrote:
> Thanks for the replies..so I added the "try" block but it still does not
> seem to be outputting my default error message:
>
> def Conversion():
> try:
>
> print "This program converts the first value from inches to
> centimeters and second value centimeters to inches." print "(1
> inch = 2.54 centimeters)" inches = input("Enter length in inches:
> ") centimeters = 2.54 * float(inches)
> print "That is", centimeters, "centimeters."
> centimeters = input("Enter length in centimeters: ")
> inch = float(centimeters) / 2.54
> print "That is", inch, "inches."
>
> except ValueError:
> print "Invalid digit, please try again."
> Conversion()
>
> Error message:
>
> Traceback (most recent call last):
> File "/Users/JT/Desktop/hw#2.py", line 16, in <module>
> Conversion()
> File "/Users/JT/Desktop/hw#2.py", line 9, in Conversion
> centimeters = input("Enter length in centimeters: ")
> File "<string>", line 1, in <module>
> NameError: name 'fs' is not defined
input() in Python 2.x tries to evaluate your input as a Python expression,
so if you enter "2*2" it gives you 4, and when you enter "fs" it tries to
look up the value of a global variable "fs" in your python script. You don't
have such a variable in your script, so it complains with a NameError.
The best way to avoid such puzzling behaviour is to use raw_input() instead
of input().
Also you should make the try...except as narrow as possible
try:
centimeters = float(centimeters)
except ValueError as e:
print e
is likely to catch the float conversion while with many statements in the
try-suite you are more likely to hide a problem that is unrelated to that
conversion.
PS: In Python 3.x raw_input() is gone, but input() behaves like raw_input()
in 2.x
More information about the Tutor
mailing list