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

Module Four

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

📦 Module 4: Functions, Modules & Clean Code

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!

🎯 Learning Objectives

After this module, you will be able to:

  • Explain what a function is and why we use it.
  • Define your own functions and call (use) them.
  • Understand parameters and return values.
  • Import and use modules in Python.
  • Write clean, readable code with comments.
  • Break a big program into smaller, manageable pieces.
  • Understand the concept of code reusability.

📖 Warm‑up Story: Aisha’s Smoothie Shop

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!

📘 Lesson 1: What is a Function?

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.

📘 Lesson 2: Defining a Function

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.

📘 Lesson 3: Calling a Function

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.

📘 Lesson 4: Parameters – Inputs for Functions

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.

📘 Lesson 5: Return Values – Getting Results

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.

📘 Lesson 6: Why Functions Are Useful

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.

📘 Lesson 7: Scope – Where Variables Live

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.

📘 Lesson 8: Modules – Ready‑Made Tools

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.

📘 Lesson 9: Importing Modules

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.

📘 Lesson 10: Creating Your Own Module

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.

📘 Lesson 11: Clean Code – Writing Neat Programs

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.

📘 Lesson 12: Comments – Explaining Your Code

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.

📘 Lesson 13: Naming Conventions – Good Names

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.

📘 Lesson 14: Refactoring – Improving Your Code

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.

📘 Lesson 15: The Power of Reusability

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.

📚 Key Vocabulary

WordSimple Definition
FunctionA reusable block of code that does a specific task.
ParameterAn input that you pass to a function.
Return ValueThe output that a function sends back.
ModuleA file containing Python code that you can import.
ImportTo bring a module into your program.
ScopeWhere a variable is accessible – local or global.
Clean CodeCode that is easy to read and understand.
CommentA note in the code that is ignored by the computer.
RefactoringImproving code without changing what it does.
ReusabilityUsing the same code in multiple places.

🧠 Important Concepts

  • Modularity: Breaking a program into independent modules or functions – each piece does one thing well.
  • Abstraction: Hiding complex details – a function lets you use it without knowing how it works inside.
  • DRY Principle: Don’t Repeat Yourself – if you find yourself copying code, use a function!
  • Separation of Concerns: Each function should focus on a single task.

👣 Step‑by‑Step Explanations

How to define and call a function in Python

  1. Use the def keyword, followed by the function name and parentheses.
  2. Add a colon : and indent the function body.
  3. Write the instructions inside the function body.
  4. To use the function, write its name with parentheses.

How to import and use a module

  1. Write import module_name at the top of your file.
  2. Use the module’s functions with module_name.function_name().
  3. Alternatively, use from module_name import function_name to import a specific function.

🌍 Real‑life Examples

  • Smartphone: The “send_message” function – you give it a contact and a message, and it sends it.
  • Calculator: The “square_root” function – you input a number, and it returns the square root.
  • Search Engine: The “search” function – you type a query, and it returns results.

🇳🇬 Nigerian Examples

  • e‑Naira: The “send_money” function – you input a recipient and amount, and it transfers the money.
  • Paystack: The “make_payment” function – you pass the transaction details, and it processes payment.
  • NIN verification: The “verify_id” function – you input a NIN, and it returns the citizen’s details.
  • Traffic management: The “change_light” function – you call it to switch traffic lights.

🎮 Fun Examples Children Can Relate To

  • Minecraft: A “build_house” function – you call it to build a house.
  • Roblox: A “jump” function – you call it to make your character jump.
  • Pokémon: An “attack” function – you call it to make your Pokémon attack.
  • FIFA: A “pass_ball” function – you call it to pass the ball.

🏠 Everyday Examples

  • Making tea: A “make_tea” function – you give it the type of tea, and it returns a cup.
  • Setting an alarm: A “set_alarm” function – you give it the time, and it sets the alarm.
  • Washing clothes: A “wash_clothes” function – you give it the type of fabric, and it washes.

🧑‍🏫 Teacher Notes

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.

👪 Parent Tips

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.

✨ Interesting Facts

  • Python has over 200 built‑in modules – you can use them right away!
  • The first programming language to use functions was FORTRAN in 1957.
  • Google uses functions extensively – they have millions of lines of code organised into functions.

💡 Did You Know?

  • Did you know that you can import a module and rename it with as? (e.g., import math as m)
  • Did you know that Python functions can have default parameters?
  • Did you know that the Nigerian tech ecosystem has many open‑source modules written by local developers?

🔔 Remember This

  • Functions are like recipes – they make your code reusable.
  • Always give your functions and variables clear, descriptive names.
  • Use comments to explain tricky parts of your code.
  • Modules are pre‑written code – use them to save time.
  • Clean code is important – it helps you and others understand your work.

⚠️ Common Mistakes

  • Forgetting to indent – Python requires indentation inside functions.
  • Using global variables when you should use parameters – it makes code harder to test.
  • Not using return – forgetting to return a value from a function.
  • Confusing function definition and calling – you define with def, you call by name.
  • Writing long, complicated functions – break them into smaller functions.

✅ Best Practices

  • Write small functions that do one thing well.
  • Use descriptive names – like calculate_average instead of ca.
  • Add a docstring (a comment) at the start of each function to explain what it does.
  • Keep your code DRY – Don’t Repeat Yourself.
  • Regularly refactor your code to keep it clean.

📊 Diagrams & Tables

Flowchart: Function Call

        +------------------+
        |   Start          |
        +--------+---------+
                 |
        +--------v---------+
        |   Call function  |
        +--------+---------+
                 |
        +--------v---------+
        |   Execute code   |
        +--------+---------+
                 |
        +--------v---------+
        |   Return result  |
        +--------+---------+
                 |
        +--------v---------+
        |   Continue       |
        +------------------+
    

Comparison Table: Functions vs Modules

FeatureFunctionModule
DefinitionA reusable block of codeA file containing code
ScopeInside a programCan be used across programs
Exampledef greet():import math
ReusabilityWithin one programAcross many programs

Docstring Example

        def add(a, b):
            """This function adds two numbers and returns the result."""
            return a + b
    

📝 End‑of‑Module Summary

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!

❓ Frequently Asked Questions

  1. What is a function in simple words? It’s a reusable piece of code that does a specific job.
  2. Why do we use functions? To avoid repeating code and to make programs easier to organise.
  3. What is a parameter? A value that you pass into a function to customise its behaviour.
  4. What is a return value? The result that a function sends back after it finishes.
  5. What is a module? A file containing Python code that you can import and use.
  6. How do I import a module? Use the import keyword – e.g., import math.
  7. What is clean code? Code that is easy to read and understand.
  8. What is a comment? A note in the code that is ignored by the computer.
  9. What is refactoring? Improving code without changing what it does.
  10. What is the DRY principle? Don’t Repeat Yourself – use functions to avoid repetition.

🤔 Review Questions

  1. What is a function?
  2. How do you define a function in Python?
  3. How do you call a function?
  4. What is a parameter?
  5. What is a return value?
  6. Why are functions useful?
  7. What is a module?
  8. How do you import a module?
  9. What is scope?
  10. What is the difference between a local and a global variable?
  11. What is clean code?
  12. What are comments used for?
  13. What is refactoring?
  14. What is the DRY principle?
  15. Why is reusability important?

📝 Fill‑in‑the‑Blank

  1. A ______ is a reusable block of code.
  2. You define a function using the ______ keyword.
  3. ______ are inputs that you pass to a function.
  4. A function sends back a result using the ______ statement.
  5. A ______ is a file containing Python code.
  6. You import a module using the ______ keyword.
  7. ______ code is easy to read and understand.
  8. ______ are notes in the code that are ignored by the computer.
  9. ______ is the process of improving code without changing its behaviour.
  10. The DRY principle stands for ______.

✅ True or False

  1. A function can only be called once. (False)
  2. Functions help you avoid repeating code. (True)
  3. Parameters are optional for all functions. (True – they can be optional)
  4. A function must always have a return value. (False – it can just do something)
  5. You can import a module to use its code. (True)
  6. Global variables are only accessible inside functions. (False)
  7. Comments are executed by the computer. (False)
  8. Refactoring changes what the code does. (False)
  9. Clean code has descriptive names. (True)
  10. Reusability is a key principle of software engineering. (True)

🔘 Multiple Choice

  1. What is a function?
    A) A variable
    B) A reusable block of code
    C) A data type
    D) A loop
    Answer: B
  2. How do you define a function in Python?
    A) function name():
    B) def name():
    C) define name():
    D) func name():
    Answer: B
  3. What is a parameter?
    A) A result from a function
    B) An input to a function
    C) A comment
    D) A module
    Answer: B
  4. What does a return statement do?
    A) Prints a value
    B) Sends a value back from the function
    C) Defines a function
    D) Imports a module
    Answer: B
  5. What is a module?
    A) A type of loop
    B) A file containing Python code
    C) A variable
    D) A function
    Answer: B
  6. How do you import a module?
    A) include math
    B) import math
    C) use math
    D) require math
    Answer: B
  7. What is a local variable?
    A) A variable that is global
    B) A variable defined inside a function
    C) A variable defined outside all functions
    D) A variable that is a list
    Answer: B
  8. What is clean code?
    A) Code that is short
    B) Code that is easy to read
    C) Code that is fast
    D) Code that has no comments
    Answer: B
  9. What are comments used for?
    A) To make the code run faster
    B) To explain the code to humans
    C) To define variables
    D) To import modules
    Answer: B
  10. What is refactoring?
    A) Adding new features
    B) Improving code structure
    C) Deleting code
    D) Changing the output
    Answer: B
  11. What does DRY stand for?
    A) Do Repeat Yourself
    B) Don’t Repeat Yourself
    C) Do Run Yourself
    D) Don’t Run Yourself
    Answer: B
  12. Which of these is a benefit of functions?
    A) Code is longer
    B) Code is reusable
    C) Code is harder to read
    D) Code is slower
    Answer: B
  13. What is the keyword to define a function?
    A) function
    B) def
    C) define
    D) func
    Answer: B
  14. What is a docstring?
    A) A comment that explains a module
    B) A comment that explains a function
    C) A type of variable
    D) A loop
    Answer: B
  15. Which of these is a good practice?
    A) Using unclear variable names
    B) Writing long functions
    C) Using descriptive names
    D) Avoiding comments
    Answer: C

🔗 Matching Exercises

TermDefinition
1. FunctionA. A reusable block of code
2. ParameterB. An input to a function
3. ReturnC. The output from a function
4. ModuleD. A file containing Python code
5. CommentE. A note in the code

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

✏️ Short Answer Questions

  1. What is a function and why is it useful?
  2. How do you define a function in Python? Give an example.
  3. What is the difference between a parameter and a return value?
  4. What is a module? Give an example of a built‑in Python module.
  5. Why is writing clean code important?

🎭 Scenario‑based Exercises

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.

👥 Group Activity

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.

🧑 Individual Activity

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.

💬 Classroom Discussion Questions

  1. Why is it better to use functions than to write the same code multiple times?
  2. How do modules help software engineers work faster?
  3. What would happen if we never wrote clean code?
  4. Can you think of a real‑world situation where you would use a function?

🛠️ Mini Project

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.

📋 Practical Assignment

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.

🏆 Challenge Exercise

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.

📌 Quiz Answers

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.

🎁 Key Takeaways

  • Functions are reusable blocks of code – they are the building blocks of programs.
  • Parameters and return values make functions flexible and powerful.
  • Modules provide ready‑made tools – use them to save time.
  • Clean code is easy to read and understand – it uses good names and comments.
  • Refactoring is important – always look for ways to improve your code.

🔜 Preparation for Module 5

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!

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