pythonpython-3.xif-statementwhile-looptry-except

Python: else ValueError: (Specifically ValueError In This Case)


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 :).


Solution

  • try and except are a form of control flow. Essentially, it means try to run this code, except if an exception occurs (such as ValueError) do something else.

    if and else are another form of control flow. Together, they mean if a condition is true, do something; else, do something else.

    An exception occurring is not a condition, and thus it would not make sense to use else with an exception like ValueError. Instead, you want to use the try/except block.