Module 1, topic 6, week 3, Thursday
File I/O and error handling (try/except)
Reading error messages, try and except, else and finally, raising errors, and the basics of files
Lesson notebook
The lesson as a Jupyter notebook: the explanations, every example and the 15 solved problems, ready to run and change.
topic-06-error-handling-and-files.ipynb, 44 KB
Practice notebook
The 15 practice problems with examples of input and output, a hint and a hidden solution for each.
topic-06-practice.ipynb, 29 KB
Introduction: error handling and file basics
A beginner-friendly guide to handling errors with try and except, so that a program does not crash when something goes wrong. It starts from the simplest examples and gets harder step by step: what an error is, the common error types, try and except, several error types, else and finally, try in loops and functions, and raising your own errors. A short part at the end shows the basics of reading and writing files. Then it walks through 15 solved problems from easy to medium-hard. At the end there are practice problems.
You should already know variables, data types, if/else, loops, functions, lists, dictionaries and comprehensions.
What you will learn
- 1.What an exception is and how to read an error message
- 2.The most common error types and when each one happens
- 3.
tryandexcept, and how Python moves through them - 4.Catching one type, several types, and getting the message with
as error - 5.
elseandfinally - 6.
tryinside loops and functions: asking until the input is valid, skipping bad values - 7.Raising your own errors with
raise, and how an error travels through function calls - 8.The basics of files: writing, reading, and the modes
"r","w","a" - 9.15 solved problems and practice problems
1Errors and how to read them
1.1A program that stops
print("Start")
number = int("abc")
print("End")Output
Start
Error
ValueError: invalid literal for int() with base 10: 'abc'
Change it and run: change "abc" to "12". Now End is printed.
Start was printed, then the program stopped. End was never printed. An error that happens while the program runs is called an exception.
1.2How to read the message
The last line of the message has two parts:
ValueError: invalid literal for int() with base 10: 'abc'
- Before the colon: the type of the error (
ValueError). - After the colon: the explanation.
Always read this line first. The type tells you what kind of problem it is, and the type is also what try/except works with.
ValueError1: invalid literal for int() with base 10: 'abc'2
- 1The type: what kind of problem it is. This is the name you write after
except. - 2The explanation: what exactly went wrong, often with the value that caused it.
1.3Syntax errors are different
A SyntaxError means the code itself is not written correctly. Python finds it before running anything, so not even the first line runs:
print("Start")
if 5 > 3
print("yes")Error
SyntaxError: expected ':'
Start was not printed. A syntax error cannot be handled while the program runs. You fix it in the code.
| Syntax error | Exception | |
|---|---|---|
| When | before the program starts | while the program runs |
| Cause | the code is written wrongly | a value or a situation the code cannot handle |
| What to do | fix the code | fix the code, or handle it with try/except |
1.4The common error types
You have already met most of them in earlier lessons:
| Error type | When it happens | Example |
|---|---|---|
ValueError | the type is right but the value is not | int("abc") |
TypeError | the type is wrong for this operation | "5" + 5 |
ZeroDivisionError | division by zero | 10 / 0 |
IndexError | a list index that does not exist | [1, 2, 3][5] |
KeyError | a dictionary key that does not exist | {"a": 1}["b"] |
NameError | a name that was never created | print(totl) |
AttributeError | a method that this type does not have | "abc".append("d") |
print(10 / 0)Error
ZeroDivisionError: division by zero
Change it and run: divide by 2 instead.
print("5" + 5)Error
TypeError: can only concatenate str (not "int") to str
numbers = [1, 2, 3]
print(numbers[5])Error
IndexError: list index out of range
prices = {"apple": 1.5}
print(prices["kiwi"])Error
KeyError: 'kiwi'
Change it and run: ask for "apple".
total = 100
print(totl)Error
NameError: name 'totl' is not defined. Did you mean: 'total'?
Python even suggests the name you probably meant.
Two kinds of causes. Some errors are mistakes in the code (a misspelled name, a wrong index): you fix the code. Others come from outside (the user types letters instead of a number): the code is fine, but it must be ready for them. try/except is for the second kind.
Try it yourself
Show a hint
KeyError: the key 'Apple' does not exist. Keys are case-sensitive.Show the solution
prices = {"apple": 1.5}
print(prices["apple"])Output
1.5
2try and except
2.1The basic form
try:
number = int("abc")
print("This line is skipped")
except ValueError:
print("That is not a number")
print("The program continues")Output
That is not a number The program continues
Change it and run: change "abc" to "7". Which lines run now?
try:
# code that may cause an error
except ErrorType:
# what to do if that error happensThe program did not stop. Python tried the code, the error happened, and the except block ran instead.
2.2How Python runs it
- Python runs the lines of the
tryblock. - If an error happens, the rest of the
tryblock is skipped and Python jumps toexcept. - If no error happens, the
exceptblock is skipped. - In both cases the program continues below.
The same code with a value that works:
try:
number = int("42")
print("Converted:", number)
except ValueError:
print("That is not a number")
print("The program continues")Output
Converted: 42 The program continues
| Error in try | No error in try | |
|---|---|---|
Lines of try after the error | skipped | all run |
except block | runs | skipped |
| Code below | runs | runs |
2.3With input from the user
text = input("How old are you? ")
try:
age = int(text)
print("Next year you will be", age + 1)
except ValueError:
print("Please type a whole number")Output
How old are you? twenty Please type a whole number
Change it and run: type 20 in the input box, then type twenty again.
2.4A value to continue with
Often the except block gives the variable a default value, so the rest of the program can go on:
text = "abc"
try:
quantity = int(text)
except ValueError:
quantity = 1
print("Quantity:", quantity)Output
Quantity: 1
Change it and run: change "abc" to "5".
Try it yourself
not a number if the text is not a whole number.Show a hint
int(text) goes inside try. The except block names ValueError.Show the solution
text = input()
try:
print(int(text) + 1)
except ValueError:
print("not a number")Output
not a number
3Catching the right error
3.1An except catches only the type you name
Another type still stops the program:
try:
result = 10 / 0
except ValueError:
print("That is not a number")Error
ZeroDivisionError: division by zero
Change it and run: change ValueError to ZeroDivisionError.
3.2Several except blocks
def divide(a, b):
try:
print(int(a) / int(b))
except ValueError:
print("Please use whole numbers")
except ZeroDivisionError:
print("Cannot divide by zero")
divide("10", "2")
divide("ten", "2")
divide("10", "0")Output
5.0 Please use whole numbers Cannot divide by zero
Change it and run: add a call divide("0", "10"). Is that an error?
Python uses the first except block whose type matches, and only that one.
3.3One block for several types
When the reaction is the same, write the types as a tuple:
try:
print(int("10") / int("0"))
except (ValueError, ZeroDivisionError):
print("Bad input")Output
Bad input
3.4The error message: as error
as error stores the error in a variable, so you can print its explanation:
try:
number = int("abc")
except ValueError as error:
print("Problem:", error)Output
Problem: invalid literal for int() with base 10: 'abc'
Change it and run: change "abc" to "3.5" and read the new message.
numbers = [1, 2, 3]
try:
print(numbers[5])
except IndexError as error:
print("Problem:", error)
print("Type:", type(error).__name__)Output
Problem: list index out of range Type: IndexError
3.5Exception: almost every error
Exception matches almost every error type. Use it as the last block, for the cases you did not expect, and print the message so that the problem is not hidden:
def show(value, index):
try:
print(10 / value[index])
except ZeroDivisionError:
print("Cannot divide by zero")
except Exception as error:
print("Unexpected problem:", type(error).__name__, "-", error)
show([5, 0], 0)
show([5, 0], 1)
show([5, 0], 7)
show(5, 0)Output
2.0 Cannot divide by zero Unexpected problem: IndexError - list index out of range Unexpected problem: TypeError - 'int' object is not subscriptable
Change it and run: add a call show("50", 0).
The order matters: specific types first, Exception last. If Exception came first, it would catch everything and the other blocks would never run.
3.6Do not hide errors
An except: without a type catches every error, also the ones that are real mistakes in your code:
try:
total = 10 + numbr
except:
print("Something went wrong")Output
Something went wrong
Change it and run: change except: to except ValueError:. Now Python shows the real problem.
The real problem is a misspelled name (numbr), but the message hides it. Name the error type you expect. Then unexpected errors still stop the program and show you where the mistake is.
| Form | Catches | Use it |
|---|---|---|
except ValueError: | one type | most of the time |
except (ValueError, KeyError): | the listed types | the same reaction for several types |
except ValueError as error: | one type, and gives the message | when you want to show or save the explanation |
except Exception as error: | almost everything | as the last block, and always print the message |
except: | everything | avoid it |
Try it yourself
numbers = [10, 20, 30], read an index and a divisor (two lines) and print the item at that index divided by the divisor. Print not a number, no such index or cannot divide by zero when something goes wrong.Show a hint
except blocks: ValueError, IndexError, ZeroDivisionError.Show the solution
numbers = [10, 20, 30]
try:
index = int(input())
divisor = int(input())
print(numbers[index] / divisor)
except ValueError:
print("not a number")
except IndexError:
print("no such index")
except ZeroDivisionError:
print("cannot divide by zero")Output
10.0
4else and finally
elseruns only if no error happened intry.finallyruns always, with or without an error.
def read_number(text):
try:
number = int(text)
except ValueError:
print("Not a number:", text)
else:
print("Success:", number)
finally:
print("Done with", text)
read_number("42")
read_number("abc")Output
Success: 42 Done with 42 Not a number: abc Done with abc
Change it and run: add a call read_number("3.5").
| Block | Runs when | Typical use |
|---|---|---|
try | always (until an error happens) | the code that may fail |
except | an error of that type happened | a message, a default value |
else | no error happened | the work that needs the result of try |
finally | always | a final message, cleaning up |
Only try and except are required. The order is fixed: try, except, else, finally.
4.1Why else?
Code in else is not protected by the except blocks. This keeps the try block small: only the risky line is inside it.
text = "8"
try:
number = int(text)
except ValueError:
print("Not a number")
else:
print("Half:", number / 2)
print("Double:", number * 2)Output
Half: 4.0 Double: 16
Change it and run: change "8" to "eight".
4.2finally runs even when the error is not caught
try:
print(10 / 0)
finally:
print("This is printed before the program stops")Output
This is printed before the program stops
Error
ZeroDivisionError: division by zero
Choose a value and see which lines run.
- try:
- number = int(text)runs
- print("Converted:", number)runs
- except ValueError:
- print("Not a number")skipped
- else:
- print("No error")runs
- finally:
- print("Done")runs
- print("The program continues")runs
Output
Converted: 42 No error Done The program continues
No error: the whole try block runs, except is skipped, else and finally run.
Try it yourself
text to a whole number. Print not a number in except, Half: and half of the number in else, and Done in finally.Show a hint
try, except ValueError, else, finally. Only the conversion goes into try.Show the solution
text = "6"
try:
number = int(text)
except ValueError:
print("not a number")
else:
print("Half:", number / 2)
finally:
print("Done")Output
Half: 3.0 Done
5try in loops and functions
5.1Asking until the input is valid
while True:
text = input("Enter your age: ")
try:
age = int(text)
break
except ValueError:
print("Please type a whole number")
print("Next year you will be", age + 1)Output
Enter your age: abc Please type a whole number Enter your age: 20.5 Please type a whole number Enter your age: 20 Next year you will be 21
Change it and run: type your own answers in the input box, one per line, with a valid number last.
break runs only when int(text) worked. After an error, the loop asks again.
5.2Skipping the bad values of a list
The try goes inside the loop, so one bad value does not stop the others:
values = ["10", "abc", "30", "", "5"]
total = 0
skipped = 0
for value in values:
try:
total = total + int(value)
except ValueError:
skipped = skipped + 1
print("Total:", total)
print("Skipped:", skipped)Output
Total: 45 Skipped: 2
Change it and run: add two more bad values to the list.
Compare with a try around the loop: the first bad value ends the whole loop.
values = ["10", "abc", "30", "", "5"]
total = 0
try:
for value in values:
total = total + int(value)
except ValueError:
print("Stopped at a bad value")
print("Total:", total)Output
Stopped at a bad value Total: 10
Change it and run: move "abc" to the end of the list. What is the total now?
| Where is the try? | A bad value | Result |
|---|---|---|
| inside the loop | that one value is skipped | the loop goes on with the next value |
| around the loop | the loop ends | the values after it are never processed |
5.3A function that returns a default
def to_number(text, default=0):
try:
return int(text)
except ValueError:
return default
print(to_number("42"))
print(to_number("abc"))
print(to_number("abc", -1))Output
42 0 -1
Change it and run: call to_number("12.5", 99).
5.4An error travels up through function calls
If a function does not handle an error, the error goes to the place that called the function. It can be caught there:
def half(text):
return int(text) / 2
def show_half(text):
try:
print(half(text))
except ValueError:
print("Cannot use", text)
show_half("8")
show_half("abc")Output
4.0 Cannot use abc
Change it and run: add a call show_half("10").
The error happened inside half, but half has no try. So it travelled to show_half, which caught it. If nobody catches it, the program stops.
Try it yourself
Show a hint
try inside it. Add 1 to the counter after int(value) worked.Show the solution
values = input().split()
count = 0
for value in values:
try:
int(value)
count = count + 1
except ValueError:
pass
print(count)Output
3
6Raising your own errors
6.1raise
Sometimes you decide that a value is wrong, even if Python has no problem with it. raise creates an error with your own message:
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return age
print(set_age(20))
print(set_age(-5))Output
20
Error
ValueError: Age cannot be negative
6.2Catching an error that you raised
It is caught like any other error:
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return age
try:
set_age(-5)
except ValueError as error:
print("Problem:", error)Output
Problem: Age cannot be negative
Change it and run: call set_age(30) inside the try and print the result.
6.3Choosing the type
Use the type that describes the problem:
| Problem | Type to raise |
|---|---|
| the value is not acceptable (negative age, empty name) | ValueError |
| the type is wrong (text where a number is needed) | TypeError |
def average(numbers):
if not isinstance(numbers, list):
raise TypeError("numbers must be a list")
if len(numbers) == 0:
raise ValueError("the list is empty")
return sum(numbers) / len(numbers)
for data in [[4, 6], [], "46"]:
try:
print(average(data))
except (TypeError, ValueError) as error:
print(type(error).__name__, "-", error)Output
5.0 ValueError - the list is empty TypeError - numbers must be a list
Change it and run: add [10] to the list of test values.
6.4Why raise instead of printing?
A function that only prints a message cannot tell its caller that something went wrong. A function that raises lets the caller decide what to do: show a message, ask again, or use a default.
6.5Check first, or try?
Both ways are correct:
prices = {"apple": 1.5}
if "kiwi" in prices:
print(prices["kiwi"])
else:
print("No such product")
try:
print(prices["kiwi"])
except KeyError:
print("No such product")Output
No such product No such product
Change it and run: change "kiwi" to "apple" in all three places.
| Use if when | Use try when |
|---|---|
the check is simple: key in d, b != 0, len(items) > 0 | you cannot know before you try: is this text a number? |
| the problem is a normal, frequent case | the problem is rare |
Good habits
- Keep the
tryblock small: only the lines that may fail. - Name the error type.
- Do not use
tryto hide mistakes in your own code. Fix them. - Write a message that helps the user: what was wrong and what to do.
Try it yourself
average(numbers) that raises a ValueError for an empty list. The loop at the bottom calls it with two lists and prints the average, or no numbers.Show a hint
if len(numbers) == 0: then raise ValueError("the list is empty").Show the solution
def average(numbers):
if len(numbers) == 0:
raise ValueError("the list is empty")
return sum(numbers) / len(numbers)
for numbers in [[4, 6], []]:
try:
print(average(numbers))
except ValueError:
print("no numbers")Output
5.0 no numbers
7File basics
Variables are gone when the program ends. A file keeps data on the disk. This part shows only the basics of text files.
7.1Writing
with open("notes.txt", "w") as file:
file.write("first line\n")
file.write("second line\n")
print("Saved")Output
Saved
Change it and run: add a third line to the file.
open("notes.txt", "w")opens the file for writing. If it does not exist, Python creates it, in the same folder as the program.withcloses the file by itself when the block ends.writetakes only text, and it does not start a new line by itself: add\nat the end of each line. Convert numbers withstr().
7.2Reading
Every example that reads a file first creates it, so each example works on its own.
with open("notes.txt", "w") as file:
file.write("first line\nsecond line\n")
with open("notes.txt") as file:
text = file.read()
print(text)Output
first line second line
read() gives the whole file as one text. A for loop gives one line at a time. Each line ends with \n, and .strip() removes it:
with open("notes.txt", "w") as file:
file.write("first line\nsecond line\n")
with open("notes.txt") as file:
for line in file:
print(line.strip())Output
first line second line
Change it and run: remove .strip(). Where do the empty lines come from?
A file contains text, so numbers must be converted with int() or float():
with open("numbers.txt", "w") as file:
file.write("10\n20\n30\n")
total = 0
with open("numbers.txt") as file:
for line in file:
total = total + int(line)
print(total)Output
60
Change it and run: add a fourth number to the file.
7.3Modes
| Mode | Meaning | If the file exists | If the file does not exist |
|---|---|---|---|
"r" | read (the default) | reads it | FileNotFoundError |
"w" | write | erases it, then writes | creates it |
"a" | append | keeps it, writes at the end | creates it |
with open("log.txt", "w") as file:
file.write("Monday\n")
with open("log.txt", "a") as file:
file.write("Tuesday\n")
with open("log.txt") as file:
print(file.read())Output
Monday Tuesday
Change it and run: change "a" to "w". Which line is lost?
Try it yourself
Show a hint
range(1, 6) with file.write(str(number) + "\n"). Reading: a loop over the lines with int(line).Show the solution
with open("numbers.txt", "w") as file:
for number in range(1, 6):
file.write(str(number) + "\n")
total = 0
with open("numbers.txt") as file:
for line in file:
total = total + int(line)
print(total)Output
15
Try it yourself
1: Aylin.Show a hint
"w" to create, "a" to add, and no mode to read. Count the lines with a variable that starts at 1.Show the solution
with open("names.txt", "w") as file:
file.write("Aylin\nMurad\nLeyla\n")
with open("names.txt", "a") as file:
file.write("Kamran\n")
file.write("Nigar\n")
number = 1
with open("names.txt") as file:
for line in file:
print(f"{number}: {line.strip()}")
number = number + 1Output
1: Aylin 2: Murad 3: Leyla 4: Kamran 5: Nigar
8Common mistakes
The red text is the real message Python shows. Where there is no message, the program runs but does the wrong thing: the comment shows what it prints.
except: without a type
Wrong
try:
total = 10 + numbr
except:
print("Something went wrong")
# prints: Something went wrongRight
try:
number = int("abc")
print("This line is skipped")
except ValueError:
print("That is not a number")
print("The program continues")
# prints: That is not a number, The program continuesReal mistakes are hidden. Name the type: except ValueError:.
Catching the wrong type
Wrong
try:
result = 10 / 0
except ValueError:
print("That is not a number")ZeroDivisionError: division by zero
Right
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
# prints: Cannot divide by zeroThe error is not caught. Read the last line of the message for the type.
Too much code inside try
Wrong
try:
a = int("8")
b = int("x")
print(a / b)
except ValueError:
print("Something is not a number")
# prints: Something is not a numberRight
a = int("8")
try:
b = int("x")
except ValueError:
print("b is not a number")
# prints: b is not a numberYou do not know which line failed. Keep only the risky lines in try.
try around the loop instead of inside it
Wrong
values = ["10", "abc", "30", "", "5"]
total = 0
try:
for value in values:
total = total + int(value)
except ValueError:
print("Stopped at a bad value")
print("Total:", total)
# prints: Stopped at a bad value, Total: 10Right
values = ["10", "abc", "30", "", "5"]
total = 0
skipped = 0
for value in values:
try:
total = total + int(value)
except ValueError:
skipped = skipped + 1
print("Total:", total)
print("Skipped:", skipped)
# prints: Total: 45, Skipped: 2The first bad value ends the loop. Put try inside the loop.
except Exception before a specific type
Wrong
try:
print(10 / 0)
except Exception:
print("Some problem")
except ZeroDivisionError:
print("Cannot divide by zero")
# prints: Some problemRight
try:
print(10 / 0)
except ZeroDivisionError:
print("Cannot divide by zero")
except Exception:
print("Some problem")
# prints: Cannot divide by zeroThe specific block never runs. Specific types first.
An empty reaction (pass)
Wrong
try:
amount = int("abc")
except ValueError:
pass
print("Done")
# prints: DoneRight
text = "abc"
try:
quantity = int(text)
except ValueError:
quantity = 1
print("Quantity:", quantity)
# prints: Quantity: 1The error disappears silently. Print a message or use a default.
Using a variable that was never set because of the error
Wrong
try:
amount = int("abc")
except ValueError:
print("Not a number")
print(amount)NameError: name 'amount' is not defined
Right
try:
amount = int("abc")
except ValueError:
amount = 0
print(amount)
# prints: 0NameError later. Give it a default in except.
Printing in a function instead of raising
Wrong
def set_age(age):
if age < 0:
print("Age cannot be negative")
return age
age = set_age(-5)
print("Stored:", age)
# prints: Age cannot be negative, Stored: -5Right
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return age
try:
set_age(-5)
except ValueError as error:
print("Problem:", error)
# prints: Problem: Age cannot be negativeThe caller cannot react. Write raise ValueError("...").
Opening an existing file with "w"
Wrong
with open("log.txt", "w") as file:
file.write("Monday\n")
with open("log.txt", "w") as file:
file.write("Tuesday\n")
with open("log.txt") as file:
print(file.read())
# prints: TuesdayRight
with open("log.txt", "w") as file:
file.write("Monday\n")
with open("log.txt", "a") as file:
file.write("Tuesday\n")
with open("log.txt") as file:
print(file.read())
# prints: Monday, TuesdayThe old content is erased. Use "a" to add.
Forgetting \n or .strip() with files
Wrong
with open("notes.txt", "w") as file:
file.write("first line")
file.write("second line")
with open("notes.txt") as file:
print(file.read())
# prints: first linesecond lineRight
with open("notes.txt", "w") as file:
file.write("first line\nsecond line\n")
with open("notes.txt") as file:
for line in file:
print(line.strip())
# prints: first line, second lineOne long line, or empty lines when printing. \n when writing, strip() when reading.
A variable that was never set:
try:
amount = int("abc")
except ValueError:
print("Not a number")
print(amount)Output
Not a number
Error
NameError: name 'amount' is not defined
amount was never created, because the error happened before the assignment finished. Give it a default in the except block.
9Solved problems (easy to medium-hard)
Every example was run, and the outputs are real.
9.1Level 1: Easy
Problem 1: A safe conversion
text = input()
try:
number = int(text)
print(number * 2)
except ValueError:
print("not a number")Output
21 42
Change it and run: type abc, then 3.5.
Problem 2: A safe division
a = 10
b = 0
try:
print(a / b)
except ZeroDivisionError:
print("cannot divide by zero")Output
cannot divide by zero
Problem 3: A safe list index
items = ["a", "b", "c"]
index = 5
try:
print(items[index])
except IndexError:
print("no such index")Output
no such index
Problem 4: A safe dictionary lookup, with the message
prices = {"apple": 1.5, "bread": 0.8}
try:
print(prices["milk"])
except KeyError as error:
print("Missing key:", error)Output
Missing key: 'milk'
Problem 5: Save and read three lines
with open("cities.txt", "w") as file:
file.write("Baku\nGanja\nSheki\n")
with open("cities.txt") as file:
for line in file:
print(line.strip())Output
Baku Ganja Sheki
9.2Level 2: Medium
Problem 6: A division that cannot crash
try:
a, b = map(int, input().split())
print(a / b)
except ValueError:
print("Please type two whole numbers")
except ZeroDivisionError:
print("Cannot divide by zero")Output
10 0 Cannot divide by zero
Change it and run: type 10 4, then ten 4.
Why: two different things can go wrong, so there are two except blocks.
Problem 7: Ask until the number is between 1 and 10
while True:
try:
number = int(input("A number from 1 to 10: "))
except ValueError:
print("That is not a whole number")
continue
if 1 <= number <= 10:
break
print("Out of range")
print("Thank you:", number)Output
A number from 1 to 10: abc That is not a whole number A number from 1 to 10: 15 Out of range A number from 1 to 10: 7 Thank you: 7
Change it and run: type your own answers, one per line.
Why: try handles text that is not a number, and the if handles a number that is out of range. continue goes back to the start of the loop.
Problem 8: The sum of the valid numbers
values = ["12", "x", "7.5", "30", "-4"]
numbers = []
for value in values:
try:
numbers.append(int(value))
except ValueError:
print("Skipped:", value)
print(numbers)
print("Sum:", sum(numbers))Output
Skipped: x Skipped: 7.5 [12, 30, -4] Sum: 38
Why: int("7.5") is a ValueError too, because the text is not a whole number.
Problem 9: else and finally together
def check(text):
try:
number = float(text)
except ValueError:
print(text, "-> not a number")
else:
print(text, "-> half is", number / 2)
finally:
print("checked", text)
check("9")
check("nine")Output
9 -> half is 4.5 checked 9 nine -> not a number checked nine
Problem 10: The sum of the numbers in a file
with open("numbers.txt", "w") as file:
file.write("12\n7\n30\n11\n")
with open("numbers.txt") as file:
numbers = [int(line) for line in file]
print(numbers)
print("Sum:", sum(numbers))Output
[12, 7, 30, 11] Sum: 60
9.3Level 3: Medium-Hard
Problem 11: A calculator that reports every problem
def calculate(a, operator, b):
try:
a = float(a)
b = float(b)
if operator == "+":
return a + b
if operator == "/":
return a / b
raise ValueError(f"unknown operator {operator}")
except ZeroDivisionError:
return "error: division by zero"
except ValueError as error:
return f"error: {error}"
print(calculate("8", "+", "2"))
print(calculate("8", "/", "0"))
print(calculate("8", "/", "two"))
print(calculate("8", "%", "2"))Output
10.0 error: division by zero error: could not convert string to float: 'two' error: unknown operator %
Change it and run: add print(calculate("x", "+", "2")).
Why: the unknown operator is our own ValueError, raised with raise. It is caught by the same block as the conversion error, and the message shows which one it was.
Problem 12: A function that checks its argument
def check_password(password):
if len(password) < 8:
raise ValueError("the password needs at least 8 characters")
if password.isdigit():
raise ValueError("the password cannot be only digits")
return True
for password in ["abc", "12345678", "python2026"]:
try:
check_password(password)
print(password, "-> accepted")
except ValueError as error:
print(password, "->", error)Output
abc -> the password needs at least 8 characters 12345678 -> the password cannot be only digits python2026 -> accepted
Change it and run: test a password of your own.
Problem 13: An error caught by the caller
def percent(part, whole):
return part / whole * 100
def report(name, part, whole):
try:
print(name, round(percent(part, whole), 1))
except ZeroDivisionError:
print(name, "no data")
report("Aylin", 17, 20)
report("Murad", 0, 0)Output
Aylin 85.0 Murad no data
Why: percent stays simple and does not handle anything. The error travels to report, which knows what to print.
Problem 14: Grades with bad records
records = ["Aylin 85", "Murad ninety", "Leyla", "Kamran 45"]
grades = {}
problems = []
for record in records:
try:
name, grade = record.split()
grades[name] = int(grade)
except ValueError:
problems.append(record)
print(grades)
print("Bad records:", problems)Output
{'Aylin': 85, 'Kamran': 45}
Bad records: ['Murad ninety', 'Leyla']Change it and run: add the record "Nigar 77".
Why: two different problems give the same error type. int("ninety") is a ValueError, and a record with only one word cannot be unpacked into two variables, which is a ValueError too.
Problem 15: A log that grows
with open("log.txt", "w") as file:
file.write("program started\n")
def add_entry(text):
with open("log.txt", "a") as file:
file.write(text + "\n")
add_entry("user logged in")
add_entry("user logged out")
with open("log.txt") as file:
entries = [line.strip() for line in file]
print(len(entries), "entries")
print("Last:", entries[-1])Output
3 entries Last: user logged out
Why: the function opens the file with "a", so every call adds one line at the end.
10Practice problems (try them yourself)
Fifteen problems in three levels. The first lines in each editor read the input or give the starting values. Press Run to try one input, then Check to run your code with several inputs, including the ones that cause an error.
Easy
One error type and one try/except each.
- 1.Read a text from the user. Print the number doubled, or
not a numberif it is not a whole number.Examples:21gives42abcgivesnot a number-4gives-8Show a hint
Putint(text)insidetry. The error type for a text that is not a whole number isValueError.Show one possible solution
Pythontext = input() try: print(int(text) * 2) except ValueError: print("not a number")Output
42
- 2.Read two whole numbers from one line and print the first divided by the second, or
cannot divide by zero.Examples:10 2gives5.07 0givescannot divide by zero0 5gives0.0Show a hint
The division is the risky line. Its error type isZeroDivisionError.Show one possible solution
Pythona, b = map(int, input().split()) try: print(a / b) except ZeroDivisionError: print("cannot divide by zero")Output
5.0
- 3.Given
items = ["a", "b", "c"], read an index from the user and print the item at that index, orno such index.Examples:0givesa2givesc5givesno such indexShow a hint
items[index]gives anIndexErrorwhen the index does not exist. A negative index such as -1 is valid.Show one possible solution
Pythonitems = ["a", "b", "c"] index = int(input()) try: print(items[index]) except IndexError: print("no such index")Output
a
- 4.Given
prices = {"apple": 1.5, "bread": 0.8}, read a product name and print its price, orno such product. Usetry/except.Examples:applegives1.5breadgives0.8kiwigivesno such productShow a hint
prices[product]gives aKeyErrorwhen the key is missing.Show one possible solution
Pythonprices = {"apple": 1.5, "bread": 0.8} product = input() try: print(prices[product]) except KeyError: print("no such product")Output
1.5
- 5.Read a text and print
whole number,decimal numberornot a number.Examples:42giveswhole number3.5givesdecimal numberabcgivesnot a numberShow a hint
Tryint(text)first. In itsexceptblock, tryfloat(text)with a secondtry/except.Show one possible solution
Pythontext = input() try: int(text) print("whole number") except ValueError: try: float(text) print("decimal number") except ValueError: print("not a number")Output
whole number
Medium
Loops, functions and two error types.
- 6.Read a line of values separated by spaces. Print the sum of the values that are whole numbers and how many values were skipped, on one line with a space between them.Examples:
10 abc 30 x 5gives45 21 2 3gives6 0a bgives0 2Show a hint
Two variables,totalandskipped. Thetrygoes inside the loop: add intry, count the skipped value inexcept.Show one possible solution
Pythonvalues = input().split() total = 0 skipped = 0 for value in values: try: total = total + int(value) except ValueError: skipped = skipped + 1 print(total, skipped)Output
45 2
- 7.Write a function
safe_divide(a, b)that returns the result, orNoneifbis zero.Examples:10 2gives5.010 0givesNone0 3gives0.0Show a hint
return a / binsidetry, andreturn Noneinsideexcept ZeroDivisionError:.Show one possible solution
Pythondef safe_divide(a, b): try: return a / b except ZeroDivisionError: return None a, b = map(int, input().split()) print(safe_divide(a, b))Output
5.0
- 8.Write a function
safe_int(text, default)that returns the text as a whole number, ordefaultif it cannot be converted.Examples:42gives42abcgives-1-8gives-8Show a hint
return int(text)insidetry, andreturn defaultinsideexcept ValueError:.Show one possible solution
Pythondef safe_int(text, default): try: return int(text) except ValueError: return default text = input() print(safe_int(text, -1))Output
42
- 9.Keep asking the user for a whole number from 1 to 5 until the input is valid. Then print
okand the number. Print nothing for the wrong answers.Examples:3givesok 3abc, 9, 4givesok 40, 6, 1givesok 1Show a hint
while True:withint(input())insidetry. Inexcept ValueError:writecontinue. After thetry,breakwhen the number is from 1 to 5.Show one possible solution
Pythonwhile True: try: number = int(input()) except ValueError: continue if 1 <= number <= 5: break print("ok", number)Output
ok 3
- 10.Read a text and an index (two lines). Print the character at that index. Print
not a numberif the index is not a whole number, andno such indexif it is out of range.Examples:python, 0givesppython, 10givesno such indexpython, xgivesnot a numberShow a hint
Two things can go wrong, so twoexceptblocks:ValueErrorfor the conversion andIndexErrorfor the index.Show one possible solution
Pythontext = input() try: index = int(input()) print(text[index]) except ValueError: print("not a number") except IndexError: print("no such index")Output
p
Medium-Hard
Raising errors, several problems in one input, and a file.
- 11.Write a function
check_age(age)that raises aValueErrorwith a message if the age is below 0 or above 120, and returns the age otherwise. Read an age and printok, or the message. The message isage must be between 0 and 120.Examples:20givesok-1givesage must be between 0 and 120121givesage must be between 0 and 120Show a hint
Inside the function:if age < 0 or age > 120:thenraise ValueError("age must be between 0 and 120"). Outside: call it intry, and print the error inexcept ValueError as error:.Show one possible solution
Pythondef check_age(age): if age < 0 or age > 120: raise ValueError("age must be between 0 and 120") return age age = int(input()) try: check_age(age) print("ok") except ValueError as error: print(error)Output
ok
- 12.Read a line of records like
Aylin:85 Murad:x Leyla:78. Build a dictionary of the valid ones. Print the dictionary and how many records were bad, on one line with a space between them.Examples:Aylin:85 Murad:x Leyla:78gives{'Aylin': 85, 'Leyla': 78} 1A:1gives{'A': 1} 0A B:2gives{'B': 2} 1Show a hint
For every record,name, grade = record.split(":")andint(grade)go insidetry. Both problems (no colon, a grade that is not a number) are aValueError.Show one possible solution
Pythonrecords = input().split() grades = {} bad = 0 for record in records: try: name, grade = record.split(":") grades[name] = int(grade) except ValueError: bad = bad + 1 print(grades, bad)Output
{'Aylin': 85, 'Leyla': 78} 1 - 13.Write a function
parse_time(text)that takes a text like14:30and returns the minutes since midnight. It raises aValueErrorif the text is not in that form or the numbers are out of range (hours 0 to 23, minutes 0 to 59). The last lines print the result, orinvalid time.Examples:14:30gives87000:00gives023:59gives1439Show a hint
Split the text at":"into two variables and convert both withint(). A wrong form already gives aValueErrorby itself. For numbers out of range,raise ValueError(...)yourself.Show one possible solution
Pythondef parse_time(text): hours, minutes = text.split(":") hours = int(hours) minutes = int(minutes) if hours < 0 or hours > 23 or minutes < 0 or minutes > 59: raise ValueError("out of range") return hours * 60 + minutes text = input() try: print(parse_time(text)) except ValueError: print("invalid time")Output
870
- 14.Write a function
to_numbers(values)that returns two lists: the values that could be converted to whole numbers, and the values that could not.Examples:10 abc 30 xgives([10, 30], ['abc', 'x'])1 2gives([1, 2], [])agives([], ['a'])Show a hint
Two empty lists. In the loop,good.append(int(value))insidetryandbad.append(value)insideexcept ValueError:. Return both:return good, bad.Show one possible solution
Pythondef to_numbers(values): good = [] bad = [] for value in values: try: good.append(int(value)) except ValueError: bad.append(value) return good, bad values = input().split() print(to_numbers(values))Output
([10, 30], ['abc', 'x'])
- 15.A file has one value per line, and some lines are not numbers. Print the sum of the valid numbers and how many lines were skipped, on one line with a space between them. The first lines of the editor create the file.
Show a hint
Open the file for reading and loop over its lines.int(line)goes insidetry. An empty line is aValueErrortoo.Show one possible solution
Pythonwith open("values.txt", "w") as file: file.write("10\nabc\n30\n\n5\n") total = 0 skipped = 0 with open("values.txt") as file: for line in file: try: total = total + int(line) except ValueError: skipped = skipped + 1 print(total, skipped)Output
45 2
11Check yourself
Twelve quick questions. Your answers are saved in this browser, so you can leave the page and continue later. Each finished round is kept as an attempt below the questions; you can delete the attempts at any time.
0 of 12 answered.
12Quick summary
| Concept | What it does | Example |
|---|---|---|
| Exception | an error while the program runs | ValueError, KeyError, ZeroDivisionError |
try / except | handles an error instead of stopping | except ValueError: |
| Several types | one block each, or a tuple | except (ValueError, KeyError): |
as error | gives access to the message | except ValueError as error: |
Exception | almost every error, as the last block | except Exception as error: |
else | runs if no error happened | else: print(number) |
finally | runs always | finally: print("done") |
try in a loop | one bad value does not stop the others | for v in values: try: ... |
raise | creates an error yourself | raise ValueError("too short") |
with open(name, mode) | opens a file and closes it by itself | with open("a.txt", "w") as file: |
"r" / "w" / "a" | read / write (erases) / append | open("log.txt", "a") |
write / read | text into a file / the whole file | file.write("hi\n"), file.read() |