Hello, brilliant builder! In Module 3, you learned how to use loops and lists to make your programs more powerful. You even wrote your first real Python programs. Now, it is time to learn how to organise your code so it stays neat, reusable, and easy to understand.
Have you ever built something with Lego? You use the same blocks to build many different things. In programming, functions are like Lego blocks – you write a piece of code once, and then you can use it again and again!
We will also learn about modules – which are like boxes full of useful tools that other people have already built. And we will learn how to write clean code – code that is easy to read and understand, even for beginners.
By the end of this module, you will be able to write programs that are organised, reusable, and professional. Let’s get started!
After this module, you will be able to:
Aisha loved making smoothies. She had a big recipe book with many smoothie recipes. Every time a customer ordered, she would find the recipe and make it from scratch. But she noticed that many steps were the same – peel, chop, blend, pour.
One day, she had an idea. She wrote down the common steps as a recipe template (like a function). For each smoothie, she would just write the ingredients (the parameters) and the template would do the rest.
She also kept a box of tools – a blender, a knife, a juicer – that she could use anytime. These were like modules – ready‑to‑use tools.
Aisha could now serve customers much faster, and her recipes were easy to change. She had become a master organiser – just like a software engineer!
Now, let’s learn how to write our own recipe templates – functions!
Definition: A function is a block of reusable code that performs a specific task. You can call (use) it whenever you need it.
Why is it important? Functions help you avoid repeating code. Write once, use many times!
Simple explanation: Think of a function like a recipe in a cookbook. The recipe has a name, a list of ingredients, and a set of instructions. Once you have the recipe, you can make the dish any time.
Real‑life example: A washing machine has a “wash” function – you put clothes in, and it does the washing.
School example: Your teacher uses a “mark_attendance” function – she calls it every day.
Home example: You have a “make_tea” function – you follow the same steps each time.
Nigerian example: A bank has a “transfer_money” function – it is used whenever a customer transfers funds.
Illustration:
+------------------+
| Function |
| "greet" |
+--------+---------+
|
+--------v---------+
| Input: name |
+--------+---------+
|
+--------v---------+
| print("Hello, |
| " + name)|
+--------+---------+
|
+--------v---------+
| Output: Hello, |
| [name] |
+------------------+
Mini summary: A function is a reusable block of code that does a specific job.
Definition: Defining a function means creating it – giving it a name and writing the instructions it will perform.
Why is it important? You must define a function before you can use it.
Simple explanation: Like writing a new recipe in your cookbook – you write the instructions, then you can follow them later.
Real‑life example: You write a to‑do list – each task is like a function definition.
School example: Your teacher writes the lesson plan – it’s a plan to be followed.
Home example: You write a shopping list – it defines what you need to buy.
Nigerian example: A farmer writes a planting schedule – it defines when to plant each crop.
Illustration:
def greet():
print("Hello!")
# This defines a function called "greet".
# When we call it, it will print "Hello!".
Mini summary: You define a function using the def keyword, followed by the name and parentheses.
Definition: Calling a function means running (executing) the code inside it.
Why is it important? A function does nothing until you call it – you have to tell it to work!
Simple explanation: You have a recipe for a cake. Calling the function is like actually baking the cake.
Real‑life example: You press the “on” button on your TV – that calls the “turn_on” function.
School example: The teacher says “take attendance” – that calls the attendance function.
Home example: You ask your smart speaker to “play music” – that calls a function.
Nigerian example: You use a POS machine to “withdraw cash” – that calls a function.
Illustration:
# Define the function
def greet():
print("Hello!")
# Call the function
greet() # This prints "Hello!"
Mini summary: You call a function by writing its name followed by parentheses.
Definition: Parameters are variables that you pass to a function – they are like ingredients for the recipe.
Why is it important? Parameters make functions flexible – they can work with different data.
Simple explanation: A recipe for a smoothie needs ingredients like fruit and milk. The fruit is a parameter – you can change it to make different smoothies.
Real‑life example: A vending machine – you insert money (a parameter) and get a snack.
School example: The attendance function takes a “student name” as a parameter.
Home example: The “set_alarm” function takes a “time” parameter.
Nigerian example: A mobile banking function “transfer” takes “amount” and “recipient” as parameters.
Illustration:
def greet(name):
print("Hello, " + name)
greet("Aisha") # Prints: Hello, Aisha
greet("Chidi") # Prints: Hello, Chidi
Mini summary: Parameters are variables that you pass into a function to customise its behaviour.
Definition: A return value is the output that a function sends back after it finishes.
Why is it important? Functions often compute something – the return value is the result you can use.
Simple explanation: You give money to a shopkeeper (input), they give you change (return value).
Real‑life example: A calculator – you input numbers, it returns the sum.
School example: You answer a test – the teacher returns a score.
Home example: A thermometer – it returns the temperature.
Nigerian example: A bank function “check_balance” returns the account balance.
Illustration:
def add(a, b):
result = a + b
return result
sum = add(5, 3)
print(sum) # Prints 8
Mini summary: The return statement sends a value back from the function.
Definition: Functions make your code modular – you can build your program from small, independent pieces.
Why is it important? They save you time, reduce errors, and make your code easier to read.
Simple explanation: Instead of repeating the same code, you write a function once and use it many times.
Real‑life example: A chef uses the same knife‑cutting technique for many dishes – that’s a function.
School example: You use the same study method for different subjects.
Home example: You use the same cleaning routine for each room.
Nigerian example: A driver uses the same “start_engine” function for different cars.
Illustration:
# Without a function (repeated code)
print("Good morning!")
print("Good morning!")
print("Good morning!")
# With a function (reusable)
def greet():
print("Good morning!")
greet()
greet()
greet()
Mini summary: Functions save time and reduce repetition – they are a key tool for any programmer.
Definition: Scope means where a variable can be accessed – inside a function, it’s local; outside, it’s global.
Why is it important? It helps you keep your code organised and prevents conflicts.
Simple explanation: A variable inside a function is like a secret – only that function can see it.
Real‑life example: Your phone’s password is known only to you (local), not to everyone (global).
School example: Your test answers are only in your test paper (local), not in everyone’s.
Home example: Your room is your space – only you know where your things are.
Nigerian example: A market trader’s pricing strategy is local – not everyone knows it.
Illustration:
x = 10 # global variable
def my_function():
y = 5 # local variable
print(x) # can access global x
print(y) # can access local y
# print(y) # ERROR! y is not defined outside
Mini summary: Variables defined inside a function are local; variables defined outside are global.
Definition: A module is a file containing Python code – usually functions and variables – that you can import and use.
Why is it important? Modules let you use code that others have written – you don’t have to reinvent the wheel.
Simple explanation: A module is like a toolbox. You open it, pick a tool, and use it.
Real‑life example: A carpenter has a toolbox with a hammer, saw, and screws – all ready to use.
School example: A teacher has a resource book with ready‑made exercises.
Home example: A kitchen has a spice rack – you use different spices for different dishes.
Nigerian example: A mechanic has a set of tools – each tool is like a module.
Illustration:
import math # import the math module
print(math.sqrt(16)) # 4.0 (square root)
print(math.pi) # 3.14159...
Mini summary: Modules are pre‑written code that you can import to add new capabilities.
Definition: Importing means bringing a module into your program so you can use its functions and variables.
Why is it important? It gives you access to a huge library of code.
Simple explanation: Like borrowing a book from the library – you bring it to your desk to read.
Real‑life example: You import a video player to watch a movie.
School example: Your teacher uses a textbook from the library.
Home example: You use a recipe from a cookbook.
Nigerian example: A trader imports goods to sell in the market.
Illustration:
import random # module for random numbers
print(random.randint(1, 10)) # prints a random number between 1 and 10
Mini summary: You import modules using the import keyword.
Definition: You can create your own module by saving a Python file and then importing it into another program.
Why is it important? It allows you to reuse your code across many projects.
Simple explanation: You write a list of useful functions in a file, and you can use them in any program.
Real‑life example: You write a collection of recipes in a notebook – it becomes your own cookbook.
School example: You make a study guide – you can use it for different exams.
Home example: You make a list of chore routines – you can follow them every week.
Nigerian example: A tailor creates a pattern for a dress – they can use it for many dresses.
Illustration:
# Save this as my_tools.py
def greet(name):
print("Hello, " + name)
# In another file:
import my_tools
my_tools.greet("Aisha") # Hello, Aisha
Mini summary: You can create your own modules by saving Python code in a file and importing it.
Definition: Clean code is code that is easy to read, understand, and modify.
Why is it important? Clean code saves time and reduces bugs – it’s like a tidy room.
Simple explanation: Clean code is like a well‑written story – clear sentences, good spacing, and understandable words.
Real‑life example: A well‑organised book – each chapter has a title and clear sections.
School example: Your notebook with neat handwriting and headings.
Home example: A tidy kitchen where everything is in its place.
Nigerian example: A well‑organised market – each section is clearly labelled.
Illustration:
# Clean code example
def calculate_average(scores):
"""This function calculates the average of a list of scores."""
total = sum(scores)
count = len(scores)
average = total / count
return average
Mini summary: Clean code is easy to read, has good variable names, and has comments to explain.
Definition: Comments are notes in the code that are ignored by the computer – they are for human readers.
Why is it important? They explain what the code does – helpful for yourself and others.
Simple explanation: Like writing margin notes in a book to remember important points.
Real‑life example: A recipe with notes: “Add salt to taste”.
School example: Your notes on a textbook – highlighting key sentences.
Home example: A sticky note on the fridge: “Buy milk”.
Nigerian example: A signpost in the market: “Shoe section”.
Illustration:
# This is a comment
# It explains that the next line prints a greeting
print("Hello!")
Mini summary: Comments start with # and are ignored by Python – they are for programmers.
Definition: Naming conventions are guidelines for naming variables, functions, and modules to make code more readable.
Why is it important? Good names make your code self‑explanatory – you don’t need extra comments.
Simple explanation: Use names that describe what the variable or function does.
Real‑life example: A street is named “Market Road” – you know where it leads.
School example: A book titled “Mathematics for Beginners” – you know what it’s about.
Home example: A drawer labelled “Cutlery” – you know what’s inside.
Nigerian example: A bus named “Eko” – you know it goes to Lagos.
Illustration:
# Good names
user_age = 10
def calculate_score():
...
# Bad names
a = 10
def cs():
...
Mini summary: Use descriptive, clear names – it makes your code easier to understand.
Definition: Refactoring is the process of improving the design of existing code without changing its behaviour.
Why is it important? It makes code cleaner, faster, and easier to maintain.
Simple explanation: Like cleaning your room – you rearrange things to make them more organised.
Real‑life example: A chef reorganises the kitchen to work faster.
School example: You rewrite your notes to make them clearer.
Home example: You redecorate your room for better use of space.
Nigerian example: A shop owner rearranges the shop to make it easier for customers.
Illustration:
# Before refactoring (repeated code)
total = 0
for i in range(5):
total = total + i
print(total)
# After refactoring (using a function)
def sum_range(n):
total = 0
for i in range(n):
total = total + i
return total
print(sum_range(5))
Mini summary: Refactoring is improving your code’s structure without changing what it does.
Definition: Reusability means using the same code (like a function or module) in multiple places.
Why is it important? It saves time, reduces errors, and makes programs easier to maintain.
Simple explanation: Like using the same recipe to bake many cakes.
Real‑life example: A template for a letter – you fill in the name and address.
School example: You use the same study technique for different subjects.
Home example: You use the same chore list every week.
Nigerian example: A tailor uses the same pattern for many different fabrics.
Illustration:
# Reusable function
def welcome(name):
print("Welcome, " + name + "!")
welcome("Aisha")
welcome("Chidi")
welcome("Ada")
Mini summary: Reusability is a core principle of software engineering – write once, use many times.
| Word | Simple Definition |
|---|---|
| Function | A reusable block of code that does a specific task. |
| Parameter | An input that you pass to a function. |
| Return Value | The output that a function sends back. |
| Module | A file containing Python code that you can import. |
| Import | To bring a module into your program. |
| Scope | Where a variable is accessible – local or global. |
| Clean Code | Code that is easy to read and understand. |
| Comment | A note in the code that is ignored by the computer. |
| Refactoring | Improving code without changing what it does. |
| Reusability | Using the same code in multiple places. |
def keyword, followed by the function name and parentheses.: and indent the function body.import module_name at the top of your file.module_name.function_name().from module_name import function_name to import a specific function.This module is about organisation and reuse. Encourage students to identify repeated patterns in their code and turn them into functions. Use physical analogies (Lego blocks, recipes) to explain functions. Emphasise the importance of writing clean, readable code from the beginning.
Ask your child to think about routines they repeat daily (like brushing teeth) – that’s a function! Discuss how they could “write a recipe” for that routine. Encourage them to keep their code clean and organised, just like keeping their room tidy.
as? (e.g., import math as m)def, you call by name.calculate_average instead of ca.
+------------------+
| Start |
+--------+---------+
|
+--------v---------+
| Call function |
+--------+---------+
|
+--------v---------+
| Execute code |
+--------+---------+
|
+--------v---------+
| Return result |
+--------+---------+
|
+--------v---------+
| Continue |
+------------------+
| Feature | Function | Module |
|---|---|---|
| Definition | A reusable block of code | A file containing code |
| Scope | Inside a program | Can be used across programs |
| Example | def greet(): | import math |
| Reusability | Within one program | Across many programs |
def add(a, b):
"""This function adds two numbers and returns the result."""
return a + b
You have completed Module 4 – a huge step towards becoming an advanced software engineer! You learned about functions – the building blocks of reusable code. You now know how to define functions, pass parameters, and return values. You also learned about modules – ready‑made tools that you can import and use. You discovered the importance of clean code, comments, and good naming conventions.
With these skills, you can write programs that are organised, easy to understand, and easy to improve. You are now ready to build larger, more complex applications.
Keep practising – every great engineer started where you are now!
import keyword – e.g., import math.function name():def name():define name():func name():include mathimport mathuse mathrequire mathfunctiondefdefinefunc| Term | Definition |
|---|---|
| 1. Function | A. A reusable block of code |
| 2. Parameter | B. An input to a function |
| 3. Return | C. The output from a function |
| 4. Module | D. A file containing Python code |
| 5. Comment | E. A note in the code |
Answers: 1‑A, 2‑B, 3‑C, 4‑D, 5‑E
Scenario 1: You are building a simple calculator. Write a function for addition, subtraction, multiplication, and division. Each function takes two numbers as parameters and returns the result.
Scenario 2: You have a list of student names. Write a function that takes a list and a name, and returns True if the name is in the list, False otherwise.
In groups, write a program that uses a function to calculate the average of a list of numbers. Then, write another function that uses the first function to calculate the average of multiple groups. Present your code and explain how you used functions to keep the code organised.
Write a Python program that includes a function called is_even that takes a number and returns True if it is even, False otherwise. Then, use a loop to ask the user for numbers and print whether each is even or odd.
Build a Text‑Based Adventure Game: Write a Python program that uses functions to handle different parts of the game – e.g., start_game(), show_instructions(), play_round(). Use parameters and return values to pass data between functions.
Write a Python program that uses the math module to calculate the square root, sine, and cosine of a number entered by the user. Use functions to organise your code.
Write a Python program that defines a function fibonacci(n) that returns the nth Fibonacci number (the first two are 1, 1, then each is the sum of the previous two). Test it with different values.
Fill‑in‑the‑Blank: 1. function, 2. def, 3. Parameters, 4. return, 5. module, 6. import, 7. Clean, 8. Comments, 9. Refactoring, 10. Don’t Repeat Yourself.
True/False: 1F, 2T, 3T, 4F, 5T, 6F, 7F, 8F, 9T, 10T.
Multiple Choice: 1B, 2B, 3B, 4B, 5B, 6B, 7B, 8B, 9B, 10B, 11B, 12B, 13B, 14B, 15C.
In Module 5, you will learn about objects and classes – a more advanced way to organise code. You will also explore file handling, so your programs can save data and read it back. To prepare, think about real‑world objects (like a car or a phone) and how they have properties (color, speed) and actions (start, stop).
You are becoming a true engineer – keep going! See you in Module 5!