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 ValueEr
The problem isn't with the conversion to an int
. user_num
doesn't get a value if an exception is thrown, but it's used later.
prompt_text = "Enter a number: "
try:
user_num = int(input(prompt_text)) # this fails with `asd2`
except ValueError:
print("Error") # Prints your error
for i in range(1,10):
print(i, " times ", user_num, " is ", i*user_num) # user_num wasn't assigned because of the error
even = ((user_num % 2) == 0)
if even:
print(user_num, " is even")
else:
print(user_num, " is odd")
You can fix this by putting the code that uses user_num
in the try-block. I'll also add create a function to clean things up.
def is_even(num):
return num%2 == 0
prompt_text = "Enter a number: "
try:
user_num = int(input(prompt_text))
for i in range(1,10):
print(i, " times ", user_num, " is ", i*user_num)
if is_even(user_num):
print(user_num, " is even")
else:
print(user_num, " is odd")
except ValueError:
print("Error")
See the ideone here.