Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
โ† Python Fundamentals Level One ยท Lesson 3 of 5

Module Two

๐Ÿ“– Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
3
Module 2 ยท Python Programming Level 1

๐Ÿ Module Two: Diving Deeper into Python โ€“ Dictionaries, Files, and More!

1. Module Title

Module Two: Diving Deeper into Python โ€“ Dictionaries, Files, and More!


2. Module Introduction

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!


3. Learning Objectives

After completing this module, you will be able to:

  • Understand and use dictionaries to store key-value pairs.
  • Use sets to store unique items.
  • Read from and write to files (file input/output).
  • Handle errors using try and except.
  • Write functions that take parameters and return values.
  • Understand the basics of classes and objects.
  • Use list methods to manipulate lists.
  • Loop through different data structures.
  • Build a small project that uses all the new concepts.

4. Warm-up Story

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.


5. Main Lessons

Lesson 1: Review of Module One

Before we start new things, let's quickly review what we learned in Module One.

We learned:

  • Programming is giving instructions to a computer.
  • Python is a beginner-friendly programming language.
  • Variables store data.
  • Data types: integers (whole numbers), floats (decimals), and strings (text).
  • We used input() to get user input.
  • We used if/else to make decisions.
  • We used while and for loops to repeat code.
  • We used lists to store many items.
  • We wrote functions using def.
  • We added comments with #.
  • We debugged errors.

You have a strong foundation. Now, let's build on it!


Lesson 2: What is a Dictionary?

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.


Lesson 3: Working with Dictionaries

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.


Lesson 4: Looping Through 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.


Lesson 5: What is a Set?

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.


Lesson 6: Working with Sets

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.


Lesson 7: Reading from Files

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.


Lesson 8: Writing to Files

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.


Lesson 9: Error Handling โ€“ try and except

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.


Lesson 10: Functions with Parameters

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.


Lesson 11: Functions that Return Values

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.


Lesson 12: Introduction to Classes and Objects

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.


Lesson 13: More List 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.


Lesson 14: Putting It All Together โ€“ A Small Project

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:

  1. Add a new contact (name and phone number).
  2. View all contacts.
  3. Search for a contact by name.
  4. Delete a contact.
  5. Save contacts to a file so they don't disappear when the program closes.

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.


Lesson 15: Review โ€“ What We Learned in Module Two

In this module, we learned:

  • Dictionaries store key-value pairs.
  • Sets store unique items.
  • How to read from and write to files.
  • How to handle errors with try and except.
  • Functions with parameters and return values.
  • The basics of classes and objects.
  • More list methods.
  • How to build a small project using all these concepts.

You have now built a strong foundation in Python. You are ready for Level 2!


6. Key Vocabulary

  • Dictionary: A collection of key-value pairs.
  • Key: A unique identifier in a dictionary.
  • Value: The data associated with a key.
  • Set: A collection of unique items.
  • File: A place to store data permanently.
  • Read: To get data from a file.
  • Write: To save data to a file.
  • Error Handling: Catching and managing errors.
  • Parameter: A value passed into a function.
  • Return: To send a value back from a function.
  • Class: A blueprint for creating objects.
  • Object: An instance of a class.

7. Important Concepts

  • Dictionaries make data easy to find: Use keys to look up values quickly.
  • Sets remove duplicates: Great for tracking unique items.
  • Files save your data forever: Your program data survives after you close it.
  • Error handling prevents crashes: Always handle possible errors.
  • Functions with parameters are flexible: They can work with different data.
  • Classes model real-world things: They help you organise complex code.

8. Step-by-step Explanations

How to read and write files:

  1. Open the file with open("filename", "r") for reading.
  2. Read the content with .read() or loop through lines.
  3. Close the file with .close().
  4. For writing, use open("filename", "w").
  5. Write content with .write().
  6. Close the file.

9. Real-life Examples

  • A dictionary storing product prices in a store.
  • A set storing unique visitors to a website.
  • A file storing user settings.
  • Error handling in a payment system.
  • A function that calculates discounts.
  • A class representing a bank account.

10. Nigerian Examples

  • A dictionary storing Naira-to-Dollar exchange rates.
  • A set storing the states you have visited in Nigeria.
  • A file storing daily sales records.
  • Error handling when entering a PIN at an ATM.
  • A function that calculates VAT on items.
  • A class representing a market vendor.

11. Fun Examples Children Can Relate To

  • A dictionary of your friends' favourite games.
  • A set of your favourite foods.
  • A file storing your high scores.
  • Error handling in a game when the user enters invalid input.
  • A function that calculates how many days until your birthday.
  • A class representing a video game character.

12. Everyday Examples

  • ๐Ÿ“ฑ A phone book (dictionary).
  • ๐ŸŽต A playlist with unique songs (set).
  • ๐Ÿ“ A to-do list saved to a file.
  • ๐Ÿ” A login system with error handling.
  • ๐Ÿ“Š A function that calculates averages.
  • ๐Ÿ  A class representing a house.

13. Teacher Notes

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.


14. Parent Tips

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


15. Interesting Facts

  • ๐Ÿ“š Dictionaries in Python are very fast โ€“ they can find a value instantly!
  • ๐Ÿ”’ Sets are used in many games to track unique items.
  • ๐Ÿ’พ Files are how programs save your progress in games.
  • ๐Ÿงช Error handling is what keeps websites from crashing.
  • ๐Ÿ—๏ธ Classes are used to build everything from video games to web apps.

16. Did You Know?

  • Python dictionaries are used behind the scenes in many web applications.
  • Sets are used to find common friends on social media.
  • File I/O is how databases work โ€“ they store data permanently.
  • Error handling is a skill that makes you a better programmer.
  • Classes are the foundation of object-oriented programming (OOP).

17. Remember This

  • โœ… Dictionaries = key-value pairs.
  • โœ… Sets = unique items.
  • โœ… Files = permanent storage.
  • โœ… try/except = error handling.
  • โœ… Functions can take parameters and return values.
  • โœ… Classes = blueprints for objects.

18. Common Mistakes

  • โŒ Forgetting quotes around keys in dictionaries.
  • โŒ Trying to access a key that doesn't exist.
  • โŒ Forgetting to close a file.
  • โŒ Not handling errors that might occur.
  • โŒ Forgetting the self parameter in class methods.

19. Best Practices

  • โœ… Use get() to safely access dictionary keys.
  • โœ… Use sets when you need unique items.
  • โœ… Always close files or use with statements.
  • โœ… Always handle potential errors.
  • โœ… Use descriptive names for classes and methods.

20. Illustrations

Dictionary Structure

  +------------------------------------------+
  |  DICTIONARY                               |
  |  +--------------------------------------+ |
  |  |  KEY       |  VALUE                  | |
  |  |------------|-------------------------| |
  |  |  "Ada"     |  "080-1234-5678"       | |
  |  |  "Chidi"   |  "080-8765-4321"       | |
  |  |  "Bola"    |  "080-5555-5555"       | |
  |  +--------------------------------------+ |
  +------------------------------------------+

Comparison Table โ€“ Data Structures

Data StructureWhat It DoesExample
ListOrdered collection of items["Apple", "Banana", "Mango"]
DictionaryKey-value pairs for fast lookups{"Ada": "080-1234", "Chidi": "080-5678"}
SetUnique items, no duplicates{"Mango", "Orange", "Banana"}

Comparison Table โ€“ File Modes

ModeWhat It DoesIf File Doesn't Exist
"r" (read)Reads from a fileError
"w" (write)Writes to a file (overwrites)Creates it
"a" (append)Adds to the end of a fileCreates it

Timeline โ€“ Module Two Learning Path

  +------------------------------------------------------------------+
  |  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                                               |
  +------------------------------------------------------------------+

23. End-of-Module Summary

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!


24. Frequently Asked Questions

  1. What is a dictionary? A collection of key-value pairs.
  2. What is a set? A collection of unique items.
  3. Why do we need files? To save data permanently.
  4. What does try/except do? It prevents errors from crashing your program.
  5. What are parameters? Values you pass into a function.
  6. What does return do? It sends a value back from a function.
  7. What is a class? A blueprint for creating objects.
  8. What is an object? An instance of a class.
  9. How do I read a file? Use open("file", "r").
  10. How do I write to a file? Use open("file", "w").

25. Review Questions

  1. What is a dictionary?
  2. What is a key in a dictionary?
  3. What is a value in a dictionary?
  4. How do you add an item to a dictionary?
  5. What is a set?
  6. How do you add an item to a set?
  7. How do you read from a file?
  8. How do you write to a file?
  9. What does try/except do?
  10. What is a parameter in a function?
  11. What does return do in a function?
  12. What is a class?
  13. What is an object?
  14. What is the difference between a list and a dictionary?
  15. What is the difference between a list and a set?

26. Fill-in-the-Blank

  1. A _____ stores key-value pairs. (dictionary)
  2. A _____ stores unique items. (set)
  3. To read a file, use the _____ mode. ("r")
  4. To write to a file, use the _____ mode. ("w")
  5. _____ handles errors in Python. (try/except)
  6. A _____ is a value passed into a function. (parameter)
  7. The _____ keyword returns a value from a function. (return)
  8. A _____ is a blueprint for creating objects. (class)
  9. An _____ is an instance of a class. (object)
  10. A _____ is an ordered collection of items. (list)

27. True or False

  1. Dictionaries store key-value pairs. (True)
  2. Sets allow duplicate items. (False)
  3. Files save data permanently. (True)
  4. try/except prevents errors. (True)
  5. Functions can take parameters. (True)
  6. Functions cannot return values. (False)
  7. A class is an object. (False)
  8. A set is an ordered collection. (False)
  9. You must close files after using them. (True)
  10. Dictionaries are used for fast lookups. (True)

28. Multiple Choice Questions

  1. What does a dictionary store?
    A) Key-value pairs B) Only values C) Only keys D) Duplicates Answer: A
  2. What does a set store?
    A) Unique items B) Duplicate items C) Key-value pairs D) Only numbers Answer: A
  3. What mode reads from a file?
    A) "r" B) "w" C) "a" D) "x" Answer: A
  4. What mode writes to a file?
    A) "w" B) "r" C) "a" D) "x" Answer: A
  5. What does try/except do?
    A) Handles errors B) Writes to files C) Reads from files D) Loops code Answer: A
  6. What is a parameter?
    A) A value passed to a function B) A type of loop C) A data structure D) An error Answer: A
  7. What does return do?
    A) Sends a value back B) Prints a value C) Loops code D) Creates a variable Answer: A
  8. What is a class?
    A) A blueprint for objects B) A collection of items C) A type of loop D) A file Answer: A
  9. What is an object?
    A) An instance of a class B) A key-value pair C) A file D) A loop Answer: A
  10. Which is a dictionary?
    A) {"name": "Ada"} B) ["Ada", "Chidi"] C) {"Ada", "Chidi"} D) "Ada" Answer: A
  11. Which is a set?
    A) {"Ada", "Chidi"} B) {"name": "Ada"} C) ["Ada", "Chidi"] D) "Ada" Answer: A
  12. Why do we close files?
    A) To save memory and prevent errors B) To make them faster C) To delete them D) To read them Answer: A
  13. What is a Nigerian example of a dictionary?
    A) A price list with items and prices B) A list of names C) A set of cities D) A file Answer: A
  14. What is a Nigerian example of a set?
    A) All the states you've visited B) A list of cities C) A dictionary of prices D) A file Answer: A
  15. Is Python free?
    A) Yes B) No Answer: A

29. Matching Exercises

TermDefinition
DictionaryA) Unique items
SetB) Key-value pairs
FileC) Handles errors
try/exceptD) Sends a value back
returnE) Permanent storage

Answers: Dictionary-B, Set-A, File-E, try/except-C, return-D


30. Short Answer Questions

  1. What is a dictionary?
  2. What is the difference between a list and a dictionary?
  3. What is a set?
  4. How do you read from a file?
  5. How do you write to a file?
  6. What does try/except do?
  7. What is a class?

31. Scenario-based Exercises

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


32. Group Activity

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.


33. Individual Activity

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.


34. Classroom Discussion Questions

  • When would you use a dictionary instead of a list?
  • When would you use a set instead of a list?
  • Why is it important to save data to files?
  • How can error handling make your program better?
  • What real-world things could you model with classes?

35. Mini Project

Build a simple "Student Grade Manager" program. It should:

  1. Use a dictionary to store student names and grades.
  2. Allow the user to add, view, and delete students.
  3. Save the data to a file so it doesn't disappear.
  4. Load the data when the program starts.
  5. Calculate and display the average grade.

36. Practical Assignment

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.


37. Challenge Exercise

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


38. Quiz Answers

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


39. Key Takeaways

  • ๐Ÿ”น Dictionaries store key-value pairs for fast lookups.
  • ๐Ÿ”น Sets store unique items and remove duplicates.
  • ๐Ÿ”น Files save your data permanently.
  • ๐Ÿ”น try/except handles errors gracefully.
  • ๐Ÿ”น Functions with parameters and return values are flexible.
  • ๐Ÿ”น Classes and objects model real-world things.
  • ๐Ÿ”น List methods make working with lists easier.
  • ๐Ÿ”น You can build real projects with these skills.

40. Preparation for the Next Module

In Level 2, you will build on everything you have learned. You will explore more advanced concepts like:

  • More advanced object-oriented programming.
  • Working with external libraries.
  • Building graphical user interfaces (GUIs).
  • Introduction to web development with Python.
  • Working with APIs to get data from the internet.
  • Building larger, more complex projects.

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!

๐Ÿ† Get Certified

๐Ÿ”’

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (โ‚ฆ2,000 or 20,000 coins), and get a verified certificate with your name on it.

๐ŸŽ“ Sign Up to Get Certified
๐Ÿ› ๏ธ Practice Tools
Hands-on simulators & labs - subscription required.
โ†’
๐ŸŽฏ Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
โ†’