Today you will learn:
By the end, you will be able to write programs that don’t crash when the user enters wrong input.
Programs crash if they get unexpected input:
Example without error handling:
number = int(input("Enter a number: "))
print(10 / number)
Problem:
abc → ValueError0 → ZeroDivisionErrortry → code block that might cause errors
except → what happens when a specific error occurs
try:
number = int(input("Enter a number: "))
print(10 / number)
except ValueError:
print("Please enter a number!")
except ZeroDivisionError:
print("Division by zero is not allowed!")
Explanation:
ValueError → input is not a numberZeroDivisionError → division by zeroYou can also catch all errors if you don’t know the exact error type:
try:
# code
except:
print("An error occurred!")
Tip:
We improve the number guessing game from Day 7:
Problem before:
guess = int(input("Guess the number from 1 to 10: "))
With error handling:
import random
number = random.randint(1, 10)
guess = 0
attempts = 0
while guess != number:
try:
guess = int(input("Guess the number from 1 to 10: "))
attempts += 1
if guess < number:
print("Too low!")
elif guess > number:
print("Too high!")
else:
print("Correct! You took", attempts, "attempts!")
except ValueError:
print("Please enter a number!")
Explanation:
ValueError → a message is shownEnhance your existing number guessing game:
try / except inside a function, e.g., def guess_number():