Introduction to Python For Loop
In Python, a for loop is a control flow statement that allows you to iterate over a sequence of elements, such as a list, tuple, string, or range. It is a powerful tool for automating repetitive tasks and processing collections of data.
Syntax of a For Loop
The syntax of a for loop in Python is as follows:
for variable in sequence:
# Code block to be executed
The variable
represents the current element being processed in each iteration of the loop, while the sequence
is the collection of elements to iterate over. The code block is indented and executed for each element in the sequence.
Example: Iterating over a List
Let’s start with a simple example of iterating over a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
This code will output:
apple
banana
cherry
In each iteration of the loop, the fruit
variable takes on the value of the current element in the fruits
list, and then it is printed to the console.
Example: Iterating over a String
For loops are not limited to iterating over lists. They can also be used to iterate over strings:
message = "Hello, World!"
for char in message:
print(char)
This code will output:
H
e
l
l
o
,
W
o
r
l
d
!
Similar to the previous example, the char
variable takes on the value of each character in the message
string, and it is printed to the console.
Example: Iterating over a Range
In addition to iterating over sequences like lists and strings, for loops can also iterate over a range of numbers:
for number in range(1, 5):
print(number)
This code will output:
1
2
3
4
In this example, the number
variable takes on the value of each number in the range from 1 to 5 (excluding 5), and it is printed to the console.
Example: Using the Enumerate Function
The enumerate()
function is a handy tool when you need to iterate over a sequence and also keep track of the index of each element:
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)
This code will output:
0 apple
1 banana
2 cherry
In this example, the index
variable represents the index of each element in the fruits
list, and the fruit
variable represents the corresponding element itself.
Conclusion
For loops are a fundamental concept in Python programming. They allow you to iterate over sequences and perform operations on each element. Whether you are working with lists, strings, or ranges, for loops provide a concise and efficient way to automate repetitive tasks and process collections of data.
By understanding the syntax and examples provided in this article, you should now have a solid understanding of how to use for loops in Python.