Module Three: Building Cool Projects โ Strings, Tuples, and More!
Welcome back, young coder! You have made incredible progress. In Module One, you learned the basics โ variables, data types, input, if/else, loops, lists, and functions. In Module Two, you explored dictionaries, sets, file handling, error handling, functions with return values, and even classes!
Now, in Module Three, we will learn some new, powerful concepts that will make your code even better. We will explore strings in more detail โ they are not just text, they have many cool methods! We will learn about tuples โ a special kind of list that cannot be changed. We will discover how to pack and unpack values. We will build a real game โ a "Millionaire Quiz Game" โ using everything we have learned. We will also learn some advanced function tricks like default arguments and keyword arguments.
This module is all about taking your skills to the next level and building something fun. Let's get started!
After completing this module, you will be able to:
Chidi's Millionaire Dream
Chidi loved watching the TV show "Who Wants to Be a Millionaire?" He always dreamed of being a contestant. He said to his friend Ada, "I wish I could practice with questions before the show!" Ada said, "Chidi, you know Python! You can build your own quiz game!"
Chidi was excited. He decided to build a "Millionaire Quiz Game" using Python. He created a list of questions and answers. He used strings to format the questions nicely. He used loops to go through all the questions. He used if/else to check if the answers were correct. He even used a dictionary to keep track of scores. When he finished, he had a fully working game. He invited his friends to play, and they all had fun. Chidi realised that with Python, he could build anything he imagined!
Before we start new things, let's quickly review what we learned in the first two modules.
From Module One:
input() gets user input.if/elif/else for decisions.while and for loops.def.#.From Module Two:
try/except.append(), sort(), reverse().You have a strong foundation. Now, let's add some more tools to your toolbox!
Definition: Strings are pieces of text. Python has many built-in methods (tools) that let you change and work with strings.
Why it's important: You will often need to clean, format, or change text in your programs.
Simple explanation: It's like having a set of tools to fix, clean, and change words.
Real-life example: Changing all letters to uppercase for a consistent look.
School example: Removing extra spaces from a student's name.
Home example: Checking if a password is strong.
Nigerian example: Formatting a phone number to a standard format.
Illustration โ Code:
# String methods
text = " Hello, World! "
# Remove extra spaces from the ends
print(text.strip()) # "Hello, World!"
# Convert to uppercase
print(text.upper()) # " HELLO, WORLD! "
# Convert to lowercase
print(text.lower()) # " hello, world! "
# Split into a list of words
words = text.split() # ["Hello,", "World!"]
# Check if it starts with something
print(text.startswith(" Hello")) # True
# Check if it ends with something
print(text.endswith("!")) # True
# Find a word
print(text.find("World")) # Finds the position
# Replace text
print(text.replace("World", "Python")) # " Hello, Python! "
Mini summary: String methods let you manipulate and work with text easily.
Definition: We can format strings using format() or f-strings. We can also join strings together from a list.
Why it's important: Formatting helps you create nice-looking output. Joining helps you combine many pieces of text.
Simple explanation: It's like putting puzzle pieces together to make a complete picture.
Real-life example: Creating a sentence from a list of words.
School example: Printing a report card with formatted grades.
Home example: Creating a shopping list with prices.
Nigerian example: Formatting currency values with the Naira symbol.
Illustration โ Code:
# Using f-strings (preferred in modern Python)
name = "Ada"
age = 10
print(f"Hello, {name}! You are {age} years old.")
# Using format() method
print("Hello, {}! You are {} years old.".format(name, age))
# Joining a list of strings
words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(sentence) # "Python is awesome"
# Splitting a string into a list
text = "apple,banana,mango"
fruits = text.split(",")
print(fruits) # ["apple", "banana", "mango"]
Mini summary: format() and f-strings format text; join() combines strings.
Definition: A tuple is like a list, but it cannot be changed (it is immutable). You create a tuple using parentheses ().
Why it's important: Tuples are used for data that should not change โ like days of the week, coordinates, or settings.
Simple explanation: A tuple is like a list that you write in pen โ you can't erase or change it.
Real-life example: The days of the week: ("Monday", "Tuesday", "Wednesday").
School example: The subjects in a school timetable.
Home example: The names of your family members.
Nigerian example: The names of the states in the South-East.
Illustration โ Code:
# Creating a tuple
days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
# Accessing items
print(days[0]) # "Monday"
# Looping through a tuple
for day in days:
print(day)
# Trying to change a tuple will cause an error
# days[0] = "Sunday" # Error! Tuples cannot be changed
Mini summary: Tuples are like lists, but they cannot be changed after creation.
Definition: Packing is putting multiple values into a tuple. Unpacking is taking those values out and assigning them to variables.
Why it's important: Packing and unpacking make it easy to work with multiple values at once.
Simple explanation: It's like packing a suitcase (packing) and then unpacking it when you arrive (unpacking).
Real-life example: Returning multiple values from a function.
School example: Getting a student's name, age, and grade in one go.
Home example: Getting the temperature, humidity, and wind speed from a weather sensor.
Nigerian example: Getting the name, price, and quantity of a product from a database.
Illustration โ Code:
# Packing values into a tuple
student = ("Ada", 10, "A")
# Unpacking values into variables
name, age, grade = student
print(name) # "Ada"
print(age) # 10
print(grade) # "A"
# Returning multiple values from a function
def get_student():
return "Chidi", 12, "B"
name2, age2, grade2 = get_student()
print(name2, age2, grade2) # "Chidi 12 B"
# Swapping values using tuple unpacking
a = 5
b = 10
a, b = b, a
print(a, b) # 10 5
Mini summary: Packing groups values; unpacking separates them into variables.
Definition: Default arguments let you set a default value for a parameter. If the caller doesn't provide a value, the default is used.
Why it's important: Default arguments make your functions more flexible and easier to use.
Simple explanation: It's like having a backup plan โ if the user doesn't choose, you decide for them.
Real-life example: A function that greets a person. If no name is given, it says "Hello, Guest!".
School example: A function that calculates grades. If no pass mark is given, it uses 50 as default.
Home example: A function that calculates a discount. If no discount is given, it uses 10% as default.
Nigerian example: A function that calculates tax. If no tax rate is given, it uses 7.5% as default.
Illustration โ Code:
# A function with a default argument
def greet(name="Guest"):
print("Hello, " + name + "!")
greet() # Prints: Hello, Guest!
greet("Ada") # Prints: Hello, Ada!
# Another example
def calculate_discount(price, discount=10):
return price - (price * discount / 100)
print(calculate_discount(100)) # Uses 10% discount -> 90
print(calculate_discount(100, 20)) # Uses 20% discount -> 80
Mini summary: Default arguments give a fallback value if the user doesn't provide one.
Definition: Keyword arguments let you pass arguments to a function by name, not just by position. This makes your code clearer.
Why it's important: It makes function calls easier to read and understand.
Simple explanation: It's like saying "Put the sugar in the bowl" โ you name what you are doing.
Real-life example: order(food="Pizza", quantity=2).
School example: grade(student="Ada", score=90).
Home example: set_alarm(time="7:00", days="Monday").
Nigerian example: buy_item(name="Rice", quantity=5, price=1000).
Illustration โ Code:
# A function with multiple parameters
def student_info(name, age, grade):
print(f"Name: {name}, Age: {age}, Grade: {grade}")
# Positional arguments (order matters)
student_info("Ada", 10, "A")
# Keyword arguments (order doesn't matter)
student_info(grade="B", name="Chidi", age=12)
# Mixing positional and keyword (positional first)
student_info("Bola", age=11, grade="C")
# Default arguments with keyword arguments
def greet(name="Guest", greeting="Hello"):
print(greeting + ", " + name + "!")
greet() # Hello, Guest!
greet(name="Ada") # Hello, Ada!
greet(greeting="Hi", name="Chidi") # Hi, Chidi!
Mini summary: Keyword arguments let you pass values by name for clarity.
len() and range()Definition: len() returns the length (number of items) of a collection. range() generates a sequence of numbers.
Why it's important: They are used in loops and to check sizes of data structures.
Simple explanation: len() counts how many, range() gives you numbers to count with.
Real-life example: Checking the length of a password.
School example: Looping through a list of student names.
Home example: Creating a range of numbers for a timer.
Nigerian example: Counting the number of items in a shopping list.
Illustration โ Code:
# len() โ get the length
fruits = ["Mango", "Orange", "Banana"]
print(len(fruits)) # 3
text = "Hello, World!"
print(len(text)) # 13
# range() โ generate numbers
for i in range(5):
print(i) # Prints 0, 1, 2, 3, 4
# range(start, stop, step)
for i in range(1, 10, 2):
print(i) # Prints 1, 3, 5, 7, 9
# Using len() and range() together
for i in range(len(fruits)):
print(fruits[i])
Mini summary: len() counts items; range() generates number sequences.
Definition: List comprehensions are a shorter way to create lists. They combine a loop and a condition in one line.
Why it's important: They make your code shorter and easier to read.
Simple explanation: It's like writing a loop and an if statement all in one line.
Real-life example: Creating a list of doubled numbers.
School example: Creating a list of even numbers from 1 to 20.
Home example: Creating a list of words that start with "a".
Nigerian example: Creating a list of prices above a certain amount.
Illustration โ Code:
# Traditional way
squares = []
for i in range(1, 6):
squares.append(i * i)
print(squares) # [1, 4, 9, 16, 25]
# List comprehension โ shorter!
squares2 = [i * i for i in range(1, 6)]
print(squares2) # [1, 4, 9, 16, 25]
# With a condition
evens = [i for i in range(1, 11) if i % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]
# Using with strings
fruits = ["Mango", "Orange", "Banana"]
upper_fruits = [fruit.upper() for fruit in fruits]
print(upper_fruits) # ["MANGO", "ORANGE", "BANANA"]
Mini summary: List comprehensions are a shorter way to create lists from loops.
Now we will build our capstone project โ a "Millionaire Quiz Game". Let's plan it first.
What the game will do:
What we need:
We will store our questions in a list of tuples. Each tuple will have: (question, option_a, option_b, option_c, option_d, correct_answer).
Illustration โ Code:
# List of questions
questions = [
("What is the capital of Nigeria?", "Lagos", "Abuja", "Kano", "Ibadan", "B"),
("Who is the president of Nigeria?", "Buhari", "Tinubu", "Jonathan", "Obasanjo", "B"),
("What is 5 + 3?", "6", "7", "8", "9", "C"),
("Which is the largest country in Africa?", "Nigeria", "South Africa", "Algeria", "DR Congo", "C"),
("What is the currency of Nigeria?", "Naira", "Cedis", "Rand", "Shilling", "A")
]
Mini summary: Store questions in a list of tuples for easy access.
We will write a function to display a question and its options, get user input, and check if it's correct.
Illustration โ Code:
def ask_question(question_tuple):
# Unpack the tuple
question, a, b, c, d, correct = question_tuple
# Display the question and options
print("\n" + question)
print("A. " + a)
print("B. " + b)
print("C. " + c)
print("D. " + d)
# Get user's answer
answer = input("Your answer (A/B/C/D): ").upper()
# Check if correct
if answer == correct:
print("โ
Correct!")
return True
else:
print("โ Wrong! The correct answer was " + correct + ".")
return False
Mini summary: Display the question, get input, and check the answer.
Now we put everything together with a main game loop.
Illustration โ Code:
def play_game():
score = 0
total = len(questions)
print("=" * 40)
print("๐ WELCOME TO THE MILLIONAIRE QUIZ GAME! ๐")
print("=" * 40)
for index, q in enumerate(questions):
print(f"\n๐ Question {index + 1} of {total}")
if ask_question(q):
score += 1
# Display final score
print("\n" + "=" * 40)
print(f"๐ GAME OVER! You scored {score} out of {total}.")
if score == total:
print("๐ PERFECT SCORE! You are a genius! ๐")
elif score >= total * 0.7:
print("๐ Great job! You are a quiz master!")
elif score >= total * 0.4:
print("๐ Not bad! Keep learning!")
else:
print("๐ Keep studying! You'll do better next time!")
print("=" * 40)
# Run the game
play_game()
Mini summary: The main loop runs all questions and displays the final score.
We can add difficulty levels to our game. Easy questions, medium questions, and hard questions.
Illustration โ Code:
# Questions with difficulty
easy_questions = [
("What is the capital of Nigeria?", "Lagos", "Abuja", "Kano", "Ibadan", "B"),
("What is 5 + 3?", "6", "7", "8", "9", "C")
]
medium_questions = [
("Which year did Nigeria gain independence?", "1950", "1960", "1970", "1980", "B"),
("Who is the current president of Nigeria?", "Buhari", "Tinubu", "Jonathan", "Obasanjo", "B")
]
hard_questions = [
("What is the largest state in Nigeria by area?", "Lagos", "Borno", "Niger", "Bauchi", "C"),
("Which river is the longest in Nigeria?", "Niger", "Benue", "Cross", "Ogun", "A")
]
def play_with_difficulty():
difficulty = input("Choose difficulty (easy/medium/hard): ").lower()
if difficulty == "easy":
questions = easy_questions
elif difficulty == "medium":
questions = medium_questions
elif difficulty == "hard":
questions = hard_questions
else:
print("Invalid choice. Playing easy mode.")
questions = easy_questions
# Play the game with the chosen questions...
Mini summary: Add difficulty levels to make the game more interesting.
In this module, we learned:
len() and range().You now have the skills to build real projects with Python!
upper(), lower()).How to build a quiz game:
This module is project-focused. Let students work on the quiz game step by step. Encourage them to add their own features โ more questions, difficulty levels, timers, or graphics. Pair programming works well here.
Play the quiz game with your child! Let them quiz you on the questions they created. Encourage them to add more questions from subjects they enjoy. Celebrate their achievement in building a complete game!
+-------------+ +-------------+ +-------------+ +-------------+
| START | --> | SHOW | --> | GET | --> | CHECK |
| GAME | | QUESTION | | USER | | ANSWER |
+-------------+ +-------------+ | INPUT | +-------------+
| +-------------+ |
| +-------------+
| | CORRECT? |
| +-------------+
| | |
| V V
| +-------------+ +-------------+
| | SCORE++ | | SHOW |
| +-------------+ | CORRECT |
| | ANSWER |
V +-------------+
+-------------+ |
| MORE | <------------------------------------+
| QUESTIONS? |
+-------------+
| Yes
V
+-------------+
| FINAL |
| SCORE |
+-------------+
V
+-------------+
| END GAME |
+-------------+
| Data Structure | Ordered | Mutable | Allows Duplicates | Example |
|---|---|---|---|---|
| List | Yes | Yes | Yes | [1, 2, 3, 3] |
| Tuple | Yes | No | Yes | (1, 2, 3, 3) |
| Set | No | Yes | No | {1, 2, 3} |
| Dictionary | Yes (Python 3.7+) | Yes | Keys: No, Values: Yes | {"a": 1, "b": 2} |
| Method | What It Does | Example |
|---|---|---|
| upper() | Converts to uppercase | "hello".upper() โ "HELLO" |
| lower() | Converts to lowercase | "HELLO".lower() โ "hello" |
| strip() | Removes spaces from ends | " hi ".strip() โ "hi" |
| split() | Splits into a list | "a,b,c".split(",") โ ["a","b","c"] |
| join() | Joins a list into a string | ",".join(["a","b"]) โ "a,b" |
| replace() | Replaces text | "hi".replace("i","o") โ "ho" |
+------------------------------------------------------------------+ | Lesson 1: Review of Modules One and Two | | Lesson 2: String Methods โ Making Text Smarter | | Lesson 3: More String Methods โ Formatting and Joining | | Lesson 4: What is a Tuple? | | Lesson 5: Packing and Unpacking | | Lesson 6: Default Arguments in Functions | | Lesson 7: Keyword Arguments in Functions | | Lesson 8: The Power of len() and range() | | Lesson 9: List Comprehensions โ A Shorter Way to Build Lists | | Lesson 10: Building the Millionaire Quiz Game โ Planning | | Lesson 11: Building the Millionaire Quiz Game โ Step 1: Data | | Lesson 12: Building the Millionaire Quiz Game โ Step 2: Display | | Lesson 13: Building the Millionaire Quiz Game โ Step 3: Main | | Lesson 14: Enhancing the Quiz Game โ Adding Difficulty Levels | | Lesson 15: Review | +------------------------------------------------------------------+
In this module, we have taken our Python skills to a new level. We learned powerful string methods that let us manipulate text easily. We discovered tuples โ immutable lists that protect our data from being changed. We mastered packing and unpacking, which makes working with multiple values a breeze. We learned about default and keyword arguments, which make our functions more flexible and our code clearer.
We explored len() and range(), two essential tools for loops. We learned about list comprehensions โ a shorter, more elegant way to build lists. Most importantly, we built a complete "Millionaire Quiz Game" project that used everything we learned. We even added difficulty levels to make it more interesting.
You now have the confidence and skills to build real projects with Python. You can create games, apps, and tools that solve problems and entertain people. The journey continues โ keep coding, keep exploring, and keep having fun!
upper() and lower().len() do? Returns the length of a collection.range() do? Generates a sequence of numbers.upper() do?split() do?len() return?range(5) generate?_____ converts a string to uppercase. (upper())_____ splits a string into a list. (split())_____ generates a sequence of numbers. (range())upper() converts a string to lowercase. (False)split() splits a string into a list. (True)len() returns the length of a string. (True)range(5) generates numbers from 1 to 5. (False โ it generates 0 to 4)upper() do?len() do?range(5) generate?if/else B) Using for loop C) Using while loop D) Using try/except Answer: Ajoin() B) split() C) upper() D) strip() Answer: Astrip() B) split() C) upper() D) lower() Answer: A| Term | Definition |
|---|---|
| upper() | A) Splits into a list |
| split() | B) Converts to uppercase |
| Tuple | C) Immutable list |
| len() | D) Returns length |
| range() | E) Generates numbers |
Answers: upper()-B, split()-A, Tuple-C, len()-D, range()-E
split() and join()?range() do?Scenario 1: You want to create a quiz about Nigerian states and their capitals.
Task: Write the code to store 3 questions and display them.
Answer:
questions = [
("What is the capital of Lagos?", "Ikeja", "Lagos", "Abuja", "Ibadan", "A"),
("What is the capital of Oyo?", "Ibadan", "Oyo", "Abuja", "Lagos", "A"),
("What is the capital of Kano?", "Kano", "Abuja", "Ibadan", "Lagos", "A")
]
for q in questions:
print(q[0])
print("A. " + q[1])
print("B. " + q[2])
print("C. " + q[3])
print("D. " + q[4])
answer = input("Your answer: ").upper()
if answer == q[5]:
print("Correct!")
else:
print("Wrong! Correct answer is " + q[5])
In groups of three, build an enhanced version of the Millionaire Quiz Game. Add a timer, lifelines (like 50/50), and a leaderboard. Each person takes a different part of the project.
Write a quiz game on a topic you are passionate about โ sports, music, movies, or anything else. Include at least 10 questions and a scoring system.
Build a "Millionaire Quiz Game" with the following features:
Write a complete quiz game about Nigerian culture. Include:
Enhance the quiz game with a timer โ each question must be answered in 10 seconds. If the time runs out, the question is marked wrong. Use the time module to implement this.
Fill-in-the-blank: 1. upper(), 2. split(), 3. tuple, 4. Unpacking, 5. default, 6. len(), 7. range(), 8. list comprehension, 9. tuple, 10. if/else
True/False: 1F, 2T, 3F, 4T, 5T, 6F, 7T, 8F, 9F, 10T
Multiple Choice: 1A, 2B, 3B, 4A, 5A, 6A, 7A, 8A, 9A, 10A, 11A, 12A, 13A, 14A, 15A
Matching: upper()-B, split()-A, Tuple-C, len()-D, range()-E
upper(), lower(), split(), join() are powerful tools.len() and range() are essential for loops.Congratulations! You have completed Level 1 of Python Programming. You have learned all the fundamentals โ from variables to functions, from lists to dictionaries, from files to classes, and from strings to building games!
In Level 2, you will take your skills even further. You will learn:
You have built a strong foundation. The world of Python is vast and exciting. Keep coding, keep exploring, and never stop learning!
๐ Congratulations! You have completed Level 1 of Python Programming! ๐
You are now ready for Level 2 โ Advanced Python!