A for
loop in Python iterates over a sequence (such as a list, tuple, string, or range) and executes a block of code for each item.
for variable in sequence:
# code block to execute
for i in range(5):
print(i)
The for
loop assigns each item from the sequence to the loop variable one by one and runs the loop body. It stops when all items are processed.
# Example 1: Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Example 2: Loop through a string
for char in "Python":
print(char)
# Example 3: Using range() to print numbers 1 to 5
for num in range(1, 6):
print(num)
# Example 4: Sum of numbers in a list
numbers = [1, 2, 3, 4, 5]
total = 0
for n in numbers:
total += n
print("Sum:", total)
# Example 5: Nested for loop to print a pattern
for i in range(1, 4):
for j in range(i):
print("*", end="")
print()