Module 10 · Python for Beginners
Errors, Modules and Next Steps
Handle errors gracefully with try and except, raise your own, use Python's built-in modules (random, datetime, statistics), install more with pip, and plan what to learn next.
About 30 minutes
Open in ColabEvery example as a notebook you can run, edit and save to your Google Drive.
Reading a traceback
When Python hits an error it can't handle, it stops and prints a traceback: the trail of lines it was running. Read it from the bottom:
def average(scores):
return sum(scores) / len(scores)
print(average([]))Output
Traceback (most recent call last):
File "<ipython-input-1>", line 4, in <module>
print(average([]))
File "<ipython-input-1>", line 2, in average
return sum(scores) / len(scores)
ZeroDivisionError: division by zero- The last line says what went wrong:
ZeroDivisionError: division by zero. - The lines above show where: line 2, inside
average, called from line 4. - So:
averagewas given an empty list, andlen([])is 0.
The errors you've met in this course:
| Error | Usually means |
|---|---|
SyntaxError | Python can't read the line: a missing colon, quote or bracket |
IndentationError | a block isn't indented, or indented inconsistently |
NameError | a misspelt name, or a cell that hasn't been run |
TypeError | the wrong type: text plus a number, or a missing argument |
ValueError | the right type but an impossible value: int("forty") |
IndexError | a list or string position that doesn't exist |
KeyError | a dictionary key that doesn't exist |
ZeroDivisionError | dividing by zero |
Handling errors with try and except
Some errors aren't bugs in your code: they come from the outside world. A user types "forty" instead of 40; a file is missing. try and except let your program handle the problem instead of crashing:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
'forty' isn't a number. Please type digits, like 40.- Python runs the
tryblock. - If an error happens, it jumps to the matching
exceptblock instead of stopping. - If no error happens, the
exceptblock is skipped.
Try it with a valid value:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
Next year you'll be 41Catch specific errors
Name the error you expect. You can have several except blocks for different errors:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
67.33333333333333
0
The list must contain numbers only.
Noneelse and finally
Two optional extras:
elseruns only if no error happened.finallyruns always, error or not, which is useful for clean-up.
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
Recorded ₦2,500
Check completeA loop that keeps asking
Combined with a loop, try lets a program keep asking until it gets a valid answer. (This uses input, so run it in Colab rather than reading it here.)
while True:
try:
age = int(input("How old are you? "))
break
except ValueError:
print("Please type a whole number.")
print(f"Thanks. You're {age}.")while True loops forever, and break leaves the loop once int() succeeds.
Raising your own errors
Your functions can raise an error when they're given something that makes no sense, rather than quietly returning a wrong answer:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
34000.0
Error: Discount must be between 0 and 100, not 150except ValueError as error gives you the error object, so you can print its message.
Modules: using code others have written
A module is a file of ready-made functions. Python comes with hundreds (the standard library). Bring one in with import, then use its functions with a dot:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
63.8
67Ways to import:
| Write | Then use |
|---|---|
import statistics | statistics.mean(x) |
import statistics as st | st.mean(x) (a shorter name) |
from statistics import mean | mean(x) (just that function) |
random
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
Musa
5random.choice picks an item; random.randint(1, 6) rolls a die. Without random.seed, you'd get different results each run, which is the point. random.shuffle(names) mixes a list up.
datetime
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
83 days until the exam
Monday 07 December 2026Subtracting two dates gives the time between them; strftime formats a date for people. date.today() gives today's date.
Installing more: pip
Beyond the standard library, thousands of free packages are published for Python. You install them with pip. In Colab, run it in a cell with ! in front:
Shell (bash)
!pip install requestsThe most important ones for data work, pandas (tables), matplotlib (charts) and numpy (numbers), are already installed in Colab:
import pandas as pd
data = pd.DataFrame({"name": ["Adaeze", "Musa"], "score": [67, 81]})
print(data)You'll use them in the next course.
What to learn next
You now know the core of Python: values and types, text and numbers, decisions, lists, loops, dictionaries, functions, errors and modules. That's the same foundation every Python programmer builds on. Where to go from here:
| If you want to... | Take |
|---|---|
| analyse real data with tables and charts | Python for Data (short) or Python for Data Analytics |
| build programs properly, with tests | Software Engineering with Python |
| work with AI models | Generative AI Engineering |
| keep your code safe and shared | Git and GitHub |
Summary
| You want to... | Write |
|---|---|
| handle an expected error | try: ... except ValueError: ... |
| run code only if it worked | else: after except |
| run clean-up code always | finally: |
| stop on bad input | raise ValueError("message") |
| use a module | import statistics then statistics.mean(x) |
| pick at random | random.choice(items) |
| days between dates | (date2 - date1).days |
| install a package in Colab | !pip install name |
Try it
Practice
What is the median of [67, 81, 54, 72, 45]? Use statistics.median.
Practice
How many days are there from date(2026, 9, 15) to date(2026, 12, 7)?
Practice
Which error does int("twelve") raise? Type its name.
Task
10 minWrite a function parse_amount(text) that turns text like "12,500" or " 4500 " into a number: strip spaces, remove commas, and convert with int() inside a try. If it can't be converted, catch the ValueError and return None. Test it with at least three values, including one that fails. Paste your code.
Your work is checked for
- A function called parse_amount
- Uses try and except
- Catches ValueError specifically
- Strips spaces
- Removes commas
- Returns None when it fails
- Tests it at least three times
Earn your badge
Take the module check
Questions on this module. Pass and you earn the Python Errors and Modules badge, free.
Create a free account to earn the badge