Reputation: 9
Simple problem. I need to get the user to input a number, and then convert the string into an integer using try/except.
I've done things similar to this before. In fact I've done much more complicated things before, which is why I'm so confused as to why my code isn't working.
userNum = input('enter a number: ')
try:
num = int(userNum)
For some reason this causes a syntax error. The error statement reads:
Syntax Error: num = int(userNum): <string>, line 3, pos 23
Can anyone tell me why this would cause a problem and how I could fix it? I'm so confused.
Upvotes: 0
Views: 673
Reputation: 830
Try needs to have at least one of the except or finally expressions followed as in:
userNum = input('enter a number: ')
try:
num = int(userNum)
except ValueError as e:
print(e)
Upvotes: 2
Reputation: 1699
In the syntax of a try
statement, you can see that at least one except
part or a finally
part is obligatory.
Working code with except:
userNum = input('enter a number: ')
try:
num = int(userNum)
except:
print("you didn't enter a number")
print(num)
Upvotes: 1
Reputation: 16224
you can either use finally if you want something always happen, if you want something happen on error, use except:
userNum = input('enter a number: ')
try:
num = int(userNum)
finally:
print("something")
or:
userNum = input('enter a number: ')
try:
num = int(userNum)
except Exception:
print("exception something")
finally:
print("something")
or:
userNum = input('enter a number: ')
try:
num = int(userNum)
except Exception:
print("exception something")
Upvotes: 2