انتقل للمحتوى
Robo EgyptRobo Egypt
☰ Course contents
Robo Python: home
0. Lab tour1
1. The start5
2. Variables and input5
3. Conditions5
4. Loops5
5. Lists4
6. Functions4
7. Drawing with the turtle3
8. The project: the guess-the-number game3
9. Strings in depth1
10. Dictionaries (dict)3
11. Randomness and errors3
12. Classes and objects (class)2
13. Pro drawing and charts3
14. The final project: the quiz game2

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:
5.0
You cannot divide by zero!
42 is a number
hello is not a number
🐍 Open the code in Robo Python ↗
The program kept going despite the two errors
The program kept going despite the two errors
  • 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.
  1. 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.

🐍 Ask until they type a number
while True:
    try:
        age = int(input("Age: "))
        break
    except ValueError:
        print("Please write a number")
print("Age is", age)
🖥️ The output in Robo Python:
Age: twelve
Please write a number
Age: 12
Age is 12
🐍 Open the code in Robo Python ↗
✍️ Practise
Try the lesson's examples here: copy the code, change it, and click ▶ Run.
✍️ Practise here in the lessonor open the lab in a new page ↗

🎯 Challenge yourself

Easy

Turn the string "abc" into a number safely.

👀 Show the solution
🐍 Solution
try:
    n = int("abc")
except ValueError:
    print("not a number")
🖥️ The output in Robo Python:
not a number
🐍 Open the code in Robo Python ↗

Result: not a number

Medium

Take item number 10 from a list with 3 items safely (IndexError).

👀 Show the solution
🐍 Solution
items = [1, 2, 3]
try:
    print(items[10])
except IndexError:
    print("no item there")
🖥️ The output in Robo Python:
no item there
🐍 Open the code in Robo Python ↗

Result: no item there

Hard

Divide two numbers the user types, with two possible errors.

👀 Show the solution

When the program asks, we type: 8, then 0.

🐍 Solution
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:
a: 8
b: 0
cannot divide by zero
🐍 Open the code in Robo Python ↗

Result: cannot divide by zero

Finished the lesson? Mark it so your progress counts.