Python for Loops
Python for loops are used to iterate over a sequence (such as a list, tuple, string, or range) or any iterable object. They allow you to perform a set of instructions repeatedly for each item in the sequence. The basic syntax of a for loop in Python is as follows:
python
for item in sequence:
# Code block to be executed
Here, item
represents a variable that will take on the value of each item in the sequence, and sequence
is the iterable object you want to iterate over. The code block following the colon is indented and contains the instructions that will be executed for each item.
Let’s look at a few examples to illustrate the usage of for loops:
Example 1: Iterating over a list
python
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
orange
Example 2: Iterating over a string
python
message = "Hello, world!"
for char in message:
print(char)
Output:
diff
H
e
l
l
o
,
w
o
r
l
d
!
Example 3: Using the range function
python
for num in range(1, 5):
print(num)
Output:
1
2
3
4
In this last example, the range()
function generates a sequence of numbers from 1 to 4 (the second argument is exclusive), and the for loop iterates over each number in the sequence.
You can also combine for loops with conditional statements (if-else) and other control flow statements to create more complex logic within the loop.