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.
By the end of this module, you should be able to:
for loop works.while loop to repeat instructions.range() function.break and continue statements.def keyword.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.
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.
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.
Python provides two main types of loops:
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.
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.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.
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
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
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.
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
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.
students = ["Amina", "Tunde", "Ada", "David"]
for student in students:
print("Welcome,", student)
Output:
Welcome, Amina
Welcome, Tunde
Welcome, Ada
Welcome, David
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
number and gives it the value 1.number += 1 increases the number by 1.When the number becomes 6, the condition is False and the loop stops.
| 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. |
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.
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.
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:
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.
def tells Python that you are creating a function.greet is the name of the function.() hold information that can be passed into the function.greet() calls the function and tells Python to execute it.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.
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.
In this example:
def greet(name):
print("Hello,", name)
greet("Amina")
name is the parameter, while "Amina" is the argument.
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.
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.
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.
def calculate_total(price, quantity):
total = price * quantity
return total
bill = calculate_total(1000, 4)
print("Total cost: โฆ", bill)
Output:
Total cost: โฆ 4000
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.
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.
You are creating a simple program that calculates the average score of students in three subjects.
Project Requirements:
calculate_average().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.
Write a for loop that displays numbers from 1 to 20.
Ask a user to enter a number. Use a for loop to display its multiplication table from 1 to 12.
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.
Create a function called greet_user() that accepts a name and displays a personalised welcome message.
Create a function called multiply_numbers() that accepts two numbers, multiplies them and returns the answer.
Use a loop to display all even numbers between 1 and 30.
range() stops before its stop value.return when you want a function to send a result back.| 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. |
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.
Test your understanding of Module 8 by answering the following questions.
1. What is a loop in Python?
2. Which loop is commonly used to go through items in a list?
3. Which loop repeats while a condition is True?
4. What is the output of range(5) when used in a loop?
5. Which statement immediately stops a loop?
6. What does the continue statement do?
7. Which keyword is used to create a function in Python?
8. What is a parameter in Python?
9. Which statement sends a value back from a function?
10. What is an infinite loop?
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.
Build a simple Python student management program that combines the concepts covered in this course.
Your program should:
Continue practising Python and explore more advanced topics such as:
CRMNuggets โ Learn. Practice. Get Certified.