try / except, explained simply
If someone types "seven" when your program expects 7, int() raises an error and the program stops. Real programs need to cope with mistakes like that.
Put the risky line inside a try block. If it works, great. If a particular error happens, Python jumps to the matching except block instead of crashing.
Name the error you expect, such as ValueError, so you only catch the problems you know how to handle. Combine try with a while loop to keep asking until the answer makes sense.
Example: An unbreakable question
while True:
answer = input("How many tickets? ")
try:
tickets = int(answer)
break
except ValueError:
print("Please type a number, like 2.")
print(f"Booking {tickets} tickets.")Output
How many tickets? two
Please type a number, like 2.
How many tickets? 2
Booking 2 tickets.Try this
- Also reject numbers below 1 with an if check inside the loop.
- Catch ZeroDivisionError in a program that divides two numbers.
- Remove the except block and see what the error looks like.
