Python For Loops
For Loop Basics
A `for` loop in Python iterates over items of any sequence (such as a list, tuple, string, or range) in the order they appear. It is the most common way to repeat actions in Python.
Example
# Basic for loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Iterating over a string
word = "Python"
for letter in word:
print(letter)
Output
apple banana cherry P y t h o n
Range() Function
The `range()` function generates a sequence of numbers, often used in `for` loops:
Example
# range(stop)
for i in range(5):
print(i)
print("---")
# range(start, stop)
for i in range(2, 6):
print(i)
print("---")
# range(start, stop, step)
for i in range(0, 10, 2):
print(i)
Output
0 1 2 3 4 --- 2 3 4 5 --- 0 2 4 6 8
For Loop with Else
A `for` loop can include an `else` clause. The `else` block runs only if the loop completes without hitting a `break` statement.
Example
# For-else example
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
print("Found 3!")
print(num)
else:
print("Loop completed successfully")
print("---")
# With break
for num in numbers:
if num == 3:
print("Breaking at 3")
break
print(num)
else:
print("This won't execute due to break")
Output
1 2 Found 3! 3 4 5 Loop completed successfully --- 1 2 Breaking at 3
Nested For Loops
For loops can be nested to work with multi-dimensional data or generate combinations.
Example
# Multiplication table using nested loops
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i * j}")
print("---")
# Iterating over a 2D list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for element in row:
print(element, end=" ")
print()
Output
1 x 1 = 1 1 x 2 = 2 1 x 3 = 3 --- 2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 --- 3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 --- 1 2 3 4 5 6 7 8 9