Python Control Statements
Python For Loop
Learn Python For Loop with clear explanations, Python examples, and practical programming guidance.
What is a Python for loop?
A for loop processes items from an iterable one at a time. It runs the indented block once for each item and stops automatically when there are no more items.
Syntax of a for loop
for item in iterable:
# code runs once for each item
print(item)| Part | Meaning |
|---|---|
for | Starts the loop. |
item | Name that receives the current value. |
in | Connects the loop variable to the iterable. |
iterable | Object that can be visited, such as a list, string, tuple, set, dictionary, or range. |
: and indentation | Define the block executed for each item. |
How the loop works
- Python obtains the next item from the iterable.
- It assigns that item to the loop variable.
- It runs the indented loop body.
- It repeats until the iterable is exhausted.
for number in range(1, 6):
print(number)2
3
4
5
Iterating over common data types
A for loop can visit characters in a string, items in a list or tuple, and keys or key-value pairs in a dictionary:
for character in "Python":
print(character)
cars = ["Tata", "Honda", "BMW"]
for car in cars:
print(car)
student = {"name": "Asha", "experience": 8}
for key, value in student.items():
print(key, value)Use .items() when a dictionary loop needs both the key and its value. A dictionary loop without .items() visits keys only.
Using range()
range() is useful when a loop needs a sequence of numbers. The stop value is exclusive:
for number in range(3):
print(number)
for number in range(2, 6):
print(number)
for number in range(10, 4, -2):
print(number)The three forms are range(stop), range(start, stop), and range(start, stop, step).
Using enumerate() for indexes
Use enumerate() when you need both an item and its position. It is clearer than manually indexing a list:
fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits, start=1):
print(index, fruit)2 banana
3 orange
Example: calculate a factorial
A factorial multiplies every positive integer up to a number. The factorial of 0 is also 1; negative numbers do not have a factorial in this example:
number = 5
factorial = 1
if number < 0:
print("Factorial is not defined for negative numbers")
else:
for value in range(2, number + 1):
factorial *= value
print(factorial)Nested for loops
A nested for loop places one loop inside another. The inner loop completes for every item processed by the outer loop:
matrix = [
[13, 4, 27],
[22, 16, 8],
[5, 11, 19]
]
for row in matrix:
for value in row:
print(value, end=" ")
print()22 16 8
5 11 19
Nested loops are useful for matrices, grids, and tables, but their cost increases as the data grows.
Printing a pattern with nested loops
rows = 5
for row in range(1, rows + 1):
for star in range(row):
print("*", end=" ")
print()* *
* * *
* * * *
* * * * *
Using break
break stops the nearest loop immediately. It is useful when a search has found the required item:
cars = ["Tata", "Honda", "Mahindra", "BMW"]
for car in cars:
if car == "Mahindra":
break
print(car)Honda
Using continue
continue skips the rest of the current iteration and starts the next iteration:
cars = ["Tata", "Honda", "Mahindra", "BMW"]
for car in cars:
if car == "Mahindra":
continue
print(car)Honda
BMW
Using pass
pass does nothing. It is a placeholder when a block must contain a statement but the implementation will be added later:
for number in range(1, 6):
if number % 3 == 0:
pass
else:
print(number)2
4
5
Using else with a for loop
The loop else block runs when the loop finishes normally. It does not run when break exits the loop:
numbers = [2, 4, 6]
for number in numbers:
if number % 2 != 0:
print("Odd number found")
break
else:
print("All numbers are even")Searching for a value
users = ["Asha", "Ravi", "Mina"]
target = "Ravi"
for user in users:
if user == target:
print("User found")
break
else:
print("User not found")Best practices for for loops
- Iterate directly over items instead of using indexes when the index is not needed.
- Use
enumerate()when both the index and item are required. - Use descriptive loop variables such as
studentinstead of vague names. - Keep the loop body small and move reusable logic into a function.
- Use
breakfor early exit andcontinueto skip known exceptions. - Be careful with nested loops because their runtime can grow quickly.
Further Reading
Continue learning with these related Python tutorials:
Continue learning
