6 min read
ā¢Question 8 of 41easyLoops in Python
For and while loops in Python.
What You'll Learn
- For loops and iteration patterns
- While loops and when to use them
- Loop control: break, continue, else
- Useful built-in functions: range, enumerate, zip
- Performance considerations
Understanding Python Loops
Loops allow you to execute code repeatedly. Python's loop syntax is clean and readable, emphasizing iteration over sequences rather than manual index management.
For Loop
The for loop iterates over any iterable (lists, strings, ranges, etc.):
code.pyPython
# Iterate over list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Iterate over string
for char in "Python":
print(char)
# Iterate over dictionary
person = {"name": "John", "age": 30}
for key in person:
print(key) # Keys only
for key, value in person.items():
print(f"{key}: {value}") # Key-value pairsThe range() Function
Generate sequences of numbers:
code.pyPython
# range(stop) - 0 to stop-1
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# range(start, stop)
for i in range(2, 6):
print(i) # 2, 3, 4, 5
# range(start, stop, step)
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8
# Counting backwards
for i in range(5, 0, -1):
print(i) # 5, 4, 3, 2, 1enumerate() - Get Index and Value
code.pyPython
fruits = ["apple", "banana", "cherry"]
# Without enumerate (not Pythonic)
for i in range(len(fruits)):
print(f"{i}: {fruits[i]}")
# With enumerate (Pythonic!)
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# Start from different index
for i, fruit in enumerate(fruits, start=1):
print(f"{i}: {fruit}") # 1: apple, 2: banana, 3: cherryzip() - Parallel Iteration
code.pyPython
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
# Iterate two lists together
for name, age in zip(names, ages):
print(f"{name} is {age}")
# Zip three lists
cities = ["NYC", "LA", "Chicago"]
for name, age, city in zip(names, ages, cities):
print(f"{name}, {age}, {city}")
# Unequal lengths - stops at shortest
list1 = [1, 2, 3]
list2 = [4, 5]
for a, b in zip(list1, list2):
print(a, b) # (1,4), (2,5) - stops at 2 pairsWhile Loop
Execute while a condition is true:
code.pyPython
# Basic while
count = 0
while count < 5:
print(count)
count += 1
# Infinite loop with break
while True:
user_input = input("Enter 'quit' to exit: ")
if user_input == "quit":
break
print(f"You entered: {user_input}")
# Common pattern: processing until condition
data = [1, 2, 3, 4, 5]
while data: # While list is not empty
item = data.pop()
print(item)Loop Control Statements
code.pyPython
# break - exit loop immediately
for i in range(10):
if i == 5:
break
print(i) # 0, 1, 2, 3, 4
# continue - skip to next iteration
for i in range(5):
if i == 2:
continue
print(i) # 0, 1, 3, 4
# pass - do nothing (placeholder)
for i in range(5):
if i == 2:
pass # TODO: handle this case
print(i) # 0, 1, 2, 3, 4The else Clause (Unique to Python)
Executes when loop completes without break:
code.pyPython
# else runs after loop completes
for i in range(3):
print(i)
else:
print("Loop completed normally")
# else doesn't run if break occurs
for i in range(5):
if i == 3:
break
else:
print("This won't print")
# Practical use: search pattern
def find_item(items, target):
for item in items:
if item == target:
print(f"Found {target}")
break
else:
print(f"{target} not found")Nested Loops
code.pyPython
# 2D iteration
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for num in row:
print(num, end=" ")
print() # New line after each row
# With indices
for i in range(3):
for j in range(3):
print(f"({i},{j})", end=" ")
print()Interview Tip
When asked about Python loops:
- Use
forfor iterating over sequences - Use
whilefor condition-based loops - Always prefer
enumerate()overrange(len()) - Use
zip()for parallel iteration - Understand the
elseclause on loops - Avoid modifying a list while iterating over it