try and except: don't let an error stop the program
Section 11: Randomness and errorsLesson 11.3 · ⏱ 10 min
Some errors we only find when the program runs: dividing by zero, or a user who typed a word instead of a number. Instead of the program stopping, we try (try), and if an error happens we deal with it (except).
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "You cannot divide by zero!"
print(divide(10, 2))
print(divide(7, 0))
for text in ["42", "hello"]:
try:
n = int(text)
print(n, "is a number")
except ValueError:
print(text, "is not a number")
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗5.0 You cannot divide by zero! 42 is a number hello is not a number

ZeroDivisionError: dividing by zero.ValueError:int("hello")can't turn the word into a number.
💡 Tip
Use try with
int(input()) in the guess-the-number game, so the game doesn't stop if the player types a letter.- Write a program that asks for your age with input, and asks again until you type a proper number.
📌 Another example: ask until they type a number
try inside while: we ask again until they type a proper number.
When the program asks, we type: twelve, then 12.
while True:
try:
age = int(input("Age: "))
break
except ValueError:
print("Please write a number")
print("Age is", age)
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗Age: twelve Please write a number Age: 12 Age is 12
✍️ Practise
Try the lesson's examples here: copy the code, change it, and click ▶ Run.
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
🎯 Challenge yourself
Easy
Turn the string "abc" into a number safely.
👀 Show the solution🙈 Hide the solution
try:
n = int("abc")
except ValueError:
print("not a number")
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗not a number
Result: not a number
Medium
Take item number 10 from a list with 3 items safely (IndexError).
👀 Show the solution🙈 Hide the solution
items = [1, 2, 3]
try:
print(items[10])
except IndexError:
print("no item there")
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗no item there
Result: no item there
Hard
Divide two numbers the user types, with two possible errors.
👀 Show the solution🙈 Hide the solution
When the program asks, we type: 8, then 0.
try:
a = int(input("a: "))
b = int(input("b: "))
print(a / b)
except ValueError:
print("numbers only")
except ZeroDivisionError:
print("cannot divide by zero")
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗a: 8 b: 0 cannot divide by zero
Result: cannot divide by zero

