Hello, future automation expert! In Module Four, we learned about conditions and decision making. We learned how to make our programs choose different paths. But what if we need to repeat a block of code in many different places? Writing the same code again and again is boring and wastes time. That's where functions come in.
In this module, we will learn about functions — reusable blocks of code that you can call whenever you need them. Functions make your code organised, reusable, and easier to understand. By the end of this module, you will be able to write your own functions and use them in your programs.
Ade is a teacher in Ibadan. Every morning, he greeted each student individually. He said "Good morning, Aisha!", "Good morning, Chidi!", and so on. It took him a long time.
His friend told him about Python functions. Ade wrote: def greet(name): print("Good morning, " + name + "!"). Then he called: greet("Aisha"), greet("Chidi"). Python did all the greetings for him. Ade saved time and energy.
Definition: A function is a reusable block of code that performs a specific task.
Why important: Functions help you avoid repeating code. They make your code organised and easy to read.
Simple explanation: Like a recipe. You write it once, and you can use it many times.
Real-life example: print() is a function that shows text on the screen.
School example: A function that calculates the average of a list of numbers.
Home example: A function that makes a cup of tea (you follow the same steps every time).
Nigerian example: A function that prepares Jollof rice (same steps, different quantities).
Illustration:
+----------------------+
| def greet(name): |
| print("Hello " + name) |
+----------------------+
|
V
+----------------------+
| greet("Aisha") → "Hello Aisha" |
| greet("Chidi") → "Hello Chidi" |
+----------------------+
Mini summary: Functions are reusable blocks of code.
Definition: You define a function using the def keyword, followed by the function name and parentheses ().
Why important: This is how you create your own functions.
Simple explanation: Like writing a recipe in a cookbook.
Real-life example: def say_hello(): print("Hello!")
School example: def welcome(): print("Welcome to class!")
Home example: def clean_room(): print("Cleaning room...")
Nigerian example: def greet_yoruba(): print("Ẹ káàbọ̀!")
Illustration:
def say_hello():
print("Hello, world!")
# This creates a function called say_hello
Mini summary: Use def to define a function.
Definition: Calling a function means running the code inside it. You call a function by writing its name with parentheses.
Why important: This is how you use the function.
Simple explanation: Like following a recipe.
Real-life example: say_hello() runs the function.
School example: welcome() runs the welcome function.
Home example: clean_room() runs the cleaning function.
Nigerian example: greet_yoruba() runs the greeting function.
Illustration:
def say_hello():
print("Hello, world!")
say_hello() # This calls the function
# Output: Hello, world!
Mini summary: Call a function by writing its name with ().
Definition: Parameters are variables that you pass to a function. They make functions flexible.
Why important: Parameters allow you to use the same function with different values.
Simple explanation: Like adding different ingredients to a recipe.
Real-life example: def greet(name): print("Hello, " + name).
School example: def grade(score): if score >= 50: print("Pass").
Home example: def make_tea(type): print("Making " + type + " tea").
Nigerian example: def welcome(city): print("Welcome to " + city).
Illustration:
def greet(name):
print("Hello, " + name)
greet("Aisha") # Hello, Aisha
greet("Chidi") # Hello, Chidi
Mini summary: Parameters are variables that you pass to a function.
Definition: You can have multiple parameters by separating them with commas.
Why important: This makes functions even more flexible.
Simple explanation: Like a recipe that needs multiple ingredients.
Real-life example: def add(a, b): return a + b.
School example: def average(score1, score2): return (score1 + score2) / 2.
Home example: def make_sandwich(bread, filling): print("Making a " + filling + " sandwich with " + bread).
Nigerian example: def greet(name, city): print("Hello, " + name + " from " + city).
Illustration:
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8
Mini summary: Use commas to have multiple parameters.
Definition: A function can return a value using the return statement. The value can be used in the rest of the program.
Why important: This allows functions to produce results that you can use.
Simple explanation: Like getting a result from a calculation.
Real-life example: def add(a, b): return a + b.
School example: def average(scores): return sum(scores) / len(scores).
Home example: def square(number): return number * number.
Nigerian example: def convert_to_naira(dollar): return dollar * 1600.
Illustration:
def square(number):
return number * number
result = square(5)
print(result) # 25
Mini summary: Use return to send a value back.
Definition: Functions are very useful for automation. You can write a function once and use it many times.
Why important: This saves time and makes your code clean.
Simple explanation: Like a machine that does a task automatically.
Real-life example: A function that calculates tax for different amounts.
School example: A function that calculates the average of a list of grades.
Home example: A function that converts between units.
Nigerian example: A function that converts Naira to dollars.
Illustration:
def calculate_tax(amount):
tax = amount * 0.1
return tax
price = 1000
tax = calculate_tax(price)
print("Tax: " + str(tax)) # Tax: 100.0
Mini summary: Functions are powerful tools for automation.
Definition: You can set default values for parameters. If the user doesn't provide a value, the default is used.
Why important: This makes functions easier to use.
Simple explanation: Like a default setting on a device.
Real-life example: def greet(name="Friend"): print("Hello, " + name).
School example: def pass_mark(mark=50): print("Pass mark is " + str(mark)).
Home example: def make_tea(type="green"): print("Making " + type + " tea").
Nigerian example: def welcome(city="Nigeria"): print("Welcome to " + city).
Illustration:
def greet(name="Friend"):
print("Hello, " + name)
greet() # Hello, Friend
greet("Aisha") # Hello, Aisha
Mini summary: Default parameters provide a fallback value.
Definition: You can use conditions inside functions to make decisions.
Why important: This makes your functions smarter.
Simple explanation: Like a recipe that changes based on what you have.
Real-life example: def check_age(age): if age >= 18: print("Adult") else: print("Child").
School example: def grade(score): if score >= 50: return "Pass" else: return "Fail".
Home example: def is_weekend(day): if day == "Saturday" or day == "Sunday": return True else: return False.
Nigerian example: def region(state): if state == "Lagos": return "South-West" else: return "Other".
Illustration:
def grade(score):
if score >= 50:
return "Pass"
else:
return "Fail"
print(grade(75)) # Pass
print(grade(45)) # Fail
Mini summary: Use conditions inside functions to make decisions.
Definition: You can use loops inside functions to process data.
Why important: This allows you to automate repetitive tasks.
Simple explanation: Like a machine that processes a list of items.
Real-life example: def sum_list(numbers): total = 0; for num in numbers: total += num; return total.
School example: def average(numbers): total = sum(numbers); return total / len(numbers).
Home example: def print_shopping_list(items): for item in items: print(item).
Nigerian example: def print_states(states): for state in states: print(state + " is in Nigeria").
Illustration:
def sum_list(numbers):
total = 0
for num in numbers:
total += num
return total
print(sum_list([1, 2, 3, 4, 5])) # 15
Mini summary: Use loops inside functions to process data.
Definition: Functions help you organise your code into logical parts.
Why important: Well-organised code is easier to read, debug, and maintain.
Simple explanation: Like organising a toolbox with different compartments.
Real-life example: A program with separate functions for input, processing, and output.
School example: A program with a function for each task.
Home example: A program with a function for each family member.
Nigerian example: A program with a function for each state.
Illustration:
def get_input():
# gets input from user
def process_data(data):
# processes the data
def show_output(result):
# shows the result
Mini summary: Functions organise your code.
Definition: Once you write a function, you can use it in any program.
Why important: This saves you from rewriting code.
Simple explanation: Like sharing a recipe with a friend.
Real-life example: You write a function to calculate tax and use it in many projects.
School example: You write a function to calculate the average and use it for different classes.
Home example: You write a function to convert units and use it for different recipes.
Nigerian example: You write a function to greet in Yoruba and use it in different programs.
Illustration:
# In one program
def add(a, b):
return a + b
# In another program
result = add(10, 20) # 30
Mini summary: Reuse functions in different programs.
Definition: Scope is where a variable exists. Variables inside a function are local — they exist only inside that function.
Why important: This helps prevent conflicts between variables.
Simple explanation: Like each person having their own name tag.
Real-life example: A variable inside a function is separate from a variable outside.
School example: def my_function(): x = 10 — x only exists inside.
Home example: def clean_room(): room = "living room" — room only exists inside.
Nigerian example: def greet(): message = "Hello" — message only exists inside.
Illustration:
def my_function():
x = 10
print(x) # Works
my_function()
print(x) # Error! x does not exist outside
Mini summary: Variables inside functions are local.
Definition: You can add a docstring (a description) to a function to explain what it does.
Why important: Documentation helps you and others understand the function.
Simple explanation: Like writing a note to explain something.
Real-life example: def add(a, b): """Adds two numbers.""" return a + b
School example: def average(scores): """Returns the average of a list."""
Home example: def make_tea(): """Makes a cup of tea."""
Nigerian example: def greet(name): """Greets a person."""
Illustration:
def add(a, b):
"""Adds two numbers and returns the result."""
return a + b
Mini summary: Document your functions with docstrings.
Definition: You have learned the most important concepts: variables, lists, loops, conditions, and functions.
Why important: You are now ready to start building real automation projects.
Simple explanation: You have all the tools you need.
Real-life example: You can now write programs that automate tasks.
School example: You can automate grading and reports.
Home example: You can automate chores and reminders.
Nigerian example: You are a Python coder ready to solve problems!
Illustration:
Variables + Lists + Loops + Conditions + Functions = Automation
You are ready! 🎉
Mini summary: You are ready to build automation projects!
def.def greet(name):print("Hello, " + name)greet("Aisha")
Step 1: def greet(name):
Step 2: print("Hello, " + name)
Step 3: greet("Aisha") # Output: Hello, Aisha
def greet(name): print("Hello, " + name)def add(a, b): return a + bdef average(numbers): return sum(numbers) / len(numbers)def calculate_tax(amount): return amount * 0.1def celsius_to_fahrenheit(c): return c * 9/5 + 32def greet_yoruba(name): print("Ẹ káàbọ̀, " + name)def naira_to_dollar(naira): return naira / 1600def region(state): if state == "Lagos": return "South-West" else: return "Other"def make_jollof(rice, chicken): print("Making Jollof rice with " + chicken)def is_lagos(city): return city == "Lagos"def say_hello(): print("Hello, world!")def square(number): return number * numberdef favourite_food(food): print("I love " + food)def is_even(number): return number % 2 == 0def birthday(name): print("Happy Birthday, " + name)def clean_room(room): print("Cleaning " + room)def make_tea(type="green"): print("Making " + type + " tea")def check_homework(done): if done: print("Great job") else: print("Do it now")def do_chore(chore): print("Doing " + chore)def remind(task): print("Reminder: " + task)print() and len().def to define a function.().def greet() needs a colon: def greet():return when needed.
+----------------------+
| def function_name(parameters): |
| # code block |
| return result |
+----------------------+
| Function | Input | Output |
|---|---|---|
add(a, b) | 5, 3 | 8 |
greet(name) | "Aisha" | "Hello, Aisha" |
square(n) | 4 | 16 |
| Without Functions | With Functions |
|---|---|
| Repeated code | One function used many times |
| Hard to read | Easy to read |
| Hard to change | Easy to change |
| Long programs | Short programs |
In this module, we learned about functions. We discovered that functions are reusable blocks of code that help us avoid repetition. We learned how to define functions, call them, use parameters, and return values. We also learned about default parameters, scope, and documenting functions. Functions are a powerful tool for automation. With functions, you can write clean, organised, and reusable code. Great work!
def function_name():function_name()return do? Sends a value back.return do?________ keyword to define a function. (def)________ to send a value back. (return)func. (False)return sends a value back. (True)def function_name(): ✅function function_name():func function_name():function_name() ✅call function_name()run function_name()return do?def ✅funcfunctiondef add(a, b): return a + b with add(5, 3)?Match the word with its meaning:
| Word | Meaning |
|---|---|
| 1. Function | A) Sends a value back |
| 2. Parameter | B) A reusable block of code |
| 3. Return | C) A variable passed to a function |
| 4. Define | D) A description of a function |
| 5. Docstring | E) To create a function |
(Answers: 1-B, 2-C, 3-A, 4-E, 5-D)
Scenario 1: You need to greet many students every morning. Write a function that takes a name and prints a greeting.
Scenario 2: You need to calculate the area of a circle for different radii. Write a function that takes the radius and returns the area.
In groups of 3, write a function that takes a list of numbers and returns the sum, average, and maximum. Test it with different lists.
Write a function that takes a number and returns "Even" if it's even and "Odd" if it's odd. Test it with different numbers.
Create a program that uses functions to greet different people, calculate the average of a list of numbers, and check if a number is even or odd.
Write a function that calculates the tax on an amount. Tax is 10% of the amount. Test it with different amounts.
Write a function that takes a list of numbers and returns a new list with only the even numbers. Use a loop inside the function.
Fill-in-the-blank: 1-function, 2-def, 3-parentheses, 4-Parameters, 5-return
True/False: 1-T, 2-F, 3-T, 4-T, 5-F
Matching: 1-B, 2-C, 3-A, 4-E, 5-D
def to define a function.return to send a value back.In Module Six, we will learn about working with files. We will learn how to read, write, and manage files using Python. Before the next session, think of a file you would like to create or read.
See you in Module Six! 🎉
End of Module Five · Functions