Loops repeat work without copying the same line many times.
A for loop is best when you already have a sequence to process, while a while loop is best when repetition depends on a condition becoming false.
Good loop code has a clear stop point, a small body, and names that reveal what each item represents.
Loops let you execute a block of code repeatedly. Python has two loop types: for (iterate over a sequence) and while (repeat while a condition is true).
Iterates over any iterable - list, tuple, string, range, dict, etc.
# Iterate over a list
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(fruit)
# Iterate over a string
for char in "Python":
print(char, end=" ") # P y t h o n
# Iterate over a range
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(1, 6): # 1, 2, 3, 4, 5
print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8 (step=2)
print(i)
for i in range(10, 0, -1): # 10, 9, 8 ... 1 (countdown)
print(i)
fruits = ["apple", "banana", "mango"]
# enumerate - get index and value
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# 0: apple
# 1: banana
# 2: mango
# enumerate with custom start
for i, fruit in enumerate(fruits, start=1):
print(f"{i}. {fruit}")
# zip - iterate two lists together
names = ["Alice", "Bob", "Charlie"]
scores = [95, 87, 92]
for name, score in zip(names, scores):
print(f"{name}: {score}")
# Iterate dict items
person = {"name": "Alice", "age": 25}
for key, value in person.items():
print(f"{key} = {value}")
# Nested loops
for i in range(1, 4):
for j in range(1, 4):
print(f"{i}x{j}={i*j}", end=" ")
print()
Repeats as long as a condition is True. Use when you don't know the number of iterations in advance.
count = 0
while count < 5:
print(count)
count += 1 # IMPORTANT: always update the condition variable
# User input loop
while True:
answer = input("Type 'quit' to exit: ")
if answer == "quit":
break
print(f"You typed: {answer}")
# Countdown
n = 10
while n > 0:
print(n, end=" ")
n -= 1
print("Go!")
# break - exit the loop immediately
for i in range(10):
if i == 5:
break
print(i) # prints 0 1 2 3 4
# continue - skip current iteration, go to next
for i in range(10):
if i % 2 == 0:
continue
print(i) # prints 1 3 5 7 9 (odd numbers only)
# pass - keep this branch intentionally empty
for i in range(5):
if i == 3:
pass # reserved for special handling later
print(i) # prints all 0 1 2 3 4
# for-else / while-else
# else block runs only if loop completed without break
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
break
else:
print(f"{n} is prime") # 2 3 5 7
A concise way to create lists using a single line. Much more Pythonic than a for loop with append().
# List comprehension: [expression for item in iterable if condition]
squares = [x**2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
evens = [x for x in range(20) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
words = ["hello", "world", "python"]
upper = [w.upper() for w in words]
print(upper) # ['HELLO', 'WORLD', 'PYTHON']
# Nested comprehension (flatten a 2D list)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Dict comprehension
squares_dict = {x: x**2 for x in range(1, 6)}
print(squares_dict) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Set comprehension
unique_lengths = {len(w) for w in words}
print(unique_lengths) # {5, 6}
0 of 2 checked
Try this next
0 of 2 completed
Choose for when you are looping over known items. Choose while when repetition depends on a condition changing over time.
A while loop becomes infinite when its condition never becomes false. Update the controlling value inside the loop.
Use break when the loop has found what it needed or continuing would be wrong. Keep the reason easy to see.
Explore 500+ free tutorials across 20+ languages and frameworks.