Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
โ† PYTHON FUNDAMENTALS LEVEL 1 PROFESSIONAL ยท Lesson 9 of 9

Module Eight

๐Ÿ“– 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.
9
Module 8: Python Loops and Functions Module 8: Python Loops and Functions

MODULE 8: PYTHON LOOPS AND FUNCTIONS

Course: Python Fundamentals Level 1 Professional
Module: 8 of 8
Level: Beginner

1. Introduction to Python Loops and Functions

Imagine your teacher asks you to write the sentence "I will practise Python every day" 20 times.

Writing the same sentence repeatedly can become boring and time-consuming. What if you could tell a computer to repeat the instruction 20 times automatically?

Python allows you to do this using something called a loop.

Now imagine you have written a program that calculates the total price of items. You want to use the same calculation in different parts of your program. Instead of writing the same code repeatedly, you can create a reusable block of code called a function.

Loops and functions help programmers write shorter, cleaner and more organised programs.

2. Learning Objectives

By the end of this module, you should be able to:

  • Explain what loops are in Python.
  • Understand how the for loop works.
  • Use the while loop to repeat instructions.
  • Understand the purpose of the range() function.
  • Use break and continue statements.
  • Explain what Python functions are.
  • Create functions using the def keyword.
  • Pass information into functions using parameters and arguments.
  • Return values from functions.
  • Build a simple program using loops and functions.

3. What Are Loops in Python?

A loop is a programming structure that allows a computer to repeat a set of instructions multiple times.

Instead of writing the same instruction many times, you can use a loop to repeat it automatically.

Example Without a Loop

print("Welcome to Python")
print("Welcome to Python")
print("Welcome to Python")
print("Welcome to Python")
print("Welcome to Python")

Output:

Welcome to Python
Welcome to Python
Welcome to Python
Welcome to Python
Welcome to Python

Writing the same instruction five times is unnecessary.

Example Using a Loop

for number in range(5):
    print("Welcome to Python")

Output:

Welcome to Python
Welcome to Python
Welcome to Python
Welcome to Python
Welcome to Python

The loop repeats the print instruction five times using fewer lines of code.

4. Types of Loops in Python

Python provides two main types of loops:

  1. for loop: Used to repeat instructions over a sequence or a specified range of values.
  2. while loop: Used to repeat instructions as long as a condition remains True.

5. Understanding the for Loop

A for loop allows you to repeat an instruction for each item in a sequence or for each value in a range.

Basic structure:

for variable in sequence:
    statement

For example:

for number in range(5):
    print(number)

Output:

0
1
2
3
4

Python starts counting from 0 and stops before reaching 5.

Understanding the Example

  • for tells Python to start a loop.
  • number is the variable that receives each value.
  • range(5) generates the numbers 0, 1, 2, 3 and 4.
  • print(number) displays each number.

6. Understanding the range() Function

The range() function generates a sequence of numbers that can be used in a loop.

It is commonly used when you want a loop to repeat a specific number of times.

6.1 range(stop)

This creates numbers starting from 0 and ending before the specified stop value.

for number in range(5):
    print(number)

Output:

0
1
2
3
4

6.2 range(start, stop)

You can specify where the counting should begin and where it should stop.

for number in range(1, 6):
    print(number)

Output:

1
2
3
4
5

6.3 range(start, stop, step)

The third value determines how much the number should increase or decrease during each repetition.

for number in range(2, 11, 2):
    print(number)

Output:

2
4
6
8
10

In this example, Python starts at 2 and increases the number by 2 each time.

Counting Backwards

You can also use a negative step value to count backwards.

for number in range(5, 0, -1):
    print(number)

Output:

5
4
3
2
1

7. Using for Loops with Lists

A list is a collection of items stored in one variable. You can use a for loop to display each item in a list.

Example:

subjects = ["Mathematics", "English", "Science", "Computer Studies"]

for subject in subjects:
    print(subject)

Output:

Mathematics
English
Science
Computer Studies

Python goes through the list one item at a time and displays each subject.

Another Example: Displaying Student Names

students = ["Amina", "Tunde", "Ada", "David"]

for student in students:
    print("Welcome,", student)

Output:

Welcome, Amina
Welcome, Tunde
Welcome, Ada
Welcome, David

8. Understanding the while Loop

A while loop repeats instructions as long as a condition is True.

Basic structure:

while condition:
    statement

Example:

number = 1

while number <= 5:
    print(number)
    number += 1

Output:

1
2
3
4
5

How the Program Works

  1. Python creates a variable called number and gives it the value 1.
  2. Python checks whether the number is less than or equal to 5.
  3. If the condition is True, Python displays the number.
  4. The statement number += 1 increases the number by 1.
  5. Python repeats the process until the condition becomes False.

When the number becomes 6, the condition is False and the loop stops.

Important: Make sure a while loop has a way to reach its stopping condition. Otherwise, it may run forever. This is called an infinite loop.

9. Difference Between for and while Loops

for Loop while Loop
Used to go through items in a sequence or a range. Repeats while a condition remains True.
Often used when the number of repetitions is known. Often used when repetition depends on a condition.
Example: Display numbers from 1 to 10. Example: Keep asking for a password until it is correct.

10. The break Statement

The break statement is used to stop a loop immediately, even when the loop condition is still True or there are more items to process.

Example:

for number in range(1, 10):
    if number == 5:
        break

    print(number)

Output:

1
2
3
4

When the number reaches 5, the break statement stops the loop.

11. The continue Statement

The continue statement skips the current repetition and moves to the next one.

Example:

for number in range(1, 6):
    if number == 3:
        continue

    print(number)

Output:

1
2
4
5

When Python reaches 3, it skips the print statement for that repetition and continues with the next number.

12. What Are Functions in Python?

A function is a reusable block of code designed to perform a particular task.

For example, imagine you regularly calculate the total price of products. Instead of writing the same calculation repeatedly, you can create a function that performs the calculation whenever you need it.

Functions help programmers:

  • Avoid repeating the same code.
  • Organise programs into smaller sections.
  • Make programs easier to read.
  • Reuse code in different parts of a program.
  • Maintain and update programs more easily.

13. Creating Your First Python Function

Python uses the def keyword to create a function.

Basic structure:

def function_name():
    statement

Example:

def greet():
    print("Hello! Welcome to Python.")

greet()

Output:

Hello! Welcome to Python.

Understanding the Example

  • def tells Python that you are creating a function.
  • greet is the name of the function.
  • The parentheses () hold information that can be passed into the function.
  • The indented print statement is the task the function performs.
  • greet() calls the function and tells Python to execute it.
Remember: Creating a function does not automatically run it. You must call the function by using its name followed by parentheses.

14. Calling a Function Multiple Times

You can call the same function as many times as you need.

def welcome():
    print("Welcome to CRMNuggets!")

welcome()
welcome()
welcome()

Output:

Welcome to CRMNuggets!
Welcome to CRMNuggets!
Welcome to CRMNuggets!

Instead of writing the message three times inside the function, you simply call the function three times.

15. Functions with Parameters

A parameter is a variable listed inside a function's parentheses. It allows a function to receive information when it is called.

Example:

def greet(name):
    print("Hello,", name)

greet("Amina")
greet("Tunde")
greet("David")

Output:

Hello, Amina
Hello, Tunde
Hello, David

The parameter name receives a different value each time the function is called.

Understanding Parameters and Arguments

  • Parameter: The variable written inside the function definition.
  • Argument: The actual value supplied when calling the function.

In this example:

def greet(name):
    print("Hello,", name)

greet("Amina")

name is the parameter, while "Amina" is the argument.

16. Functions with Multiple Parameters

A function can accept more than one parameter.

Example:

def student_info(name, age, school):
    print("Student Name:", name)
    print("Age:", age)
    print("School:", school)

student_info("Amina", 13, "Bright Future School")

Output:

Student Name: Amina
Age: 13
School: Bright Future School

The function receives three pieces of information and displays them.

17. Functions with Return Values

Sometimes, you want a function to calculate something and send the result back to the part of the program that called it.

Python uses the return statement to send a value back from a function.

Example: Adding Two Numbers

def add_numbers(a, b):
    result = a + b
    return result

answer = add_numbers(10, 20)

print(answer)

Output:

30

The function adds the two numbers and returns the result. The result is then stored in the answer variable.

Another Example: Calculating Shopping Costs

def calculate_total(price, quantity):
    total = price * quantity
    return total

bill = calculate_total(1000, 4)

print("Total cost: โ‚ฆ", bill)

Output:

Total cost: โ‚ฆ 4000

18. Functions with Default Parameters

A default parameter is a parameter that already has a value when the function is created.

If the user does not provide another value, Python uses the default value.

Example:

def greet(name="Student"):
    print("Welcome,", name)

greet()
greet("Amina")

Output:

Welcome, Student
Welcome, Amina

When the function is called without an argument, Python uses the default name "Student". When "Amina" is supplied, it uses that name instead.

19. Combining Loops and Functions

You can use loops and functions together to create more useful programs.

For example, you can create a function that displays a welcome message and then use a loop to call it for several students.

def welcome_student(name):
    print("Welcome to Python,", name)

students = ["Amina", "Tunde", "Ada", "David"]

for student in students:
    welcome_student(student)

Output:

Welcome to Python, Amina
Welcome to Python, Tunde
Welcome to Python, Ada
Welcome to Python, David

The function displays a welcome message, while the loop repeats the function call for every student in the list.

20. Practical Project: Simple Student Score Calculator

Project Description

You are creating a simple program that calculates the average score of students in three subjects.

Project Requirements:

  • Create a function called calculate_average().
  • Allow the function to receive three subject scores.
  • Add the three scores together.
  • Divide the total by three.
  • Return the average score.
  • Use a loop to process multiple students.
  • Display each student's name and average score.

Sample Solution

def calculate_average(math, english, science):
    total = math + english + science
    average = total / 3
    return average

students = [
    ["Amina", 80, 70, 90],
    ["Tunde", 65, 75, 85],
    ["Ada", 90, 85, 95]
]

for student in students:
    name = student[0]
    math = student[1]
    english = student[2]
    science = student[3]

    average = calculate_average(math, english, science)

    print("Student:", name)
    print("Average Score:", average)
    print("--------------------")

Output:

Student: Amina
Average Score: 80.0
--------------------
Student: Tunde
Average Score: 75.0
--------------------
Student: Ada
Average Score: 90.0
--------------------

This project demonstrates how loops and functions can work together to process information for multiple students.

21. Practical Activities

Activity 1: Counting Numbers

Write a for loop that displays numbers from 1 to 20.

Activity 2: Multiplication Table

Ask a user to enter a number. Use a for loop to display its multiplication table from 1 to 12.

Activity 3: Password Attempts

Create a program that allows a user to enter a password. Use a while loop to keep asking until the correct sample password is entered.

Activity 4: Greeting Function

Create a function called greet_user() that accepts a name and displays a personalised welcome message.

Activity 5: Calculator Function

Create a function called multiply_numbers() that accepts two numbers, multiplies them and returns the answer.

Activity 6: Even Number Display

Use a loop to display all even numbers between 1 and 30.

22. Common Mistakes to Avoid

  • Forgetting to update a while loop: If the condition never becomes False, the loop may run forever.
  • Incorrect indentation: Statements inside loops and functions must be indented.
  • Using the wrong range: Remember that range() stops before its stop value.
  • Forgetting to call a function: Defining a function does not automatically execute it.
  • Using return incorrectly: Use return when you want a function to send a result back.
  • Confusing parameters and arguments: Parameters are defined in the function, while arguments are supplied when calling it.
  • Using break and continue incorrectly: Remember that break stops the loop, while continue skips the current repetition.

23. Key Terms to Remember

Term Meaning
Loop A programming structure that repeats instructions.
for Loop A loop used to process items in a sequence or range.
while Loop A loop that repeats while a condition is True.
range() A function that generates a sequence of numbers.
break A statement that stops a loop immediately.
continue A statement that skips the current repetition.
Function A reusable block of code designed to perform a task.
def A Python keyword used to define a function.
Parameter A variable listed in a function definition.
Argument A value supplied when calling a function.
return A statement used to send a result back from a function.
Infinite Loop A loop that continues without reaching a stopping condition.

24. Module Summary

In this module, you learned how to repeat instructions using loops and organise reusable code using functions.

You explored for loops, while loops, the range() function, and the break and continue statements.

You also learned how to create functions using def, pass information through parameters and arguments, and return results using the return statement.

Loops and functions are important programming skills because they help you build applications that can perform repeated tasks efficiently.

25. Knowledge Check

Test your understanding of Module 8 by answering the following questions.

1. What is a loop in Python?

  1. A structure used to repeat instructions
  2. A type of computer
  3. A Python error
  4. A data type

2. Which loop is commonly used to go through items in a list?

  1. if loop
  2. for loop
  3. def loop
  4. print loop

3. Which loop repeats while a condition is True?

  1. for
  2. if
  3. while
  4. return

4. What is the output of range(5) when used in a loop?

  1. 1, 2, 3, 4, 5
  2. 0, 1, 2, 3, 4
  3. 0, 1, 2, 3, 4, 5
  4. 5, 4, 3, 2, 1

5. Which statement immediately stops a loop?

  1. continue
  2. return
  3. break
  4. print

6. What does the continue statement do?

  1. Deletes a loop
  2. Skips the current repetition and moves to the next one
  3. Stops the entire computer
  4. Creates a function

7. Which keyword is used to create a function in Python?

  1. function
  2. create
  3. def
  4. loop

8. What is a parameter in Python?

  1. A variable listed in a function definition
  2. A computer screen
  3. A type of loop
  4. A Python installation file

9. Which statement sends a value back from a function?

  1. print
  2. input
  3. break
  4. return

10. What is an infinite loop?

  1. A loop that runs only once
  2. A loop that repeats without reaching its stopping condition
  3. A loop that cannot display output
  4. A function that returns a number
Click here to reveal the answers
  1. A - A loop repeats instructions.
  2. B - A for loop can process items in a list.
  3. C - A while loop repeats while its condition is True.
  4. B - range(5) generates 0, 1, 2, 3 and 4.
  5. C - break stops a loop immediately.
  6. B - continue skips the current repetition.
  7. C - def is used to define a function.
  8. A - A parameter is a variable listed in a function definition.
  9. D - return sends a value back from a function.
  10. B - An infinite loop continues without reaching its stopping condition.

26. Course Completion

Congratulations! You have completed all eight modules of Python Fundamentals Level 1 Professional.

Throughout this course, you have learned the basic concepts required to start writing Python programs.

What You Have Learned

  1. Module 1: Introduction to Python Programming.
  2. Module 2: Installing Python and Writing Your First Program.
  3. Module 3: Python Syntax, Comments and Indentation.
  4. Module 4: Python Variables and Data Types.
  5. Module 5: Python Operators and Expressions.
  6. Module 6: Python Input and Output.
  7. Module 7: Python Conditional Statements.
  8. Module 8: Python Loops and Functions.

Final Practical Challenge

Build a simple Python student management program that combines the concepts covered in this course.

Your program should:

  • Ask the user to enter a student's name.
  • Collect scores in three subjects.
  • Calculate the total and average scores.
  • Use conditional statements to determine the student's grade.
  • Use a function to calculate the average.
  • Use a loop to process more than one student.
  • Display the student's name, scores, average and grade.

Recommended Next Step

Continue practising Python and explore more advanced topics such as:

  • Python Lists and Tuples
  • Python Dictionaries and Sets
  • Python File Handling
  • Python Object-Oriented Programming
  • Python Libraries and Modules
  • Python for Data Analysis
Well done! You have completed Python Fundamentals Level 1 Professional. Keep practising, build small projects and continue developing your programming skills.

CRMNuggets โ€“ Learn. Practice. Get Certified.

๐Ÿ† 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.
โ†’