Hello, brilliant builder! In Module 5, you learned about classes, objects, and files. Now, we are going to explore even more powerful tools in Python – dictionaries, tuples, and error handling.
Imagine you have a phonebook. You look up a name and find a phone number. That is a dictionary – it stores pairs of keys and values. A tuple is like a list, but it cannot be changed – it's a fixed collection.
Sometimes, your program might make a mistake – like trying to divide by zero. Instead of crashing, we can handle errors gracefully and keep the program running.
By the end of this module, you will be able to use these tools to write more efficient and reliable programs. Let's dive in!
After this module, you will be able to:
try/except.Amara ran a small market stall in Lagos. She sold fruits and vegetables. She had a list of items and their prices. But it was hard to find prices quickly – she had to scan the whole list.
Her friend, a software engineer, said: “Use a dictionary! Instead of a list, you can look up the price directly by the item name.”
Amara created a dictionary where the item name was the key and the price was the value. Now she could find any price instantly – like magic!
She also wanted to keep track of her daily sales in a tuple – a fixed record of the day's total. And when she made a mistake entering a price, she learned to handle errors so her program wouldn't crash.
Now, let's learn how to use these tools in Python!
Definition: A dictionary is a collection of key-value pairs. You use a key to look up its value – like a phonebook.
Why is it important? Dictionaries let you store and retrieve data quickly using a unique key.
Simple explanation: Think of a dictionary (the book). You look up a word (the key) and you find its meaning (the value).
Real‑life example: A phonebook – names (keys) and phone numbers (values).
School example: A student ID (key) and the student's name (value).
Home example: A recipe book – dish name (key) and instructions (value).
Nigerian example: A market price list – item name (key) and price (value).
Illustration:
+----------------------+
| Dictionary |
+----------------------+
| Key | Value |
+---------+------------+
| "apple" | 200 |
| "orange"| 150 |
| "banana"| 100 |
+---------+------------+
Mini summary: A dictionary stores key-value pairs for fast lookup.
Definition: You create a dictionary using curly braces {} and separate keys and values with colons :.
Why is it important? This is the syntax you need to create dictionaries in Python.
Simple explanation: You write {"key": "value"}.
Real‑life example: {"Chidi": "08012345678", "Ama": "08087654321"}
School example: {"Math": 85, "English": 90, "Science": 78}
Home example: {"dad": "John", "mom": "Mary", "sister": "Ada"}
Nigerian example: {"Lagos": 15, "Abuja": 10, "Kano": 8} (city population in millions).
Illustration:
prices = {
"apple": 200,
"orange": 150,
"banana": 100
}
print(prices["apple"]) # 200
Mini summary: Use {} to create dictionaries with key-value pairs.
Definition: You access a value by using its key in square brackets [].
Why is it important? This is how you get the data you need from a dictionary.
Simple explanation: Like looking up a word in a dictionary – you use the word to find the meaning.
Real‑life example: phonebook["Chidi"] returns Chidi's phone number.
School example: grades["Math"] returns your Math grade.
Home example: family["dad"] returns your dad's name.
Nigerian example: prices["apple"] returns the price of an apple.
Illustration:
prices = {"apple": 200, "orange": 150}
print(prices["apple"]) # 200
Mini summary: Use the key in [] to get its value.
Definition: You can add a new key-value pair or change an existing value by assigning to the key.
Why is it important? Dictionaries are dynamic – you can update them as needed.
Simple explanation: Like adding a new contact to your phone or updating a phone number.
Real‑life example: Adding a new friend to your contact list.
School example: Updating a grade after a test.
Home example: Adding a new chore to the chore list.
Nigerian example: Adding a new item to your market price list.
Illustration:
prices = {"apple": 200}
prices["orange"] = 150 # adding
prices["apple"] = 250 # changing
print(prices) # {'apple': 250, 'orange': 150}
Mini summary: You can add or change items by assigning to a key.
Definition: You can remove a key-value pair using del or pop().
Why is it important? Sometimes you need to delete data that is no longer needed.
Simple explanation: Like deleting a contact from your phone.
Real‑life example: Removing an old friend from your contact list.
School example: Removing a subject you no longer take.
Home example: Removing a chore that is done.
Nigerian example: Removing an item that is out of stock.
Illustration:
prices = {"apple": 200, "orange": 150}
del prices["apple"] # removes apple
prices.pop("orange") # removes orange
print(prices) # {}
Mini summary: Use del or pop() to remove items.
Definition: You can loop through keys, values, or both using for loops.
Why is it important? This lets you process all the data in a dictionary.
Simple explanation: Like going through each contact in your phonebook.
Real‑life example: Printing all contacts in your phone.
School example: Displaying all your grades for each subject.
Home example: Listing all the chores for the week.
Nigerian example: Displaying all items in a market price list.
Illustration:
prices = {"apple": 200, "orange": 150}
for item, price in prices.items():
print(item, "costs", price, "naira")
Mini summary: Use .items() to loop through key-value pairs.
Definition: A tuple is a collection of items that is immutable – it cannot be changed after creation.
Why is it important? Tuples are useful for data that should not change, like days of the week.
Simple explanation: A tuple is like a list, but you cannot add, remove, or change items.
Real‑life example: The days of the week – Monday to Sunday.
School example: The subjects you take this term – they are fixed.
Home example: Your family members – a fixed set.
Nigerian example: The states in the South‑East – fixed.
Illustration:
days = ("Monday", "Tuesday", "Wednesday")
print(days[0]) # Monday
# days[0] = "Sunday" # ERROR! Cannot change
Mini summary: Tuples are fixed collections that cannot be changed.
Definition: Use a list when you need to change items; use a tuple when you need a fixed collection.
Why is it important? Choosing the right type makes your program more efficient and safer.
Simple explanation: If you have a list of things that might change, use a list. If they are fixed, use a tuple.
Real‑life example: Your shopping list (list) – you add and remove items. The days of the week (tuple) – fixed.
School example: Your class schedule (list) – it can change. The school subjects (tuple) – fixed.
Home example: Your chores (list) – they change. Your family members (tuple) – fixed.
Nigerian example: Items in your cart (list) – they change. The regions in Nigeria (tuple) – fixed.
Illustration:
shopping_list = ["bread", "milk", "eggs"] # list – can change
weekdays = ("Mon", "Tue", "Wed") # tuple – fixed
Mini summary: Lists are for changeable data; tuples are for fixed data.
Definition: Error handling is a way to catch and manage errors so your program doesn't crash.
Why is it important? It makes your program robust – it can handle unexpected situations.
Simple explanation: Like wearing a helmet – it protects you if you fall.
Real‑life example: A vending machine – if you insert a wrong coin, it gives it back instead of breaking.
School example: If you make a mistake on a test, your teacher helps you correct it instead of failing you instantly.
Home example: If you spill water, you clean it up – you don't panic.
Nigerian example: A POS machine – if it can't read your card, it says "try again" instead of crashing.
Illustration:
try:
result = 10 / 0 # This will cause an error!
except ZeroDivisionError:
print("Cannot divide by zero!")
Mini summary: Error handling lets your program recover from mistakes.
try/except BlockDefinition: try and except are used to test a block of code for errors and handle them.
Why is it important? It allows you to catch specific errors and respond appropriately.
Simple explanation: You try to do something, and if it fails, you except (catch) the error and do something else.
Real‑life example: You try to open a door. If it's locked, you use a key (instead of breaking the door).
School example: You try to answer a question. If you don't know, you raise your hand and ask for help.
Home example: You try to cook a new recipe. If it doesn't taste good, you add salt instead of throwing it away.
Nigerian example: You try to withdraw money from an ATM. If the amount is too high, it shows "insufficient balance" instead of crashing.
Illustration:
try:
number = int(input("Enter a number: "))
print("You entered", number)
except ValueError:
print("That's not a valid number!")
Mini summary: try runs code; except catches and handles errors.
Definition: You can catch specific types of errors (like ValueError or ZeroDivisionError) to handle them differently.
Why is it important? It lets you give the user a helpful message instead of a technical error.
Simple explanation: Like a lifeguard – they have different ways to help if you're drowning vs. if you're just tired.
Real‑life example: If a file is not found, you can create it instead of crashing.
School example: If a student enters an invalid answer, the teacher prompts them to try again.
Home example: If you can't find a tool, you look for it instead of giving up.
Nigerian example: If a transaction fails, the app shows a message like "network error" instead of crashing.
Illustration:
try:
result = 10 / int(input("Enter divisor: "))
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Please enter a number!")
Mini summary: Catch specific errors to give better feedback.
else and finally ClausesDefinition: else runs if no error occurred; finally runs always, whether an error occurred or not.
Why is it important? They help you structure your code neatly and ensure cleanup actions happen.
Simple explanation: else is like “if everything goes well, do this”. finally is like “no matter what, do this”.
Real‑life example: When you try to cook: else – enjoy the meal; finally – clean the kitchen.
School example: When you write a test: else – get a grade; finally – return the paper.
Home example: When you do laundry: else – fold clothes; finally – put detergent away.
Nigerian example: When you shop: else – pay; finally – leave the store.
Illustration:
try:
result = 10 / 2
except ZeroDivisionError:
print("Error!")
else:
print("Result:", result)
finally:
print("Done.")
Mini summary: else runs on success; finally always runs.
Definition: You can use raise to trigger an error on purpose when something is wrong.
Why is it important? It lets you enforce rules in your program – like checking that a value is valid.
Simple explanation: Like a teacher saying “Stop!” if you break a rule.
Real‑life example: A vending machine rejects a fake coin.
School example: A teacher rejects an assignment without a name.
Home example: A parent says “No” if you want candy before dinner.
Nigerian example: A bank app raises an error if you try to transfer more than your balance.
Illustration:
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative!")
print("Age is", age)
check_age(10) # works
# check_age(-5) # raises an error
Mini summary: Use raise to trigger errors when something is wrong.
Definition: When working with files, you can use error handling to manage missing files or permissions.
Why is it important? It prevents your program from crashing if a file doesn't exist.
Simple explanation: If you try to read a file that doesn't exist, you can create it instead of crashing.
Real‑life example: If a book is missing from the library, you order a new one.
School example: If your notebook is lost, you get a new one.
Home example: If you can't find a recipe, you search online.
Nigerian example: If a customer's record is not in the system, you create a new one.
Illustration:
try:
file = open("data.txt", "r")
content = file.read()
file.close()
except FileNotFoundError:
print("File not found. Creating a new one.")
file = open("data.txt", "w")
file.write("New file created.")
file.close()
Mini summary: Use error handling to manage file operations safely.
Definition: A real program uses dictionaries, tuples, and error handling together to solve problems.
Why is it important? This is how professional software engineers build robust applications.
Simple explanation: You use dictionaries to store data, tuples for fixed data, and error handling to manage mistakes.
Real‑life example: A weather app uses a dictionary to store city‑temperature pairs, tuples for fixed data like months, and error handling for network issues.
School example: A gradebook uses a dictionary for student grades, a tuple for subjects, and error handling for invalid inputs.
Home example: A recipe app uses a dictionary for recipes, a tuple for ingredients that are always needed, and error handling for missing files.
Nigerian example: A banking app uses dictionaries for customer data, tuples for fixed currency types, and error handling for transaction errors.
Illustration:
# Dictionary for prices
prices = {"apple": 200, "orange": 150}
# Tuple for fixed categories
categories = ("Fruits", "Vegetables")
# Error handling for input
try:
item = input("Enter item: ")
print("Price:", prices[item])
except KeyError:
print("Item not found!")
Mini summary: Combining dictionaries, tuples, and error handling creates powerful programs.
| Word | Simple Definition |
|---|---|
| Dictionary | A collection of key-value pairs. |
| Key | A unique identifier used to look up a value. |
| Value | The data associated with a key. |
| Tuple | A fixed, unchangeable collection. |
| Immutable | Cannot be changed after creation. |
| Error Handling | Managing errors to prevent crashes. |
| try/except | Blocks used to catch and handle errors. |
| raise | Trigger an error on purpose. |
| KeyError | Error when a key is not found in a dictionary. |
| ValueError | Error when a value is invalid. |
{key: value}.dict[key].dict[new_key] = value.del dict[key].for key, value in dict.items():.try block.except ErrorType:.else block for success.finally block for cleanup.raise errors to enforce rules.This module introduces powerful data structures and error handling. Use real‑world analogies (phonebooks, contact lists) to explain dictionaries. Emphasise the immutability of tuples. For error handling, demonstrate common errors and how to catch them. Encourage students to write programs that handle errors gracefully.
Encourage your child to think about data as key‑value pairs – e.g., “What is the key for your phone number?”. Discuss the difference between changeable (list) and fixed (tuple) data. Talk about how error handling is like planning for mistakes – it's a sign of a good engineer.
try/except to catch errors.KeyError – when accessing a key that doesn't exist.== instead of = when adding items – assignment vs comparison.Exception – it's better to catch specific errors.finally for cleanup – like closing files..get() to safely access dictionary values (returns None if key missing).except.finally or with.
+--------+ +---------+
| Key | --> | Value |
+--------+ +---------+
| "apple"| | 200 |
| "orange"| | 150 |
| "banana"| | 100 |
+--------+ +---------+
| Feature | List | Tuple | Dictionary |
|---|---|---|---|
| Mutable? | Yes | No | Yes |
| Ordered? | Yes | Yes | Yes (Python 3.7+) |
| Access by | Index | Index | Key |
| Example | [1,2,3] | (1,2,3) | {'a':1} |
+-------------------+
| try block |
| (risky code) |
+--------+----------+
|
+--------v----------+
| Error occurred? |
+---+------------+--+
| |
Yes No
| |
v v
+--------+ +--------+
| except | | else |
| handle | | (done) |
+--------+ +--------+
| |
+------+-----+
|
+------v-----+
| finally |
| (clean up) |
+------------+
You have completed Module 6 – you are now equipped with some of the most powerful tools in Python! You learned about dictionaries – key‑value stores for fast data access. You discovered tuples – fixed collections that are safe and efficient. You also learned error handling – how to make your programs robust and user‑friendly.
These concepts are used in almost every real‑world application – from web apps to games to banking systems. You are building a solid foundation for advanced software engineering.
Keep exploring and practicing – you are doing amazing!
dict[key].try/except? A way to catch and handle errors.KeyError? An error that occurs when you try to access a key that doesn't exist..get(key) – it returns None if the key is missing.raise do? It triggers an error on purpose.try/except block?KeyError?else clause in error handling?finally clause?raise an error?try/except is used for loops. (False)KeyError occurs when you try to access a missing key. (True)finally runs only if an error occurs. (False – it always runs)raise to trigger an error on purpose. (True)[]{}()<>tryexceptfinallyraiseKeyError?raise do?else clause do in error handling?finally clause do?dict[key]dict.get(key)dict.pop(key)del dict[key]| Term | Definition |
|---|---|
| 1. Dictionary | A. A fixed, unchangeable collection |
| 2. Tuple | B. A collection of key‑value pairs |
| 3. KeyError | C. Used to catch errors |
| 4. except | D. Error when a key is missing |
| 5. raise | E. Trigger an error on purpose |
Answers: 1‑B, 2‑A, 3‑D, 4‑C, 5‑E
KeyError?Scenario 1: You are building a dictionary to store student grades. The keys are student names, and the values are grades. Write code to add a new student, update a grade, and safely retrieve a grade.
Scenario 2: You are reading a file that might not exist. Write code that handles the FileNotFoundError and creates the file if it doesn't exist.
In groups, create a dictionary of 10 items and their prices (in naira). Write functions to add, remove, and update items. Then, write a function that displays all items and prices. Use error handling to manage invalid inputs.
Write a Python program that creates a tuple of your favourite foods. Then, create a dictionary that maps each food to its price. Use error handling to check if a user‑entered food is in the dictionary.
Build a Simple Phonebook: Create a program that uses a dictionary to store contacts (name → phone number). Implement functions to add, delete, update, and search for contacts. Use error handling for cases like a contact not found or invalid input.
Write a Python program that reads a text file containing key‑value pairs (one per line, separated by commas). Store them in a dictionary. Then, allow the user to search for a key and display its value. Handle errors if the file doesn't exist or a key is missing.
Write a Python program that creates a nested dictionary – a dictionary where the values are also dictionaries. For example, a dictionary of students, where each student has a dictionary of subjects and grades. Implement functions to add a student, add a grade, and calculate the average grade for a student. Use error handling for all operations.
Fill‑in‑the‑Blank: 1. dictionary, 2. key, 3. tuple, 4. immutable, 5. Error handling, 6. try/except, 7. KeyError, 8. raise, 9. else, 10. finally.
True/False: 1F, 2F, 3F, 4T, 5F, 6T, 7F, 8T, 9T, 10F.
Multiple Choice: 1B, 2B, 3B, 4B, 5B, 6A, 7B, 8B, 9B, 10C, 11B, 12B, 13B, 14D, 15B.
In Module 7, you will learn about recursion, higher‑order functions, and working with JSON. These are advanced topics that will take your Python skills to the next level. To prepare, think about problems that can be broken down into smaller versions of themselves – like searching a folder inside a folder.
You are on an incredible journey – keep going! See you in Module 7!