I am trying to convert input() data to int() with the following code:
prompt_text = "Enter a number: "
try:
user_num = int(input(prompt_text))
except ValueError:
print("Error")
for i in range(1,10):
print(i, " times ", user_num, " is ", i*user_num)
even = ((user_num % 2) == 0)
if even:
print(user_num, " is even")
else:
print(user_num, " is odd")
I get the following odd error when I enter asd2 for example:
Enter a number: asd2 Error
Traceback (most recent call last): File "chapter3_ex1.py", line 8, in <module>
print(i, " times ", user_num, " is ", i*user_num)
NameError: name 'user_num' is not defined
What am I doing wrong?
quit()to yourexcept ValueError. right now your program doesn't stop execution on error.raw_input()and handling the validation parsing of the supplied value once you've got a string - docs.python.org/2/library/functions.html#raw_input,input()does anevalof the supplied input, effectively "turning it into code". This is unsafe.