A `for` loop in Python is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each element in the sequence. The syntax of a `for` loop in Python is straightforward:
“`python
for element in sequence:
# Execute this block of code for each element in the sequence
# Indentation is crucial in Python
# Code here
“`
Here’s a breakdown of the components:
– `element`: This is a variable that represents the current element in the sequence.
– `sequence`: This is the sequence over which the loop iterates.
Here are a few examples illustrating the use of `for` loops in Python:
### Example 1: Iterating Over a List
“`python
fruits = [“apple”, “banana”, “cherry”]
for fruit in fruits:
print(fruit)
“`
Output:
“`
apple
banana
cherry
“`
### Example 2: Iterating Over a String
“`python
word = “Python”
for char in word:
print(char)
“`
Output:
“`
P
y
t
h
o
n
“`
### Example 3: Iterating Over a Range
“`python
for num in range(1, 6):
print(num)
“`
Output:
“`
1
2
3
4
5
“`
### Example 4: Using `enumerate()` to Access Index and Value
“`python
fruits = [“apple”, “banana”, “cherry”]
for index, fruit in enumerate(fruits):
print(f”Index {index}: {fruit}”)
“`
Output:
“`
Index 0: apple
Index 1: banana
Index 2: cherry
“`
These examples demonstrate how `for` loops can be used to iterate over various types of sequences in Python. They provide a convenient way to perform repetitive tasks efficiently.