Module Two: Diving Deeper into Python โ Dictionaries, Files, and More!
Welcome back, young coder! You did an amazing job in Module One. You learned the basics โ variables, data types, input, if/else statements, loops, lists, and functions. Now, in Module Two, we will go deeper and explore even more exciting things in Python.
We will learn about dictionaries โ a special way to store information using keys and values. We will learn about sets โ a collection that only keeps unique items. We will discover how to read from and write to files so that our programs can save data forever. We will learn how to handle errors so our programs don't crash. We will also learn how to write functions that return values and even create our own classes to build our own objects! This module is full of new and exciting concepts. Let's dive in!
After completing this module, you will be able to:
Chidi's Phone Book
Chidi had a problem. He had many friends and family members, and he kept forgetting their phone numbers. He tried using a list, but it was hard to find the right number quickly. He had to remember which position each person was in.
His teacher said, "Chidi, Python has something called a dictionary. It lets you store information using a key (like a person's name) and a value (like their phone number). You can find the number just by knowing the name!"
Chidi was amazed. He wrote:
phone_book = {
"Ada": "080-1234-5678",
"Chidi": "080-8765-4321",
"Bola": "080-5555-5555"
}
print(phone_book["Ada"]) # Prints the phone number
He could now find anyone's number instantly! Chidi learned that dictionaries are like real phone books โ they let you find information using a key.
Before we start new things, let's quickly review what we learned in Module One.
We learned:
input() to get user input.if/else to make decisions.while and for loops to repeat code.def.#.You have a strong foundation. Now, let's build on it!
Definition: A dictionary is like a real-life dictionary or phone book. It stores information using a key and a value. You give it a key, and it gives you the value.
Why it's important: Dictionaries make it easy to find information quickly. You don't have to search through a list โ you just use the key!
Simple explanation: Think of a dictionary like a locker room. Each locker has a number (the key) and inside the locker is something (the value). You use the number to open the right locker.
Real-life example: A phone book: name (key) โ phone number (value).
School example: Student ID (key) โ student name (value).
Home example: Person's name (key) โ their age (value).
Nigerian example: A market vendor's stall number (key) โ the products they sell (value).
Illustration โ Code:
# A dictionary uses curly braces { } and colons :
phone_book = {
"Ada": "080-1234-5678",
"Chidi": "080-8765-4321",
"Bola": "080-5555-5555"
}
print(phone_book["Ada"]) # Prints: 080-1234-5678
Mini summary: Dictionaries store key-value pairs for fast lookups.
Definition: You can add, change, and delete items in a dictionary.
Why it's important: Dictionaries are flexible โ you can update them as your data changes.
Simple explanation: It's like having a whiteboard where you can write, erase, and change information.
Real-life example: Adding a new friend to your phone book.
School example: Adding a new student to a class list.
Home example: Changing a family member's phone number.
Nigerian example: A shop owner updates the price of an item.
Illustration โ Code:
phone_book = {} # Empty dictionary
# Adding items
phone_book["Ada"] = "080-1234-5678"
phone_book["Chidi"] = "080-8765-4321"
# Changing an item
phone_book["Ada"] = "080-9999-9999"
# Deleting an item
del phone_book["Chidi"]
# Getting all keys and values
print(phone_book.keys()) # Prints all keys
print(phone_book.values()) # Prints all values
Mini summary: You can add, change, and delete items in a dictionary.
Definition: You can use a for loop to go through all the items in a dictionary.
Why it's important: Looping helps you process all the data in a dictionary.
Simple explanation: It's like reading every entry in a phone book from start to finish.
Real-life example: Printing all contacts in a phone book.
School example: Printing all student names and their grades.
Home example: Listing all family members and their ages.
Nigerian example: Printing all products and their prices from a market list.
Illustration โ Code:
phone_book = {
"Ada": "080-1234-5678",
"Chidi": "080-8765-4321"
}
# Loop through keys
for name in phone_book:
print(name + " -> " + phone_book[name])
# Loop through both keys and values
for name, number in phone_book.items():
print(name + " has number " + number)
Mini summary: Use for loops to go through all items in a dictionary.
Definition: A set is a collection of items that are unique โ it doesn't allow duplicates. A set uses curly braces { } but without colons.
Why it's important: Sets are useful when you want to remove duplicates or check if an item exists.
Simple explanation: A set is like a bag of marbles where each marble is unique โ you can't have two identical marbles.
Real-life example: A list of the unique classes you have in a week.
School example: All the different subjects taught in your school.
Home example: All the different types of fruit in your kitchen.
Nigerian example: All the different states you have visited.
Illustration โ Code:
# A set uses curly braces with no colons
fruits = {"Mango", "Orange", "Banana", "Mango"}
# Duplicates are removed automatically
print(fruits) # Prints: {"Mango", "Orange", "Banana"}
# Adding an item
fruits.add("Apple")
# Checking if an item exists
if "Mango" in fruits:
print("Mango is in the set!")
# Removing an item
fruits.remove("Orange")
Mini summary: Sets store unique items and remove duplicates automatically.
Definition: You can perform operations on sets โ like union (combine), intersection (common items), and difference (items in one but not the other).
Why it's important: These operations help you compare and combine collections.
Simple explanation: It's like comparing two lists of friends to see who is in both.
Real-life example: Finding common members of two clubs.
School example: Finding students who are in both the music club and the art club.
Home example: Finding common items in two shopping lists.
Nigerian example: Finding markets that sell both yams and cassava.
Illustration โ Code:
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
# Union - all items from both sets
print(set_a | set_b) # {1, 2, 3, 4, 5, 6}
# Intersection - items in both sets
print(set_a & set_b) # {3, 4}
# Difference - items in set_a but not set_b
print(set_a - set_b) # {1, 2}
Mini summary: Sets allow union, intersection, and difference operations.
Definition: Reading from a file means getting data that is stored on your computer and bringing it into your program.
Why it's important: Files let you save data permanently. When you close your program, the data is still there.
Simple explanation: It's like opening a book and reading what's written inside.
Real-life example: A program reads a list of names from a file.
School example: A program reads student grades from a file.
Home example: A program reads a shopping list from a file.
Nigerian example: A program reads a price list from a file.
Illustration โ Code:
# Reading from a file
file = open("data.txt", "r") # "r" means read mode
content = file.read()
print(content)
file.close() # Always close the file
Mini summary: open() lets you read data from a file.
Definition: Writing to a file means saving data from your program to a file on your computer.
Why it's important: You can save user data, results, or anything else permanently.
Simple explanation: It's like writing in a notebook and saving it for later.
Real-life example: A program saves a user's settings.
School example: A program saves test scores.
Home example: A program saves a shopping list.
Nigerian example: A program saves sales records.
Illustration โ Code:
# Writing to a file
file = open("output.txt", "w") # "w" means write mode
file.write("Hello, World!\n")
file.write("This is a new line.\n")
file.close() # Always close the file
Mini summary: open() with "w" mode lets you write data to a file.
Definition: Error handling lets you catch errors so your program doesn't crash. You use try and except.
Why it's important: It makes your program more robust and user-friendly.
Simple explanation: It's like wearing a safety net in case you fall.
Real-life example: A program asks for a number. If the user types letters, instead of crashing, it says "Please enter a number."
School example: A program handles invalid test scores.
Home example: A program handles missing files.
Nigerian example: A program handles invalid PIN entries.
Illustration โ Code:
try:
number = int(input("Enter a number: "))
print("You entered:", number)
except ValueError:
print("That's not a valid number!")
Mini summary: try/except catches errors and prevents crashes.
Definition: Parameters are values that you pass into a function so it can work with different data.
Why it's important: Parameters make your functions flexible and reusable.
Simple explanation: It's like a recipe that lets you choose your own ingredients.
Real-life example: A function that greets a person: greet("Ada").
School example: A function that adds two numbers: add(5, 3).
Home example: A function that converts Celsius to Fahrenheit: convert(25).
Nigerian example: A function that converts Naira to Dollars: convert(5000).
Illustration โ Code:
def greet(name):
print("Hello, " + name + "!")
greet("Ada") # Prints: Hello, Ada!
greet("Chidi") # Prints: Hello, Chidi!
def add(a, b):
print(a + b)
add(5, 3) # Prints: 8
Mini summary: Functions with parameters work with different data.
Definition: A function can return a value back to where it was called. You use the return keyword.
Why it's important: Returning values lets you use the result of a function in other parts of your program.
Simple explanation: It's like asking a friend to do a calculation and then give you the answer.
Real-life example: A function that calculates the area of a rectangle and returns it.
School example: A function that calculates the average of scores.
Home example: A function that converts temperature and returns the result.
Nigerian example: A function that calculates tax and returns the amount.
Illustration โ Code:
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Prints: 8
def square(num):
return num * num
print(square(4)) # Prints: 16
Mini summary: Use return to send values back from a function.
Definition: A class is like a blueprint for creating objects. An object is an instance of a class. It has attributes (characteristics) and methods (things it can do).
Why it's important: Classes let you model real-world things in code โ like a car, a student, or a bank account.
Simple explanation: A class is like a cookie cutter. An object is the cookie you make with it.
Real-life example: A "Car" class can have attributes like colour and speed, and methods like drive and stop.
School example: A "Student" class can have attributes like name and grade, and methods like study.
Home example: A "Dog" class can have attributes like name and breed, and methods like bark.
Nigerian example: A "MarketVendor" class can have attributes like name and products, and methods like sell.
Illustration โ Code:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print("Hello, my name is " + self.name)
# Creating an object
ada = Student("Ada", 10)
ada.greet() # Prints: Hello, my name is Ada
chidi = Student("Chidi", 12)
chidi.greet() # Prints: Hello, my name is Chidi
Mini summary: Classes are blueprints for creating objects with attributes and methods.
Definition: Lists have many built-in methods that let you do things like sort, reverse, add, and remove items.
Why it's important: Methods make working with lists easy and efficient.
Simple explanation: It's like having a Swiss Army knife for lists โ many tools in one.
Real-life example: list.sort() sorts items alphabetically.
School example: list.append() adds a new student to a list.
Home example: list.remove() removes an item from a shopping list.
Nigerian example: list.reverse() reverses the order of items in a list.
Illustration โ Code:
fruits = ["Banana", "Apple", "Mango", "Orange"]
# Add an item
fruits.append("Pineapple")
# Remove an item
fruits.remove("Banana")
# Sort the list
fruits.sort()
# Reverse the list
fruits.reverse()
# Check the length
print(len(fruits))
print(fruits)
Mini summary: Lists have many built-in methods for manipulation.
Now let's use what we learned to build something useful!
Project: A Simple Contact Manager
We will build a program that lets the user:
Illustration โ Code:
# Simple Contact Manager using Dictionaries and Files
contacts = {}
filename = "contacts.txt"
# Load contacts from file
try:
file = open(filename, "r")
for line in file:
name, number = line.strip().split(",")
contacts[name] = number
file.close()
except:
print("No saved contacts found.")
def save_contacts():
file = open(filename, "w")
for name, number in contacts.items():
file.write(name + "," + number + "\n")
file.close()
while True:
print("\n===== CONTACT MANAGER =====")
print("1. Add Contact")
print("2. View All Contacts")
print("3. Search Contact")
print("4. Delete Contact")
print("5. Exit")
choice = input("Choose an option: ")
if choice == "1":
name = input("Enter name: ")
number = input("Enter phone number: ")
contacts[name] = number
save_contacts()
print("Contact added!")
elif choice == "2":
if contacts:
for name, number in contacts.items():
print(name + " -> " + number)
else:
print("No contacts found.")
elif choice == "3":
name = input("Enter name to search: ")
if name in contacts:
print(name + " -> " + contacts[name])
else:
print("Contact not found.")
elif choice == "4":
name = input("Enter name to delete: ")
if name in contacts:
del contacts[name]
save_contacts()
print("Contact deleted!")
else:
print("Contact not found.")
elif choice == "5":
print("Goodbye!")
break
else:
print("Invalid choice. Try again.")
Mini summary: Combining all the skills you learned to build a real project.
In this module, we learned:
You have now built a strong foundation in Python. You are ready for Level 2!
How to read and write files:
open("filename", "r") for reading..read() or loop through lines..close().open("filename", "w")..write().This module introduces several new concepts. Take it step by step. Use the contact manager project as a capstone. Encourage students to modify and expand the project. Pair programming can be helpful here.
Help your child think of real things that could be modelled as dictionaries, sets, or classes. For example, "What would a dictionary of your family members look like?" or "What are the unique games you own?"
self parameter in class methods.get() to safely access dictionary keys.with statements.+------------------------------------------+ | DICTIONARY | | +--------------------------------------+ | | | KEY | VALUE | | | |------------|-------------------------| | | | "Ada" | "080-1234-5678" | | | | "Chidi" | "080-8765-4321" | | | | "Bola" | "080-5555-5555" | | | +--------------------------------------+ | +------------------------------------------+
| Data Structure | What It Does | Example |
|---|---|---|
| List | Ordered collection of items | ["Apple", "Banana", "Mango"] |
| Dictionary | Key-value pairs for fast lookups | {"Ada": "080-1234", "Chidi": "080-5678"} |
| Set | Unique items, no duplicates | {"Mango", "Orange", "Banana"} |
| Mode | What It Does | If File Doesn't Exist |
|---|---|---|
| "r" (read) | Reads from a file | Error |
| "w" (write) | Writes to a file (overwrites) | Creates it |
| "a" (append) | Adds to the end of a file | Creates it |
+------------------------------------------------------------------+ | Lesson 1: Review of Module One | | Lesson 2: What is a Dictionary? | | Lesson 3: Working with Dictionaries | | Lesson 4: Looping Through a Dictionary | | Lesson 5: What is a Set? | | Lesson 6: Working with Sets | | Lesson 7: Reading from Files | | Lesson 8: Writing to Files | | Lesson 9: Error Handling โ try and except | | Lesson 10: Functions with Parameters | | Lesson 11: Functions that Return Values | | Lesson 12: Introduction to Classes and Objects | | Lesson 13: More List Methods | | Lesson 14: Putting It All Together โ A Small Project | | Lesson 15: Review | +------------------------------------------------------------------+
In this module, we have taken a big step forward in our Python journey. We learned about dictionaries โ a powerful way to store key-value pairs. We explored sets โ collections that only keep unique items. We discovered how to read from and write to files, making our programs remember data even after they close. We learned how to handle errors gracefully using try and except. We improved our functions by adding parameters and return values. We also got a taste of object-oriented programming with classes and objects.
We built a contact manager project that used all these new skills together. You now have a solid foundation in Python programming. You can build programs that store and retrieve data, handle errors, and organise code in clear, reusable ways. You are ready for the next level!
| Term | Definition |
|---|---|
| Dictionary | A) Unique items |
| Set | B) Key-value pairs |
| File | C) Handles errors |
| try/except | D) Sends a value back |
| return | E) Permanent storage |
Answers: Dictionary-B, Set-A, File-E, try/except-C, return-D
Scenario 1: You want to store the names and ages of your family members in a program.
Task: Should you use a list, dictionary, or set? Why?
Answer: A dictionary, because you want to look up a person's age by their name.
Scenario 2: You want to keep track of all the unique books you have read.
Task: Should you use a list, dictionary, or set? Why?
Answer: A set, because you only want to track unique titles (no duplicates).
In groups of three, build an enhanced version of the Contact Manager. Add a feature to save the contacts to a file and load them automatically when the program starts. Add a feature to update an existing contact. Share your work with the class.
Write a program that uses a dictionary to store students' names and their scores in a subject. Then, write a function that calculates and returns the average score.
Build a simple "Student Grade Manager" program. It should:
Write a program that reads a list of numbers from a file, finds the sum, average, and maximum number, and writes the results to another file.
Enhance the Contact Manager project to allow editing of contacts. Also, add a feature to search for a contact by phone number (not just by name).
Fill-in-the-blank: 1. dictionary, 2. set, 3. "r", 4. "w", 5. try/except, 6. parameter, 7. return, 8. class, 9. object, 10. list
True/False: 1T, 2F, 3T, 4T, 5T, 6F, 7F, 8F, 9T, 10T
Multiple Choice: 1A, 2A, 3A, 4A, 5A, 6A, 7A, 8A, 9A, 10A, 11A, 12A, 13A, 14A, 15A
Matching: Dictionary-B, Set-A, File-E, try/except-C, return-D
In Level 2, you will build on everything you have learned. You will explore more advanced concepts like:
Keep coding, keep exploring, and remember: every expert was once a beginner!
๐ Congratulations! You have completed Module Two: Diving Deeper into Python ๐
You are now ready for Level 2 โ Advanced Python!