When I enter a letter for one of the numbers I get an error:
Traceback (most recent call last):
File "/Users/rodchar/Documents/Hello World Katie/testing.py", line 7, in <module>
x = input("What is your first number?")
File "<string>", line 1, in <module>
NameError: name 's' is not defined
x = 0
y = 0
isValid = False
while isValid == False:
x = input("What is your first number?")
try:
float(x)
isValid = True
except:
isValid = False
y = input("What is your second number?")
try:
float(y)
isValid = True
except:
isValid = False
print "The answer is: %s" % (x+y)
Firstly, at least in Python 2.7,
input()is not what you want for getting user input. You actually wantraw_input(). (This is, indeed, confusing, and has been fixed in Python 3.)Secondly, as @jamylak said, the statement giving the exception is not inside a try/catch block.
Thirdly, when you catch exceptions using
except:, you should really be catching a specific type of exception (except ValueError:) instead of any and all exceptions. Catching all exceptions is bad because it masks bugs that raise exceptions you didn’t anticipate.A better way to write this would be:
xand gettingyfrom the user is very similar. Instead of writing the same thing twice, write it once and reuse it.Tested on Python 2.7: