Welcome back! In the previous tutorial, we learned about using the if
… else
… condition to control the flow of our programs. Now, let’s dive into another powerful control structure: the for
loop. Loops allow you to execute a block of code repeatedly, which is essential for tasks like iterating over a collection of items, processing data, and more. In this article, we’ll explore how to use the for
loop in Python effectively.
What is a For Loop?
A for
loop is used to iterate over a sequence (such as a list, tuple, dictionary, set, or string) and execute a block of code for each element in the sequence. The for
loop in Python is different from the traditional C-style for
loop; it is more readable and often used to iterate over iterable objects.
Syntax
The basic syntax of a for
loop in Python is:
for element in sequence:
# Code to execute for each element
Here, element
is a variable that takes on the value of each item in the sequence, one at a time, and the loop continues until all items in the sequence have been processed.
Example: Iterating Over a List
Let’s start with a simple example of iterating over a list of fruits.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
In this example, the for
loop iterates over each element in the fruits
list and prints each fruit.
Iterating Over a String
You can use a for
loop to iterate over the characters in a string.
message = "Hello"
for char in message:
print(char)
Output:
H
e
l
l
o
In this example, the for
loop iterates over each character in the message
string and prints each character.
Using the range()
Function
The range()
function generates a sequence of numbers, which is useful for creating loops that run a specific number of times. The basic syntax of range()
is range(start, stop, step)
, where start
is the starting number, stop
is the ending number (exclusive), and step
is the difference between each number in the sequence.
Example: Iterating Over a Range of Numbers
for i in range(5):
print(i)
Output:
0
1
2
3
4
In this example, the for
loop iterates over the range of numbers from 0 to 4.
Example: Specifying Start, Stop, and Step
for i in range(2, 10, 2):
print(i)
Output:
2
4
6
8
In this example, the for
loop iterates over the range of numbers from 2 to 8, with a step of 2.
Nested For Loops
You can use nested for
loops to iterate over multi-dimensional sequences, such as lists of lists.
Example: Iterating Over a Matrix
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for element in row:
print(element, end=" ")
print()
Output:
1 2 3
4 5 6
7 8 9
In this example, the outer for
loop iterates over each row in the matrix
, and the inner for
loop iterates over each element in the row, printing each element.
Using the enumerate()
Function
The enumerate()
function adds a counter to an iterable and returns it as an enumerate object, which you can convert to a list of tuples containing pairs of index and element.
Example: Using enumerate()
with a List
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)
Output:
0 apple
1 banana
2 cherry
In this example, the for
loop iterates over the fruits
list, and enumerate()
provides both the index and the element.
Using the zip()
Function
The zip()
function takes two or more sequences and returns an iterator of tuples, where each tuple contains the elements from the input sequences at the same position.
Example: Iterating Over Multiple Lists
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(name, age)
Output:
Alice 25
Bob 30
Charlie 35
In this example, the for
loop iterates over the names
and ages
lists simultaneously, printing each name and corresponding age.
Example: Using a For Loop in a Program
Let’s create a program that calculates the factorial of a number using a for
loop.
# Get user input
number = int(input("Enter a number: "))
# Initialize the factorial
factorial = 1
# Calculate the factorial using a for loop
for i in range(1, number + 1):
factorial *= i
# Print the result
print(f"The factorial of {number} is {factorial}")
In this program, we:
- Get a number from the user.
- Initialize the
factorial
variable to 1. - Use a
for
loop to iterate over the range of numbers from 1 to the user-provided number. - Multiply the
factorial
variable by each number in the range. - Print the result.
Conclusion
The for
loop is a powerful control structure in Python that allows you to iterate over sequences and perform repetitive tasks efficiently. Understanding how to use for
loops, along with functions like range()
, enumerate()
, and zip()
, will help you write more effective and concise code.
In our next tutorial, we’ll explore while loops in Python, which allow you to execute a block of code as long as a specific condition is true. Stay tuned, and happy coding!