Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← Advanced Software Engineering · Lesson 8 of 10

Module Seven

📖 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.
8
Module 7 · Advanced Software Engineer

🌀 Module 7: Recursion, Lambda & JSON

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!

🎯 Learning Objectives

After this module, you will be able to:

  • Explain what recursion is and when to use it.
  • Write recursive functions (like factorial and Fibonacci).
  • Understand the base case and recursive case.
  • Explain what a lambda function is.
  • Use lambda functions with map(), filter(), and sorted().
  • Read and write JSON data.
  • Convert Python objects to JSON and vice versa.

📖 Warm‑up Story: Ngozi’s Russian Dolls

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!

📘 Lesson 1: What is Recursion?

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.

📘 Lesson 2: Base Case and Recursive Case

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.

📘 Lesson 3: Factorial – A Classic Recursive Problem

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.

📘 Lesson 4: Fibonacci – Another Recursive Classic

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.

📘 Lesson 5: Recursion vs Iteration (Loops)

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.

📘 Lesson 6: What is a Lambda Function?

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.

📘 Lesson 7: Using Lambda with 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.

📘 Lesson 8: Using Lambda with 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.

📘 Lesson 9: Using Lambda with 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.

📘 Lesson 10: What is JSON?

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.

📘 Lesson 11: Python and JSON – The json Module

Definition: 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.

📘 Lesson 12: Reading and Writing JSON Files

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.

📘 Lesson 13: JSON with Dictionaries and Lists

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.

📘 Lesson 14: When to Use Recursion, Lambda, and JSON

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.

📘 Lesson 15: Putting It All Together

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.

📚 Key Vocabulary

WordSimple Definition
RecursionWhen a function calls itself.
Base CaseThe condition that stops recursion.
Recursive CaseThe part where the function calls itself.
LambdaA 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.
JSONA standard format for data exchange.
dumps()Converts Python object to JSON string.
loads()Converts JSON string to Python object.

🧠 Important Concepts

  • Stack Overflow: If recursion doesn't have a base case, it will call itself infinitely and cause a stack overflow error.
  • Anonymous Functions: Lambdas are anonymous – they don't have a name, which is why they are useful for short, one‑time operations.
  • Data Interchange: JSON is language‑independent – it's used by many programming languages, not just Python.
  • Serialisation: Converting a Python object to JSON is called serialisation; converting JSON back is deserialisation.

👣 Step‑by‑Step Explanations

How to write a recursive function

  1. Identify the base case – the simplest version of the problem.
  2. Identify the recursive case – how to break the problem into a smaller version.
  3. Write the function that checks the base case first, then calls itself.
  4. Test with small inputs to ensure it works.

How to use JSON in Python

  1. Import the json module.
  2. Use json.dumps() to convert a Python object to a JSON string.
  3. Use json.loads() to convert a JSON string to a Python object.
  4. Use json.dump() to write JSON to a file.
  5. Use json.load() to read JSON from a file.

🌍 Real‑life Examples

  • Recursion: A file system – searching through folders and sub‑folders.
  • Lambda: A quick calculation in a spreadsheet.
  • JSON: API responses – like getting weather data from a server.

🇳🇬 Nigerian Examples

  • Recursion: A market directory – asking each trader for directions.
  • Lambda: A trader applying a discount to all items.
  • JSON: A fintech app sending transaction data to a server.
  • Recursion: A family tree – exploring ancestors.

🎮 Fun Examples Children Can Relate To

  • Recursion: Russian dolls – opening one to find another.
  • Lambda: A quick note on a sticky pad.
  • JSON: Saving your game progress in a file.

🏠 Everyday Examples

  • Recursion: Peeling an onion – layer by layer.
  • Lambda: A quick price calculation in your head.
  • JSON: A shopping list stored on your phone.

🧑‍🏫 Teacher Notes

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.

👪 Parent Tips

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.

✨ Interesting Facts

  • Recursion is used in many algorithms, like searching and sorting.
  • Lambda functions are also called “arrow functions” in other languages.
  • JSON was derived from JavaScript, but it's now used by almost every programming language.

💡 Did You Know?

  • Did you know that Python's recursion limit is usually 1000 – meaning you can't go deeper than 1000 calls?
  • Did you know that lambda functions can be used anywhere a function is expected?
  • Did you know that JSON is human‑readable – you can open a JSON file and read it like a text file?

🔔 Remember This

  • Recursion must have a base case to stop.
  • Lambdas are one‑line functions – they are great for short operations.
  • JSON is a universal data format – it's like the lingua franca of data.
  • You can combine recursion, lambda, and JSON in powerful ways.
  • Always test recursive functions with small inputs first.

⚠️ Common Mistakes

  • Forgetting the base case – causes infinite recursion.
  • Using recursion for simple loops – sometimes a loop is simpler and faster.
  • Overcomplicating lambda functions – lambdas are for simple operations, not complex logic.
  • Not handling JSON errors – like missing keys or invalid format.
  • Forgetting to import the json module – you must import it to use JSON.

✅ Best Practices

  • Always define a base case in recursion.
  • Use recursion for naturally recursive problems (like tree traversal).
  • Use lambdas for short, one‑time operations.
  • Use with open() when working with JSON files – it handles closing the file.
  • Validate JSON data before using it – check if keys exist.

📊 Diagrams & Tables

Recursion Flowchart

        Start
          |
          v
        Is base case true? → Yes → Return result
          |
         No
          |
          v
        Call function with smaller input
          |
          v
        (go back to start)
    

Comparison Table: Recursion vs Iteration

FeatureRecursionIteration
DefinitionFunction calls itselfUses loops (for, while)
CodeOften shorter, more elegantOften longer
PerformanceCan be slower (function call overhead)Usually faster
RiskStack overflow if no base caseInfinite loop if condition never false

JSON Example Structure

        {
            "student": {
                "name": "Chidi",
                "age": 10,
                "subjects": ["Math", "Science"]
            }
        }
    

📝 End‑of‑Module Summary

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!

❓ Frequently Asked Questions

  1. What is recursion? A function calling itself to solve a smaller version of the same problem.
  2. What is a base case? The condition that stops recursion.
  3. What is a lambda function? A small, anonymous function defined in one line.
  4. What is map()? Applies a function to every item in an iterable.
  5. What is filter()? Selects items from an iterable based on a condition.
  6. What is JSON? A standard format for storing and exchanging data.
  7. How do I convert a Python object to JSON? Use json.dumps().
  8. How do I convert JSON to a Python object? Use json.loads().
  9. Can I use recursion for any problem? No – use it for problems that are naturally recursive.
  10. What is the advantage of JSON? It's human‑readable and supported by many languages.

🤔 Review Questions

  1. What is recursion?
  2. What is a base case in recursion?
  3. What is a lambda function?
  4. How do you use map() with a lambda?
  5. How do you use filter() with a lambda?
  6. What is JSON?
  7. How do you convert a Python dictionary to a JSON string?
  8. How do you convert a JSON string to a Python dictionary?
  9. How do you write JSON to a file?
  10. How do you read JSON from a file?
  11. What is the difference between json.dumps() and json.dump()?
  12. What is the difference between json.loads() and json.load()?
  13. What is a stack overflow?
  14. When should you use recursion?
  15. Why is JSON popular for data exchange?

📝 Fill‑in‑the‑Blank

  1. ______ is when a function calls itself.
  2. The ______ case stops recursion.
  3. A ______ is a small, anonymous function.
  4. ______ applies a function to every item in a list.
  5. ______ selects items that satisfy a condition.
  6. ______ is a standard format for data exchange.
  7. ______ converts a Python object to a JSON string.
  8. ______ converts a JSON string to a Python object.
  9. ______ writes JSON to a file.
  10. ______ reads JSON from a file.

✅ True or False

  1. Recursion can cause a stack overflow if there is no base case. (True)
  2. Lambda functions can have multiple lines. (False – they are one line)
  3. map() returns a list. (False – it returns an iterator)
  4. filter() returns an iterator. (True)
  5. JSON stands for JavaScript Object Notation. (True)
  6. JSON is only used in JavaScript. (False – it's used everywhere)
  7. json.dumps() writes JSON to a file. (False – it returns a string)
  8. json.load() reads JSON from a file. (True)
  9. Recursion is always faster than iteration. (False – it's often slower)
  10. Lambda functions can be assigned to variables. (True)

🔘 Multiple Choice

  1. What is recursion?
    A) A loop
    B) A function that calls itself
    C) A type of variable
    D) A module
    Answer: B
  2. What stops recursion?
    A) The recursive case
    B) The base case
    C) The lambda
    D) The JSON
    Answer: B
  3. What is a lambda function?
    A) A large function
    B) A small, anonymous function
    C) A recursive function
    D) A module
    Answer: B
  4. What does map() do?
    A) Filters items
    B) Applies a function to every item
    C) Sorts items
    D) Creates a dictionary
    Answer: B
  5. What does filter() do?
    A) Applies a function to every item
    B) Selects items that satisfy a condition
    C) Sorts items
    D) Creates a dictionary
    Answer: B
  6. What is JSON?
    A) A programming language
    B) A data format
    C) A type of loop
    D) A function
    Answer: B
  7. How do you convert a Python object to JSON?
    A) json.load()
    B) json.dumps()
    C) json.dump()
    D) json.loads()
    Answer: B
  8. How do you convert JSON to a Python object?
    A) json.load()
    B) json.dumps()
    C) json.dump()
    D) json.loads()
    Answer: D
  9. What is the base case in recursion?
    A) The first call
    B) The condition that stops recursion
    C) The last call
    D) The recursive call
    Answer: B
  10. Which of these is NOT a valid JSON type?
    A) String
    B) Number
    C) Array
    D) Set
    Answer: D
  11. What does json.dump() do?
    A) Converts JSON to a Python object
    B) Writes JSON to a file
    C) Reads JSON from a file
    D) Converts Python to JSON string
    Answer: B
  12. What does json.load() do?
    A) Converts JSON to a Python object
    B) Writes JSON to a file
    C) Reads JSON from a file
    D) Converts Python to JSON string
    Answer: C
  13. Which is a recursive problem?
    A) Summing a list
    B) Factorial
    C) Finding the maximum
    D) All of the above
    Answer: B
  14. What is a lambda function?
    A) A named function
    B) An anonymous function
    C) A recursive function
    D) A built‑in function
    Answer: B
  15. Which of these is a valid lambda?
    A) lambda x: x*2
    B) lambda x: return x*2
    C) lambda(x): x*2
    D) lambda x, y: x+y
    Answer: A

🔗 Matching Exercises

TermDefinition
1. RecursionA. A small, anonymous function
2. LambdaB. A function that calls itself
3. Base CaseC. Converts Python to JSON string
4. dumps()D. Stops recursion
5. JSONE. A standard data format

Answers: 1‑B, 2‑A, 3‑D, 4‑C, 5‑E

✏️ Short Answer Questions

  1. Explain recursion and give an example.
  2. What is the difference between json.dumps() and json.dump()?
  3. What is a lambda function and when would you use it?
  4. What is the difference between map() and filter()?
  5. Why is JSON widely used?

🎭 Scenario‑based Exercises

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.

👥 Group Activity

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.

🧑 Individual Activity

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.

💬 Classroom Discussion Questions

  1. Why is the base case so important in recursion?
  2. When would you use a lambda instead of a regular function?
  3. What are the advantages of JSON over other data formats?
  4. Can you think of a situation where recursion is a better choice than iteration?

🛠️ Mini Project

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.

📋 Practical Assignment

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.

🏆 Challenge Exercise

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.

📌 Quiz Answers

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.

🎁 Key Takeaways

  • Recursion is a powerful technique – always use a base case.
  • Lambdas are great for short, simple operations.
  • JSON is the standard for data exchange – it's easy to read and write.
  • Recursion, lambda, and JSON often work together in real programs.
  • Always test your code with small inputs first.

🔜 Preparation for Module 8

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!

🏆 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.
→