How to re-run through loop when exception happens in Python?

Question:

When executing this it only runs through the initial if elif statement. If I reach 0 it returns the proper print statement along with when I’m subtracting numbers. However if I try to subtract to reach a negative number and therefore reach the exception, it doesn’t print the statement below and reloop through like I want it to.

number = 15
print("Subtract the number", number, "until it has reached 0")
while number != 0:
    try:
        x = int(input())
        number = number-x
        if number > 0:
            print("You have", number, "points to spend!")
        elif number == 0:
            print("You have used all your points!")
            break
    except number < 0:
            print("You don't have enough points for that!")
            continue
Asked By: Ornsteiner

||

Answers:

except is used for catching errors. You want this:

while number != 0:
    x = int(input())
    if number - x > 0:
        number -= x
        print("You have", number, "points to spend!")
    elif number == x:
        number = 0
        print("You have used all your points!")
        break
    else:
        print("You don't have enough points for that!")
Answered By: The Thonnu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.