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
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!")
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
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!")