Hello, amazing engineer! You have come so far – you now know variables, loops, functions, classes, dictionaries, and error handling. In this module, we are going to explore three powerful concepts that will make you a true Python master!
Recursion is when a function calls itself. It's like looking at yourself in a mirror that reflects another mirror – you see yourself inside yourself!
Lambda functions are tiny, one‑line functions that you can use on the spot – like a quick note instead of a full letter.
JSON (JavaScript Object Notation) is a way to store and exchange data – it's like a universal language that computers all over the world understand.
By the end of this module, you will be able to write recursive functions, use lambdas, and read/write JSON data. These are advanced skills used by professional developers every day!
After this module, you will be able to:
map(), filter(), and sorted().Ngozi loved playing with Russian dolls – those wooden dolls that open to reveal a smaller doll inside, and then another, and another.
One day, she thought: “If I could write a program that opens each doll until it reaches the smallest one, that would be like a function calling itself!”
Her older brother, a software engineer, explained: “That’s called recursion. You have a function that opens a doll. If there’s a smaller doll inside, it calls itself again. This continues until it reaches the smallest doll – that’s the base case.”
Ngozi also learned about lambda – tiny functions that are so small you don't even need to name them – like a quick note. And JSON – a way to store her doll collection data so she could share it with friends.
Let's learn these amazing tools!
Definition: Recursion is a technique where a function calls itself to solve a smaller version of the same problem.
Why is it important? It's a very elegant way to solve problems that can be broken down into smaller, similar problems.
Simple explanation: Like the Russian dolls – you open one, and inside is a smaller one, until you reach the tiny one at the centre.
Real‑life example: Looking for a book in a stack of boxes – you open one box, if it's not there, you open the next, and so on.
School example: Counting the number of students in a row – you count the first student, then the rest of the row.
Home example: Peeling an onion – you peel one layer, then peel the next.
Nigerian example: Finding your way in a market – you ask one trader, they point to another, and so on.
Illustration:
def open_doll():
if there_is_a_smaller_doll():
open_doll() # calls itself!
else:
print("Reached the smallest doll!")
Mini summary: Recursion is when a function calls itself to solve a smaller version of the same problem.
Definition: The base case is the condition that stops the recursion. The recursive case is where the function calls itself.
Why is it important? Without a base case, the function would call itself forever – causing a stack overflow!
Simple explanation: The base case is like the smallest doll – you stop when you reach it. The recursive case is like opening a doll to find another doll inside.
Real‑life example: Countdown to zero – you start at 10, then 9, then 8, and when you reach 0 (base case), you stop.
School example: A teacher calling students' names – when they reach the last name (base case), they stop.
Home example: Eating a chocolate bar – you break off pieces until you have eaten the last piece (base case).
Nigerian example: Passing a message down a line of people – when the last person gets it (base case), the chain stops.
Illustration:
def countdown(n):
if n == 0: # base case
print("Blast off!")
else: # recursive case
print(n)
countdown(n-1)
Mini summary: The base case stops recursion; the recursive case calls the function again.
Definition: Factorial (written as n!) is the product of all positive integers up to n. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.
Why is it important? It's a classic example that shows how recursion works beautifully.
Simple explanation: 5! = 5 × 4! – so factorial calls itself with a smaller number.
Real‑life example: Arranging 5 books on a shelf – there are 5! ways to arrange them.
School example: How many ways can you arrange 3 students in a row? 3! = 6 ways.
Home example: How many ways can you arrange 4 chairs around a table? 4! = 24 ways.
Nigerian example: How many ways can you arrange 5 different fruits in a basket? 5! = 120 ways.
Illustration:
def factorial(n):
if n == 0: # base case
return 1
else: # recursive case
return n * factorial(n-1)
print(factorial(5)) # 120
Mini summary: Factorial is a perfect example – it calls itself with a smaller number until it reaches 0.
Definition: Fibonacci numbers are a sequence where each number is the sum of the two preceding ones: 0, 1, 1, 2, 3, 5, 8, 13, ...
Why is it important? It shows how recursion can solve problems that are naturally recursive.
Simple explanation: fib(n) = fib(n-1) + fib(n-2) – the function calls itself twice!
Real‑life example: The number of rabbits in a population after n months – each pair produces a new pair.
School example: The number of ways to climb stairs if you can take 1 or 2 steps at a time.
Home example: The number of ancestors you have going back n generations (roughly).
Nigerian example: The branching pattern of a tree – each branch splits into smaller branches.
Illustration:
def fibonacci(n):
if n <= 1: # base case
return n
else: # recursive case
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(6)) # 8
Mini summary: Fibonacci is a recursive sequence – each term is the sum of the two previous terms.
Definition: Recursion solves problems by calling itself; iteration solves them using loops (like for and while).
Why is it important? Sometimes recursion is simpler, sometimes loops are more efficient.
Simple explanation: Recursion is like climbing down a ladder (one step at a time, going deeper). Iteration is like walking down a hallway (repeating a step).
Real‑life example: Finding a file in a folder (recursion) vs adding up numbers in a list (iteration).
School example: Checking each student in a list (iteration) vs calculating factorial (recursion).
Home example: Eating a cake slice by slice (iteration) vs opening Russian dolls (recursion).
Nigerian example: Counting passengers on a bus (iteration) vs navigating a maze (recursion).
Illustration:
# Iterative factorial
def factorial_iter(n):
result = 1
for i in range(1, n+1):
result = result * i
return result
# Recursive factorial
def factorial_rec(n):
if n == 0:
return 1
return n * factorial_rec(n-1)
Mini summary: Recursion and iteration are both ways to repeat – recursion is often more elegant, iteration is often faster.
Definition: A lambda is a small, anonymous function – it has no name and is defined in one line.
Why is it important? It's useful for short, simple operations that you don't want to define as a full function.
Simple explanation: Like a quick note you write on a sticky note – you use it and throw it away.
Real‑life example: Writing a quick formula on a scrap of paper.
School example: Jotting down a quick reminder.
Home example: Writing a shopping list on a small piece of paper.
Nigerian example: A trader writing a quick price on a label.
Illustration:
# A normal function
def add(a, b):
return a + b
# A lambda function (same thing, but one line)
add_lambda = lambda a, b: a + b
print(add_lambda(5, 3)) # 8
Mini summary: A lambda is a one‑line, nameless function for short tasks.
map()Definition: map() applies a function to every item in an iterable (like a list).
Why is it important? It's a clean way to transform data without writing loops.
Simple explanation: You have a list of numbers; you want to double each one. map() does it for you!
Real‑life example: A price list – you apply a 10% discount to every item.
School example: You have a list of test scores; you add 5 points to each.
Home example: You have a list of ingredients; you convert cups to grams.
Nigerian example: A trader updates prices by adding 50 naira to each item.
Illustration:
numbers = [1, 2, 3, 4, 5]
doubled = map(lambda x: x * 2, numbers)
print(list(doubled)) # [2, 4, 6, 8, 10]
Mini summary: map() with lambda applies a function to every item in a list.
filter()Definition: filter() selects items from an iterable based on a condition.
Why is it important? It's an easy way to filter data – like keeping only the good apples.
Simple explanation: You have a list of numbers; you want only the even ones. filter() does it!
Real‑life example: A shopkeeper checks which items are in stock.
School example: A teacher finds all students who scored above 80.
Home example: You filter out chores that are already done.
Nigerian example: A trader filters out items that are out of stock.
Illustration:
numbers = [1, 2, 3, 4, 5, 6]
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens)) # [2, 4, 6]
Mini summary: filter() with lambda selects items that satisfy a condition.
sorted()Definition: sorted() sorts an iterable. You can use a lambda to specify how to sort.
Why is it important? It lets you sort by custom rules – like sorting by the second item in a tuple.
Simple explanation: You have a list of people with ages. You want to sort them by age – sorted() with a lambda does it!
Real‑life example: Sorting a list of students by their scores.
School example: Arranging books by page count.
Home example: Sorting your grocery list by price.
Nigerian example: Sorting market items by price per kilogram.
Illustration:
fruits = [("apple", 200), ("orange", 150), ("banana", 100)]
sorted_fruits = sorted(fruits, key=lambda x: x[1])
print(sorted_fruits) # [('banana', 100), ('orange', 150), ('apple', 200)]
Mini summary: sorted() with a lambda lets you sort by custom criteria.
Definition: JSON (JavaScript Object Notation) is a lightweight format for storing and exchanging data.
Why is it important? It's the most common way to send data between web servers and apps.
Simple explanation: It's like a universal language that computers use to talk to each other.
Real‑life example: When you use a weather app, it gets data from a server in JSON format.
School example: A student database stored as JSON.
Home example: A shopping list stored as JSON.
Nigerian example: A fintech app receives transaction data in JSON.
Illustration:
{
"name": "Chidi",
"age": 10,
"city": "Lagos",
"grades": [85, 90, 78]
}
Mini summary: JSON is a standard format for storing and exchanging data.
json ModuleDefinition: Python has a json module that lets you convert Python objects to JSON and vice versa.
Why is it important? It allows your Python programs to communicate with web services.
Simple explanation: You can turn a Python dictionary into a JSON string, and turn a JSON string back into a Python dictionary.
Real‑life example: Saving user settings in a JSON file.
School example: Storing student records in a JSON file.
Home example: Saving a recipe in JSON format.
Nigerian example: A bank app sending transaction data as JSON.
Illustration:
import json
data = {"name": "Chidi", "age": 10}
json_string = json.dumps(data) # convert to JSON
print(json_string) # {"name": "Chidi", "age": 10}
parsed = json.loads(json_string) # convert back to Python
print(parsed["name"]) # Chidi
Mini summary: The json module converts between Python objects and JSON.
Definition: You can save JSON data to a file and read it back later.
Why is it important? It's a common way to store configuration and data.
Simple explanation: Like saving your game progress in a file – but in JSON format.
Real‑life example: A game saves your high score in a JSON file.
School example: A teacher saves student grades in a JSON file.
Home example: You save your favourite recipes in a JSON file.
Nigerian example: A POS machine saves daily transactions in a JSON file.
Illustration:
import json
data = {"name": "Chidi", "score": 100}
# Write to file
with open("data.json", "w") as file:
json.dump(data, file)
# Read from file
with open("data.json", "r") as file:
loaded_data = json.load(file)
print(loaded_data["name"]) # Chidi
Mini summary: Use json.dump() and json.load() to work with JSON files.
Definition: JSON supports dictionaries (objects) and lists (arrays) – just like Python!
Why is it important? You can store complex nested data structures.
Simple explanation: You can have a list of dictionaries – like a list of students, each with their own details.
Real‑life example: A list of products, each with a name, price, and quantity.
School example: A list of students, each with a name and grades.
Home example: A list of family members, each with a name and age.
Nigerian example: A list of transactions, each with an amount and date.
Illustration:
import json
students = [
{"name": "Chidi", "grade": 85},
{"name": "Ama", "grade": 90}
]
# Convert to JSON string
json_data = json.dumps(students)
print(json_data)
# [{"name": "Chidi", "grade": 85}, {"name": "Ama", "grade": 90}]
Mini summary: JSON can store nested data – dictionaries inside lists, and vice versa.
Definition: Each tool has its best use cases – recursion for naturally recursive problems, lambda for short operations, JSON for data exchange.
Why is it important? Knowing when to use each tool makes you a better engineer.
Simple explanation: Use recursion for problems that break into smaller versions of themselves. Use lambda for quick, one‑time functions. Use JSON for storing and sharing data.
Real‑life example: A file system (recursion) – searching through folders and sub‑folders.
School example: Calculating factorial (recursion), filtering a list (lambda), saving grades (JSON).
Home example: Organising a closet (recursion), quick calculations (lambda), storing recipes (JSON).
Nigerian example: Navigating a market (recursion), applying discounts (lambda), storing transaction data (JSON).
Illustration:
# Recursion: traversing a folder
# Lambda: sorting a list by a key
# JSON: storing user data
Mini summary: Choose the right tool – recursion for nested problems, lambda for short functions, JSON for data storage.
Definition: You can combine recursion, lambda, and JSON in a single program.
Why is it important? Real‑world programs use multiple techniques together.
Simple explanation: You might use recursion to explore a nested structure, lambdas to filter data, and JSON to save the results.
Real‑life example: A program that explores a nested folder structure, filters files by size, and saves the results in JSON.
School example: A program that calculates grades recursively, filters students with lambdas, and saves the data in JSON.
Home example: A program that organises a recipe book using recursion (categories), filters recipes with lambdas, and saves in JSON.
Nigerian example: A financial app that recursively calculates compound interest, filters transactions, and stores data in JSON.
Illustration:
# Recursive function to explore nested data
# Lambda to filter items
# JSON to save and load data
Mini summary: Recursion, lambda, and JSON often work together in real programs.
| Word | Simple Definition |
|---|---|
| Recursion | When a function calls itself. |
| Base Case | The condition that stops recursion. |
| Recursive Case | The part where the function calls itself. |
| Lambda | A small, unnamed function. |
| map() | Applies a function to every item in a list. |
| filter() | Selects items that satisfy a condition. |
| sorted() | Sorts items based on a key. |
| JSON | A standard format for data exchange. |
| dumps() | Converts Python object to JSON string. |
| loads() | Converts JSON string to Python object. |
json module.json.dumps() to convert a Python object to a JSON string.json.loads() to convert a JSON string to a Python object.json.dump() to write JSON to a file.json.load() to read JSON from a file.This module introduces three advanced topics. For recursion, use visual aids (Russian dolls, nested boxes). For lambdas, compare them to quick notes. For JSON, show how data is exchanged between apps. Emphasise the importance of the base case in recursion to avoid infinite loops.
Ask your child to identify recursion in daily life – like nested boxes or Russian dolls. Discuss how a quick note is like a lambda function. Explain how data is stored in JSON – like a digital notebook. Encourage them to experiment with small recursive functions.
json module – you must import it to use JSON.with open() when working with JSON files – it handles closing the file.
Start
|
v
Is base case true? → Yes → Return result
|
No
|
v
Call function with smaller input
|
v
(go back to start)
| Feature | Recursion | Iteration |
|---|---|---|
| Definition | Function calls itself | Uses loops (for, while) |
| Code | Often shorter, more elegant | Often longer |
| Performance | Can be slower (function call overhead) | Usually faster |
| Risk | Stack overflow if no base case | Infinite loop if condition never false |
{
"student": {
"name": "Chidi",
"age": 10,
"subjects": ["Math", "Science"]
}
}
You have completed Module 7 – you are now a Python expert! You learned about recursion – functions that call themselves to solve problems elegantly. You discovered lambda functions – small, anonymous functions that are perfect for quick operations. And you mastered JSON – the universal language for data exchange.
These are advanced tools that are used in many real‑world applications – from AI to web development. You now have a powerful toolkit that will serve you for years to come.
You are now ready for the next stage – Module 8 will be a final project where you'll build something amazing!
map()? Applies a function to every item in an iterable.filter()? Selects items from an iterable based on a condition.json.dumps().json.loads().map() with a lambda?filter() with a lambda?json.dumps() and json.dump()?json.loads() and json.load()?map() returns a list. (False – it returns an iterator)filter() returns an iterator. (True)json.dumps() writes JSON to a file. (False – it returns a string)json.load() reads JSON from a file. (True)map() do?filter() do?json.load()json.dumps()json.dump()json.loads()json.load()json.dumps()json.dump()json.loads()json.dump() do?json.load() do?lambda x: x*2lambda x: return x*2lambda(x): x*2lambda x, y: x+y| Term | Definition |
|---|---|
| 1. Recursion | A. A small, anonymous function |
| 2. Lambda | B. A function that calls itself |
| 3. Base Case | C. Converts Python to JSON string |
| 4. dumps() | D. Stops recursion |
| 5. JSON | E. A standard data format |
Answers: 1‑B, 2‑A, 3‑D, 4‑C, 5‑E
json.dumps() and json.dump()?map() and filter()?Scenario 1: You have a nested list of numbers (like [1, [2, [3, 4]], 5]). Write a recursive function that prints all the numbers in the list.
Scenario 2: You have a list of students, each represented as a dictionary. Use a lambda with sorted() to sort them by their grades.
Scenario 3: You want to save a list of transactions to a JSON file and then read it back. Write the code to do this.
In groups, create a recursive function to calculate the sum of all numbers in a nested list. Then, use a lambda with filter() to extract only even numbers from a list. Finally, save the results to a JSON file. Each group presents their code and explains how they used recursion, lambda, and JSON.
Write a Python program that uses recursion to calculate the factorial of a number. Then, use a lambda with map() to calculate the factorial of a list of numbers. Finally, save the results to a JSON file.
Build a Recursive JSON Explorer: Write a Python program that loads a JSON file, recursively traverses the data, and prints all the keys and values in a readable format. Use recursion to handle nested dictionaries and lists. Save the output to a new JSON file.
Write a Python program that reads a JSON file containing a list of products (each with name, price, and quantity). Use a lambda with filter() to find products with a price below 100. Then, use a lambda with map() to apply a 10% discount to those products. Save the updated list to a new JSON file.
Write a Python program that uses recursion to generate all possible combinations of items from a list (like a power set). For example, for [1, 2, 3], the output should be [[], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]]. Save the result to a JSON file.
Fill‑in‑the‑Blank: 1. Recursion, 2. base, 3. lambda, 4. map(), 5. filter(), 6. JSON, 7. json.dumps(), 8. json.loads(), 9. json.dump(), 10. json.load().
True/False: 1T, 2F, 3F, 4T, 5T, 6F, 7F, 8T, 9F, 10T.
Multiple Choice: 1B, 2B, 3B, 4B, 5B, 6B, 7B, 8D, 9B, 10D, 11B, 12C, 13B, 14B, 15A.
Module 8 is a final project where you will build a complete application using everything you have learned! You will design, code, test, and present a project of your choice. To prepare, think about what you would like to build – a game? A weather app? A contact manager? Bring your ideas to the next class!
You are now a true software engineer – congratulations! See you in Module 8!