Asiman Data School

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

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. 1.What an exception is and how to read an error message
  2. 2.The most common error types and when each one happens
  3. 3.try and except, and how Python moves through them
  4. 4.Catching one type, several types, and getting the message with as error
  5. 5.else and finally
  6. 6.try inside loops and functions: asking until the input is valid, skipping bad values
  7. 7.Raising your own errors with raise, and how an error travels through function calls
  8. 8.The basics of files: writing, reading, and the modes "r", "w", "a"
  9. 9.15 solved problems and practice problems

1Errors and how to read them

1.1A program that stops

Python
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
  1. 1The type: what kind of problem it is. This is the name you write after except.
  2. 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:

Python
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 errors are different
Syntax errorException
Whenbefore the program startswhile the program runs
Causethe code is written wronglya value or a situation the code cannot handle
What to dofix the codefix the code, or handle it with try/except

1.4The common error types

You have already met most of them in earlier lessons:

The common error types
Error typeWhen it happensExample
ValueErrorthe type is right but the value is notint("abc")
TypeErrorthe type is wrong for this operation"5" + 5
ZeroDivisionErrordivision by zero10 / 0
IndexErrora list index that does not exist[1, 2, 3][5]
KeyErrora dictionary key that does not exist{"a": 1}["b"]
NameErrora name that was never createdprint(totl)
AttributeErrora method that this type does not have"abc".append("d")
Python
print(10 / 0)

Error

ZeroDivisionError: division by zero

Change it and run: divide by 2 instead.

Python
print("5" + 5)

Error

TypeError: can only concatenate str (not "int") to str
Python
numbers = [1, 2, 3]
print(numbers[5])

Error

IndexError: list index out of range
Python
prices = {"apple": 1.5}
print(prices["kiwi"])

Error

KeyError: 'kiwi'

Change it and run: ask for "apple".

Python
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

Run the code and read the last line of the message. Which type is it, and what does it say? Then fix the code so that it prints the price of the apple.
Show a hint
It is a KeyError: the key 'Apple' does not exist. Keys are case-sensitive.
Show the solution
Python
prices = {"apple": 1.5}
print(prices["apple"])

Output

1.5

2try and except

2.1The basic form

Python
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 happens

The program did not stop. Python tried the code, the error happened, and the except block ran instead.

2.2How Python runs it

  1. Python runs the lines of the try block.
  2. If an error happens, the rest of the try block is skipped and Python jumps to except.
  3. If no error happens, the except block is skipped.
  4. In both cases the program continues below.

The same code with a value that works:

Python
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
How Python runs it
Error in tryNo error in try
Lines of try after the errorskippedall run
except blockrunsskipped
Code belowrunsruns

2.3With input from the user

Python
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:

Python
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

Read a text. Print the number plus 1, or 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
Python
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:

Python
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

Python
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:

Python
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:

Python
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.

Python
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:

Python
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:

Python
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.

Do not hide errors
FormCatchesUse it
except ValueError:one typemost of the time
except (ValueError, KeyError):the listed typesthe same reaction for several types
except ValueError as error:one type, and gives the messagewhen you want to show or save the explanation
except Exception as error:almost everythingas the last block, and always print the message
except:everythingavoid it

Try it yourself

Given 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
Three things can go wrong, so three except blocks: ValueError, IndexError, ZeroDivisionError.
Show the solution
Python
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

  • else runs only if no error happened in try.
  • finally runs always, with or without an error.
Python
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").

else and finally
BlockRuns whenTypical use
tryalways (until an error happens)the code that may fail
exceptan error of that type happeneda message, a default value
elseno error happenedthe work that needs the result of try
finallyalwaysa 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.

Python
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

Python
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.

  1. try:
  2. number = int(text)runs
  3. print("Converted:", number)runs
  4. except ValueError:
  5. print("Not a number")skipped
  6. else:
  7. print("No error")runs
  8. finally:
  9. print("Done")runs
  10. 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

Convert 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
Four blocks in this order: try, except ValueError, else, finally. Only the conversion goes into try.
Show the solution
Python
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

Python
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:

Python
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.

Python
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?

Skipping the bad values of a list
Where is the try?A bad valueResult
inside the loopthat one value is skippedthe loop goes on with the next value
around the loopthe loop endsthe values after it are never processed

5.3A function that returns a default

Python
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:

Python
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

Read a line of values separated by spaces and print how many of them are whole numbers.
Show a hint
A counter and a loop with try inside it. Add 1 to the counter after int(value) worked.
Show the solution
Python
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:

Python
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:

Python
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:

Choosing the type
ProblemType to raise
the value is not acceptable (negative age, empty name)ValueError
the type is wrong (text where a number is needed)TypeError
Python
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:

Python
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.

Check first, or try?
Use if whenUse try when
the check is simple: key in d, b != 0, len(items) > 0you cannot know before you try: is this text a number?
the problem is a normal, frequent casethe problem is rare

Good habits

  • Keep the try block small: only the lines that may fail.
  • Name the error type.
  • Do not use try to 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

Write a function 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
First line of the function: if len(numbers) == 0: then raise ValueError("the list is empty").
Show the solution
Python
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

Python
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.
  • with closes the file by itself when the block ends.
  • write takes only text, and it does not start a new line by itself: add \n at the end of each line. Convert numbers with str().

7.2Reading

Every example that reads a file first creates it, so each example works on its own.

Python
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:

Python
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():

Python
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

Modes
ModeMeaningIf the file existsIf the file does not exist
"r"read (the default)reads itFileNotFoundError
"w"writeerases it, then writescreates it
"a"appendkeeps it, writes at the endcreates it
Python
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

Write the numbers 1 to 5 to a file, one per line. Then read the file and print the sum.
Show a hint
Writing: a loop over range(1, 6) with file.write(str(number) + "\n"). Reading: a loop over the lines with int(line).
Show the solution
Python
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

Create a file with three names, one per line (Aylin, Murad, Leyla). Append two more names (Kamran, Nigar), then print every name with its line number, like 1: Aylin.
Show a hint
Three steps with three modes: "w" to create, "a" to add, and no mode to read. Count the lines with a variable that starts at 1.
Show the solution
Python
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 + 1

Output

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 wrong

Right

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 continues

Real 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 zero

The 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 number

Right

a = int("8")
try:
    b = int("x")
except ValueError:
    print("b is not a number")

# prints: b is not a number

You 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: 10

Right

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: 2

The 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 problem

Right

try:
    print(10 / 0)
except ZeroDivisionError:
    print("Cannot divide by zero")
except Exception:
    print("Some problem")

# prints: Cannot divide by zero

The specific block never runs. Specific types first.

An empty reaction (pass)

Wrong

try:
    amount = int("abc")
except ValueError:
    pass

print("Done")

# prints: Done

Right

text = "abc"
try:
    quantity = int(text)
except ValueError:
    quantity = 1

print("Quantity:", quantity)

# prints: Quantity: 1

The 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: 0

NameError 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: -5

Right

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 negative

The 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: Tuesday

Right

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, Tuesday

The 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 line

Right

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 line

One long line, or empty lines when printing. \n when writing, strip() when reading.

A variable that was never set:

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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

Python
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. 1.Read a text from the user. Print the number doubled, or not a number if it is not a whole number.Examples: 21 gives 42abc gives not a number-4 gives -8
    Show a hint
    Put int(text) inside try. The error type for a text that is not a whole number is ValueError.
    Show one possible solution
    Python
    text = input()
    try:
        print(int(text) * 2)
    except ValueError:
        print("not a number")

    Output

    42
  2. 2.Read two whole numbers from one line and print the first divided by the second, or cannot divide by zero.Examples: 10 2 gives 5.07 0 gives cannot divide by zero0 5 gives 0.0
    Show a hint
    The division is the risky line. Its error type is ZeroDivisionError.
    Show one possible solution
    Python
    a, b = map(int, input().split())
    try:
        print(a / b)
    except ZeroDivisionError:
        print("cannot divide by zero")

    Output

    5.0
  3. 3.Given items = ["a", "b", "c"], read an index from the user and print the item at that index, or no such index.Examples: 0 gives a2 gives c5 gives no such index
    Show a hint
    items[index] gives an IndexError when the index does not exist. A negative index such as -1 is valid.
    Show one possible solution
    Python
    items = ["a", "b", "c"]
    index = int(input())
    try:
        print(items[index])
    except IndexError:
        print("no such index")

    Output

    a
  4. 4.Given prices = {"apple": 1.5, "bread": 0.8}, read a product name and print its price, or no such product. Use try/except.Examples: apple gives 1.5bread gives 0.8kiwi gives no such product
    Show a hint
    prices[product] gives a KeyError when the key is missing.
    Show one possible solution
    Python
    prices = {"apple": 1.5, "bread": 0.8}
    product = input()
    try:
        print(prices[product])
    except KeyError:
        print("no such product")

    Output

    1.5
  5. 5.Read a text and print whole number, decimal number or not a number.Examples: 42 gives whole number3.5 gives decimal numberabc gives not a number
    Show a hint
    Try int(text) first. In its except block, try float(text) with a second try/except.
    Show one possible solution
    Python
    text = 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.

  1. 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 5 gives 45 21 2 3 gives 6 0a b gives 0 2
    Show a hint
    Two variables, total and skipped. The try goes inside the loop: add in try, count the skipped value in except.
    Show one possible solution
    Python
    values = 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
  2. 7.Write a function safe_divide(a, b) that returns the result, or None if b is zero.Examples: 10 2 gives 5.010 0 gives None0 3 gives 0.0
    Show a hint
    return a / b inside try, and return None inside except ZeroDivisionError:.
    Show one possible solution
    Python
    def 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
  3. 8.Write a function safe_int(text, default) that returns the text as a whole number, or default if it cannot be converted.Examples: 42 gives 42abc gives -1-8 gives -8
    Show a hint
    return int(text) inside try, and return default inside except ValueError:.
    Show one possible solution
    Python
    def safe_int(text, default):
        try:
            return int(text)
        except ValueError:
            return default
    
    text = input()
    print(safe_int(text, -1))

    Output

    42
  4. 9.Keep asking the user for a whole number from 1 to 5 until the input is valid. Then print ok and the number. Print nothing for the wrong answers.Examples: 3 gives ok 3abc, 9, 4 gives ok 40, 6, 1 gives ok 1
    Show a hint
    while True: with int(input()) inside try. In except ValueError: write continue. After the try, break when the number is from 1 to 5.
    Show one possible solution
    Python
    while True:
        try:
            number = int(input())
        except ValueError:
            continue
        if 1 <= number <= 5:
            break
    print("ok", number)

    Output

    ok 3
  5. 10.Read a text and an index (two lines). Print the character at that index. Print not a number if the index is not a whole number, and no such index if it is out of range.Examples: python, 0 gives ppython, 10 gives no such indexpython, x gives not a number
    Show a hint
    Two things can go wrong, so two except blocks: ValueError for the conversion and IndexError for the index.
    Show one possible solution
    Python
    text = 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.

  1. 11.Write a function check_age(age) that raises a ValueError with a message if the age is below 0 or above 120, and returns the age otherwise. Read an age and print ok, or the message. The message is age must be between 0 and 120.Examples: 20 gives ok-1 gives age must be between 0 and 120121 gives age must be between 0 and 120
    Show a hint
    Inside the function: if age < 0 or age > 120: then raise ValueError("age must be between 0 and 120"). Outside: call it in try, and print the error in except ValueError as error:.
    Show one possible solution
    Python
    def 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
  2. 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:78 gives {'Aylin': 85, 'Leyla': 78} 1A:1 gives {'A': 1} 0A B:2 gives {'B': 2} 1
    Show a hint
    For every record, name, grade = record.split(":") and int(grade) go inside try. Both problems (no colon, a grade that is not a number) are a ValueError.
    Show one possible solution
    Python
    records = 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
  3. 13.Write a function parse_time(text) that takes a text like 14:30 and returns the minutes since midnight. It raises a ValueError if 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, or invalid time.Examples: 14:30 gives 87000:00 gives 023:59 gives 1439
    Show a hint
    Split the text at ":" into two variables and convert both with int(). A wrong form already gives a ValueError by itself. For numbers out of range, raise ValueError(...) yourself.
    Show one possible solution
    Python
    def 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
  4. 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 x gives ([10, 30], ['abc', 'x'])1 2 gives ([1, 2], [])a gives ([], ['a'])
    Show a hint
    Two empty lists. In the loop, good.append(int(value)) inside try and bad.append(value) inside except ValueError:. Return both: return good, bad.
    Show one possible solution
    Python
    def 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'])
  5. 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 inside try. An empty line is a ValueError too.
    Show one possible solution
    Python
    with 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.

Question 1

1.What is printed before this program stops?

print("A")
x = int("z")
print("B")

Question 2

2.Which error does this line cause?

print([1, 2, 3][3])

Question 3

3.What does this print?

try:
    print("a", end=" ")
    int("x")
    print("b", end=" ")
except ValueError:
    print("c", end=" ")
print("d")

Question 4

4.What happens when this runs?

try:
    x = 10 / 0
except ValueError:
    print("caught")

Question 5

5.What does this print?

try:
    n = int("5")
except ValueError:
    print("bad", end=" ")
else:
    print("good", end=" ")
finally:
    print("end")

Question 6

6.When does a finally block run?

Question 7

7.What does this print?

values = ["1", "x", "3"]
total = 0
for v in values:
    try:
        total = total + int(v)
    except ValueError:
        pass
print(total)

Question 8

8.What does this print?

values = ["1", "x", "3"]
total = 0
try:
    for v in values:
        total = total + int(v)
except ValueError:
    pass
print(total)

Question 9

9.What does raise ValueError("too short") do?

Question 10

10.What does this print?

def f(x):
    return 10 / x

try:
    print(f(0))
except ZeroDivisionError:
    print("handled")

Question 11

11.Which line opens a file so that new text is added at the end?

Question 12

12.What is the problem with an except: block that names no error type?

0 of 12 answered.

12Quick summary

Quick summary
ConceptWhat it doesExample
Exceptionan error while the program runsValueError, KeyError, ZeroDivisionError
try / excepthandles an error instead of stoppingexcept ValueError:
Several typesone block each, or a tupleexcept (ValueError, KeyError):
as errorgives access to the messageexcept ValueError as error:
Exceptionalmost every error, as the last blockexcept Exception as error:
elseruns if no error happenedelse: print(number)
finallyruns alwaysfinally: print("done")
try in a loopone bad value does not stop the othersfor v in values: try: ...
raisecreates an error yourselfraise ValueError("too short")
with open(name, mode)opens a file and closes it by itselfwith open("a.txt", "w") as file:
"r" / "w" / "a"read / write (erases) / appendopen("log.txt", "a")
write / readtext into a file / the whole filefile.write("hi\n"), file.read()