Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← Python For Automation · Lesson 7 of 14

Module Five

📖 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.
7
Module Five · Python for Automation

🔧 Module Five · Functions


📖 Module Introduction

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.

🎯 Learning Objectives

  • Understand what functions are and why they are useful.
  • Define and call your own functions.
  • Use parameters to make functions flexible.
  • Return values from functions.
  • Build reusable code for automation.

📚 Warm-up Story · Ade's Greeting Function

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.

🧩 Main Lessons

Lesson 1 · What is a Function?

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.


Lesson 2 · Defining a Function

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.


Lesson 3 · Calling 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 ().


Lesson 4 · Parameters

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.


Lesson 5 · Multiple Parameters

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.


Lesson 6 · Return Values

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.


Lesson 7 · Using Functions in Automation

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.


Lesson 8 · Default Parameter Values

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.


Lesson 9 · Functions with Conditions

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.


Lesson 10 · Functions with Loops

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.


Lesson 11 · Organising Code with Functions

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.


Lesson 12 · Reusing Functions

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.


Lesson 13 · Functions and Scope

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.


Lesson 14 · Documenting Functions

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.


Lesson 15 · You Are Ready!

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!


📌 Key Vocabulary

  • Function: A reusable block of code.
  • Define: To create a function using def.
  • Call: To run a function.
  • Parameter: A variable passed to a function.
  • Return: To send a value back.
  • Default parameter: A parameter with a default value.
  • Scope: Where a variable exists.
  • Docstring: A description of a function.
  • Reusable: Can be used multiple times.
  • Organised: Code that is neat and easy to understand.

🧠 Important Concepts

  • Functions are reusable: Write once, use many times.
  • Parameters add flexibility: Pass different values.
  • Return values produce results: Use the output of a function.
  • Functions organise code: Keeps your code clean.
  • Functions are the building blocks of automation.

👣 Step-by-Step Explanations

How to Write and Use a Function

  1. Define the function: def greet(name):
  2. Write the code: print("Hello, " + name)
  3. Call the function: greet("Aisha")
  4. Use the result: If it returns a value, store it in a variable.

Example:

    Step 1: def greet(name):
    Step 2:     print("Hello, " + name)
    Step 3: greet("Aisha")  # Output: Hello, Aisha
            

🌍 Real-life Examples

  • Greeting: def greet(name): print("Hello, " + name)
  • Math: def add(a, b): return a + b
  • Average: def average(numbers): return sum(numbers) / len(numbers)
  • Tax: def calculate_tax(amount): return amount * 0.1
  • Conversion: def celsius_to_fahrenheit(c): return c * 9/5 + 32

🇳🇬 Nigerian Examples

  • Greeting Yoruba: def greet_yoruba(name): print("Ẹ káàbọ̀, " + name)
  • Naira to Dollar: def naira_to_dollar(naira): return naira / 1600
  • State Check: def region(state): if state == "Lagos": return "South-West" else: return "Other"
  • Food: def make_jollof(rice, chicken): print("Making Jollof rice with " + chicken)
  • City: def is_lagos(city): return city == "Lagos"

🎈 Fun Examples children can relate to

  • def say_hello(): print("Hello, world!")
  • def square(number): return number * number
  • def favourite_food(food): print("I love " + food)
  • def is_even(number): return number % 2 == 0
  • def birthday(name): print("Happy Birthday, " + name)

🏠 Everyday Examples

  • Cleaning: def clean_room(room): print("Cleaning " + room)
  • Cooking: def make_tea(type="green"): print("Making " + type + " tea")
  • Homework: def check_homework(done): if done: print("Great job") else: print("Do it now")
  • Chores: def do_chore(chore): print("Doing " + chore)
  • Reminder: def remind(task): print("Reminder: " + task)

👩‍🏫 Teacher Notes

  • Encourage students to write functions for repetitive tasks.
  • Use local examples to make it relatable.
  • Have students create functions that calculate averages, greet people, etc.
  • Emphasise the power of reusing code.
  • Celebrate every function they write.

👪 Parent Tips

  • Help your child write functions for everyday tasks.
  • Write programs together that use functions.
  • Encourage them to think of tasks that can be automated.
  • Make learning Python a fun activity.
  • Celebrate their progress.

🧐 Interesting Facts

  • Functions are used in every programming language.
  • Python has many built-in functions like print() and len().
  • Functions make code easier to test.
  • Functions help you organise large programs.
  • Good programmers write functions for every task.

💡 Did You Know?

  • Did you know that you can call a function inside another function?
  • Did you know that functions can have default parameters?
  • Did you know that functions can return multiple values?
  • Did you know that you can pass any data type to a function?
  • Did you know that functions are the building blocks of automation?

🧷 Remember This

  • Functions are reusable blocks of code.
  • Use def to define a function.
  • Call a function by writing its name with ().
  • Parameters pass values to functions.
  • Return values send results back.

⚠️ Common Mistakes

  • Forgetting colons: def greet() needs a colon: def greet():
  • Forgetting indentation: The code inside the function must be indented.
  • Not returning a value: Forgetting to use return when needed.
  • Using a variable that doesn't exist: The parameter name must match.
  • Calling a function with the wrong number of arguments.

✅ Best Practices

  • Use descriptive function names.
  • Add docstrings to explain the function.
  • Keep functions short and focused.
  • Use parameters to make functions flexible.
  • Test functions with different inputs.

🎨 Illustrations, Diagrams & Tables

Function Structure

    +----------------------+
    | def function_name(parameters): |
    |    # code block      |
    |    return result     |
    +----------------------+
            

Function Example

FunctionInputOutput
add(a, b)5, 38
greet(name)"Aisha""Hello, Aisha"
square(n)416

Comparison: With and Without Functions

Without FunctionsWith Functions
Repeated codeOne function used many times
Hard to readEasy to read
Hard to changeEasy to change
Long programsShort programs

📝 End-of-Module Summary

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!

❓ Frequently Asked Questions (10)

  1. What is a function? A reusable block of code.
  2. How do you define a function? def function_name():
  3. How do you call a function? function_name()
  4. What are parameters? Variables passed to a function.
  5. What does return do? Sends a value back.
  6. What is a default parameter? A parameter with a default value.
  7. What is scope? Where a variable exists.
  8. What is a docstring? A description of a function.
  9. Why are functions useful? They make code reusable and organised.
  10. Can functions be used in automation? Yes, they are essential.

📋 Review Questions (15)

  1. What is a function?
  2. How do you define a function?
  3. How do you call a function?
  4. What are parameters?
  5. What does return do?
  6. What is a default parameter?
  7. What is scope?
  8. What is a docstring?
  9. Why are functions useful?
  10. How do you pass multiple parameters?
  11. How do you return a value?
  12. What is the difference between a parameter and an argument?
  13. Can you use conditions inside functions?
  14. Can you use loops inside functions?
  15. What is the keyword to define a function?

✏️ Fill-in-the-Blank Exercises

  1. A ______________ is a reusable block of code. (function)
  2. Use the ________ keyword to define a function. (def)
  3. Call a function by writing its name with ______________. (parentheses)
  4. _____________ pass values to a function. (Parameters)
  5. Use ________ to send a value back. (return)

✅ True or False Exercises

  1. Functions are reusable blocks of code. (True)
  2. You define a function with func. (False)
  3. Parameters pass values to functions. (True)
  4. return sends a value back. (True)
  5. Functions cannot be used in automation. (False)

🔘 Multiple Choice Questions (15)

  1. What is a function?
    a) A reusable block of code ✅
    b) A variable
    c) A loop
  2. How do you define a function?
    a) def function_name(): ✅
    b) function function_name():
    c) func function_name():
  3. How do you call a function?
    a) function_name() ✅
    b) call function_name()
    c) run function_name()
  4. What are parameters?
    a) Variables passed to a function ✅
    b) Variables inside a function
    c) Variables outside a function
  5. What does return do?
    a) Sends a value back ✅
    b) Prints a value
    c) Stops the program
  6. What is a default parameter?
    a) A parameter with a default value ✅
    b) A parameter without a value
    c) A parameter that is required
  7. What is scope?
    a) Where a variable exists ✅
    b) A type of function
    c) A type of loop
  8. What is a docstring?
    a) A description of a function ✅
    b) A type of variable
    c) A type of loop
  9. Why are functions useful?
    a) They make code reusable ✅
    b) They make code longer
    c) They make code harder
  10. How do you pass multiple parameters?
    a) Separate with commas ✅
    b) Separate with spaces
    c) Separate with dots
  11. What is the keyword to define a function?
    a) def ✅
    b) func
    c) function
  12. Can you use conditions inside functions?
    a) Yes ✅
    b) No
  13. Can you use loops inside functions?
    a) Yes ✅
    b) No
  14. What is the output of def add(a, b): return a + b with add(5, 3)?
    a) 8 ✅
    b) 5
    c) 3
  15. Can functions have no parameters?
    a) Yes ✅
    b) No

🔗 Matching Exercises

Match the word with its meaning:

WordMeaning
1. FunctionA) Sends a value back
2. ParameterB) A reusable block of code
3. ReturnC) A variable passed to a function
4. DefineD) A description of a function
5. DocstringE) To create a function

(Answers: 1-B, 2-C, 3-A, 4-E, 5-D)

📝 Short Answer Questions

  1. What is a function and why is it useful?
  2. Write a function that takes a name and prints "Hello, [name]!".
  3. Write a function that takes two numbers and returns their sum.

🎭 Scenario-based Exercises

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.

👥 Group Activity

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.

🧑‍🎓 Individual Activity

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.

🗣️ Classroom Discussion Questions

  • How can functions help you automate tasks?
  • What are some tasks you do repeatedly that could be turned into a function?
  • Why is code organisation important?

🛠️ Mini Project

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.

📁 Practical Assignment

Write a function that calculates the tax on an amount. Tax is 10% of the amount. Test it with different amounts.

🏆 Challenge Exercise

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.

🔑 Quiz Answers

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

🎁 Key Takeaways

  • Functions are reusable blocks of code.
  • Use def to define a function.
  • Use parameters to pass values.
  • Use return to send a value back.
  • Functions make code organised and reusable.

🚀 Preparation for the next module

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

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