How to handle specific integer exception in python with try function. How to handle multiple except with try function

Viewed 56

This code should tell exactly what error the user is making and prompt to try again.

How can I make custom error messages for each error?

Would there be a much more simpler solution like the do-while in c-programming?

while True:
    height = int(input("Height: "))
    try:
        check_answer = int(height)
        assert (int(height) > 0)
        assert (int(height) < 9)
        break
    except ValueError:
        print("must enter a number")
    except (???):
        print("enter a number greater than 0")
    except (???):
        print("enter a number smaller than 9")

1 Answers

If you must use the assert statement, you can pass the message as a second argument so that it becomes the message of the AssertionError exception:

while True:
    try:
        height = int(input("Height: "))
        assert height > 0, "enter a number greater than 0"
        assert height < 9, "enter a number smaller than 9"
        break
    except ValueError:
        print("must enter a number")
    except AssertionError as e:
        print(str(e))

But what you want to achieve is usually done with simple if statements instead:

while True:
    try:
        height = int(input("Height: "))
    except ValueError:
        print("must enter a number")
    if height <= 0:
        print("enter a number greater than 0")
    elif height >= 9:
        print("enter a number smaller than 9")
    else:
        break
Related