I have a question which is unrelated to my code. I'm just curious. Why is it that I (I don't know about you) can only use a ValueError with a try and except loop? for example:
print("What is 1 + 1?")
while(True):
try:
UserInput = int(input(("Your answer here:"))
if(UserInput == 2):
print("Congratulations you are correct!")
break
else:
print("That is incorrect. Try again!")
except ValueError:
print("That is not a number. Try again!")
This works perfectly fine (or at least it should) but, why (if not) would this next piece of code not work.
print("What is 1 + 1?")
while(True):
UserInput = int(input("Your answer here:"))
if(UserInput == 2):
print("Congratulations you are correct!")
break
elif(UserInput != 2):
print("That is incorrect. Try again!")
else(ValueError):
print("That is not a number. Try again!")
When I run this I get this error:
Traceback (most recent call last):
File "python", line 9
else(ValueError):
^
SyntaxError: invalid syntax
I know it is because ValueError only works (I think) with try and except loops but, why can't it not work in the above scenario? I assume they would give the same results but, I don't know everything. Maybe one of you amazingly smart people can tell me my that wont work or an alternative. Thank you for trying to clarify this to me :).
Aucun commentaire:
Enregistrer un commentaire