Python: errors, exceptions and debugging
Python errors: read a traceback, isolate the failing case with try and except, then debug without hiding the cause. Twenty corrected exercises.
Getting started
Home Assistant
Buying
Python errors: read a traceback, isolate the failing case with try and except, then debug without hiding the cause. Twenty corrected exercises.


AI-generated illustration
Some links on this page are affiliate links. The button opens Amazon so you can check today’s price.
A bug is unwanted behavior; an exception is the mechanism by which Python stops a line that fails and shows a traceback. Knowing how to read that message and wrap fragile spots with try / except makes programs more robust — as with missing files or int(input()) receiving invalid text.
| Type | Typical cause |
|---|---|
| SyntaxError | A missing : or parenthesis, or a quote left open |
| IndentationError | if / for blocks misaligned (tabs mixed with spaces) |
| TypeError | "3" + 5, or a function call with the wrong types |
| ValueError | int("abc"), or int("3.5") when you wanted an integer |
| NameError | A variable used before assignment, or a typo |
| ZeroDivisionError | Division by zero |
try / excepttry:
x = int(input("Whole number? "))
except ValueError:
print("That is not a valid integer.")
except:: you would hide any error and make debugging harder.You can chain several blocks, except ValueError:, except ZeroDivisionError:, and so on, for different messages.
else and finally (optional)else (after except): runs if no exception was raised in the try.finally: always runs (often to release a resource; with with on files, that is already handled).try:
n = int(input("Number? "))
except ValueError:
print("Invalid.")
else:
print(f"The double is {2 * n}.")
When Python crashes, the message is read from the bottom upward:
^ often points at the part of the line that is wrong.print() calls: show the suspect variables and remove them once the bug is fixed.The solutions are hidden by default: click Show solution to compare your code.
Exercise 1 — Wrap int(input("Number? ")) with try / except ValueError and print That is not an integer. if the conversion fails. Easy
try:
x = int(input("Number? "))
except ValueError:
print("That is not an integer.")
Exercise 2 — In a try, compute 1 / 0; in except ZeroDivisionError, print Division by zero is not allowed. Easy
try:
x = 1 / 0
except ZeroDivisionError:
print("Division by zero is not allowed.")
Exercise 3 — Open inexistant.txt for reading in a try and catch FileNotFoundError to print File not found. Easy
try:
with open("inexistant.txt", "r", encoding="utf-8") as f:
f.read()
except FileNotFoundError:
print("File not found.")
Exercise 4 — Use try / except ValueError / else: if the int(input()) conversion succeeds, the else block prints OK: followed by the value. Easy
try:
n = int(input("Integer? "))
except ValueError:
print("Invalid.")
else:
print("OK:", n)
Exercise 5 — try with finally: in finally, always print End. (even after a ValueError on int("abc")). Easy
try:
int("abc")
except ValueError:
print("Conversion error.")
finally:
print("End.")
Exercise 6 — A while True loop: ask for an integer with int(input()); on ValueError, print Try again. and continue; on success, break. Easy
while True:
try:
n = int(input("Integer? "))
break
except ValueError:
print("Try again.")
Exercise 7 — Catch ValueError and ZeroDivisionError in two separate except blocks after a try that reads a and b with int, then prints a / b. Easy
try:
a = int(input("a ? "))
b = int(input("b ? "))
print(a / b)
except ValueError:
print("Invalid number.")
except ZeroDivisionError:
print("b must not be 0.")
Exercise 8 — Function demander_entier(): keep asking while int(input()) raises ValueError, then return the valid integer. Intermediate
def demander_entier():
while True:
try:
return int(input("Integer? "))
except ValueError:
print("Invalid, try again.")
Exercise 9 — Function demander_entier_positif(): return an integer at least equal to 1; handle ValueError and the case 0 or negative with a message and a new prompt. Intermediate
def demander_entier_positif():
while True:
try:
n = int(input("Integer of at least 1? "))
except ValueError:
print("That is not an integer.")
continue
if n < 1:
print("You need an integer of at least 1.")
continue
return n
Exercise 10 — try: convert float(input()); except ValueError: print Invalid decimal number. Intermediate
try:
x = float(input("Decimal? "))
except ValueError:
print("Invalid decimal number.")
Exercise 11 — List xs = [10, 20]: in a try, print xs[5]; catch IndexError and print Index out of range. Intermediate
xs = [10, 20]
try:
print(xs[5])
except IndexError:
print("Index out of range.")
Exercise 12 — Function diviser(a, b) that returns a / b; if b == 0, the ZeroDivisionError that is raised will be caught by the caller — write a try / except at the call site that prints Not possible. Intermediate
def diviser(a, b): return a / b
try: print(diviser(3, 0)) except ZeroDivisionError: print(“Not possible.”)
Exercise 13 — Combine try on int(input()) and an if: if the integer is negative, print No negatives without crashing (do not raise an exception for that). Intermediate
try:
n = int(input("Integer? "))
except ValueError:
print("Not an integer.")
else:
if n < 0:
print("No negatives")
else:
print("OK:", n)
Exercise 14 — Simulate a debug: x = 3 then print("debug x =", x), then if x > 0: and print("debug after if", x) (two traces, as in the lesson). Intermediate
x = 3
print("debug x =", x)
if x > 0:
print("debug after if", x)
Exercise 15 — Function lire_entier_ou_none(): return int(input()) or None on ValueError (no infinite loop). Hard
def lire_entier_ou_none():
try:
return int(input("Integer? "))
except ValueError:
return None
Exercise 16 — try / except / else / finally: in try, int(input()); except ValueError: a message; else: Well done; finally: Finished. Hard
try:
n = int(input("Integer? "))
except ValueError:
print("Invalid.")
else:
print("Well done")
finally:
print("Finished.")
Exercise 17 — Read a file in try / except FileNotFoundError; on success, print Read., otherwise No file. Hard
try:
with open("data.txt", "r", encoding="utf-8") as f:
f.read()
except FileNotFoundError:
print("No file.")
else:
print("Read.")
Exercise 18 — A loop with three tries at most to read an integer: on each ValueError, increment a counter; after 3 failures, print Give up and break. Hard
essais = 0
while essais < 3:
try:
n = int(input("Integer? "))
print("OK", n)
break
except ValueError:
essais += 1
print("Once more.")
else:
print("Give up")
Exercise 19 — Chain a try: int(input()) then 10 / n; catch ValueError and ZeroDivisionError and print a different message for each. Hard
try:
n = int(input("Integer? "))
print(10 / n)
except ValueError:
print("That is not an integer.")
except ZeroDivisionError:
print("Division by zero.")
Exercise 20 — Write saisir_note_sur_20() that returns an integer between 0 and 20: loop until success; handle ValueError and values out of range with distinct messages. Hard
def saisir_note_sur_20():
while True:
try:
n = int(input("Grade out of 20? "))
except ValueError:
print("An integer is expected.")
continue
if n < 0 or n > 20:
print("The grade must be between 0 and 20.")
continue
return n
The higher-or-lower mini-game brings together loops, input, random and a clean try / except on the input.
Python good-practice books: Amazon.com
Was this page helpful?
Thank you!
What should we improve?
Torn between two models or stuck on a build? Drop us a line and we will get back to you by email.
Cookies and analytics
We use Google Analytics 4 to understand how the site is used (page views, navigation). It is only switched on if you accept. Declining does not stop you using the site. More: cookie settings and privacy policy (in French).