Syntax
for variable in iterable:
# code to execute for each itemExamples
List Iteration
Iterating through lists to process each element.
fruits = ["apple", "banana", "orange", "grape"]
for fruit in fruits:
print(f"I like {fruit}")
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
print(f"Sum: {total}") # 15Range Function
Using range() to iterate a specific number of times or generate number sequences.
# Count from 0 to 4
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# Count from 1 to 5
for i in range(1, 6):
print(i) # 1, 2, 3, 4, 5
# Count by steps
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8
# Countdown
for i in range(5, 0, -1):
print(f"{i}...") # 5... 4... 3... 2... 1...
print("Liftoff!")String Iteration
Iterating through characters in a string.
message = "Python"
for char in message:
print(char) # P, y, t, h, o, n
# Count vowels
text = "Hello World"
vowels = "aeiouAEIOU"
vowel_count = 0
for char in text:
if char in vowels:
vowel_count += 1
print(f"Vowels found: {vowel_count}")Enumerate Function
Getting both index and value while iterating using enumerate().
fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits):
print(f"{index + 1}. {fruit}")
# Output:
# 1. apple
# 2. banana
# 3. orange
# Start counting from different number
for index, fruit in enumerate(fruits, start=10):
print(f"Item {index}: {fruit}")Dictionary Iteration
Iterating through dictionary keys, values, or both.
student_scores = {
"Alice": 85,
"Bob": 92,
"Charlie": 78
}
# Iterate over keys
for name in student_scores:
print(f"{name}: {student_scores[name]}")
# Iterate over values
for score in student_scores.values():
print(f"Score: {score}")
# Iterate over key-value pairs
for name, score in student_scores.items():
print(f"{name} scored {score}")
if score >= 90:
print(" Excellent!")Nested Loops
Using loops within loops for multi-dimensional iteration.
# Multiplication table
for i in range(1, 4):
for j in range(1, 4):
product = i * j
print(f"{i} × {j} = {product}")
print() # Empty line between tables
# Pattern printing
for row in range(1, 5):
for col in range(row):
print("*", end=" ")
print() # New line after each rowBreak and Continue
Controlling loop execution with break and continue statements.
# Break - exit loop early
for num in range(1, 11):
if num == 5:
print("Found 5! Stopping...")
break
print(num)
print()
# Continue - skip to next iteration
for num in range(1, 6):
if num == 3:
continue # Skip 3
print(num) # Prints 1, 2, 4, 5
print()
# Practical example
passwords = ["abc", "password123", "12345", "secure_pass"]
for pwd in passwords:
if len(pwd) < 8:
print(f"{pwd} - Too short, skipping...")
continue
print(f"{pwd} - Valid password")
if pwd == "secure_pass":
print("Found secure password!")
breakBest practices
- Use descriptive variable names in for loops (for student in students: instead of for s in students:)
- Use enumerate() when you need both index and value
- Prefer list comprehensions for simple transformations ([x*2 for x in numbers])
- Avoid modifying the list you're iterating over - create a new list instead
- Use range(len(list)) only when absolutely necessary - prefer direct iteration
- Break complex nested loops into separate functions for better readability
At a glance
- Purpose
- Scripting and general-purpose applications
- File extension
- .py
- Runs in
- Python interpreter
- Usually used with
- Python standard library and packages
Specifications & further reading
Related Python documentation
The if statement is Python's primary conditional control structure. It allows your program to make decisions by executing different code blocks based on whether a condition is True or False. The if statement is fundamental to creating dynamic, responsive programs that can adapt their behavior based on various conditions, user input, or data states.while
The while loop repeats a block of code as long as its condition remains True. Unlike a for loop, which iterates a known number of times over a sequence, a while loop is ideal when you don't know in advance how many iterations you'll need - like waiting for valid user input or running until some external condition changes. A while loop can also have an optional else clause that runs if the loop finishes normally, without hitting a break.break and continue
break and continue give you fine-grained control over loop execution. break immediately exits the nearest enclosing loop entirely, skipping any remaining iterations. continue skips just the rest of the current iteration and jumps straight to the next one, without exiting the loop. Both work inside for and while loops.pass
pass is a null operation - a statement that does absolutely nothing when executed. It exists purely to satisfy Python's syntax, which requires every block (function, class, loop, conditional) to contain at least one statement. pass is commonly used as a temporary placeholder while you're still planning out code, or to intentionally leave a branch empty.