Python Loops
Loops let you repeat a block of code multiple times without writing it again. Python has two main loops — for and while. Mastering loops is essential because 90% of real programs involve iteration.
for Loop
Used to iterate over a sequence (list, tuple, string, range, etc.).
# Loop through a list
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(fruit)
# Loop through a string
for char in "Python":
print(char)
# Loop through range
for i in range(5):
print(i) # 0 1 2 3 4
The range() Function
Generates a sequence of numbers. Very common in loops.
# 0 to 4
for i in range(5):
print(i)
# 1 to 5
for i in range(1, 6):
print(i)
# 1 to 10 with step 2
for i in range(1, 11, 2):
print(i) # 1 3 5 7 9
# Countdown
for i in range(10, 0, -1):
print(i)
while Loop
Repeats a block as long as a condition is True. Use when you don't know how many iterations in advance.
count = 1
while count <= 5:
print(count)
count += 1
# Output: 1 2 3 4 5
If the condition in while never becomes False, the loop runs forever. Always ensure your loop variable changes inside the loop.
break — Exit Loop Early
Stops the loop immediately, even if the condition is still True.
for i in range(10):
if i == 5:
break
print(i)
# Output: 0 1 2 3 4
continue — Skip Current Iteration
Skips the rest of the current iteration and moves to the next one.
for i in range(10):
if i % 2 == 0:
continue
print(i)
# Output: 1 3 5 7 9 (only odd numbers)
pass — Do Nothing
Placeholder when no code is needed. Useful when writing structure first.
for i in range(5):
pass # TODO: implement later
for...else and while...else
Unique to Python — the else block runs after the loop finishes, but NOT if it was interrupted by break.
for i in range(5):
print(i)
else:
print("Loop finished")
# Output:
# 0 1 2 3 4
# Loop finished
# With break — else is skipped
for i in range(5):
if i == 3:
break
print(i)
else:
print("This won't run")
Nested Loops
# Multiplication table 1-3
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i*j}")
print("---")
Looping Through Dictionaries
student = {"name": "Ankit", "age": 22, "course": "Python"}
# Keys only
for key in student:
print(key)
# Keys and values
for key, value in student.items():
print(f"{key}: {value}")
enumerate() and zip()
fruits = ["apple", "banana", "mango"]
# Get index + value
for i, fruit in enumerate(fruits):
print(i, fruit)
# Loop two lists together
names = ["Ankit", "Priya", "Rahul"]
marks = [85, 92, 78]
for name, mark in zip(names, marks):
print(f"{name}: {mark}")
Real-World Example — Pattern Printing
# Star triangle
rows = 5
for i in range(1, rows + 1):
print("*" * i)
# Output:
# *
# **
# ***
# ****
# *****
Prefer for loops over while loops whenever you know the number of iterations. while is best for reading files, waiting for user input, or polling.
Write a program that prints the multiplication table of any number the user enters (1 to 10). Then write a separate program that finds the sum of all even numbers from 1 to 100 using a loop.
Quick Revision
foriterates over a sequence.whilerepeats while a condition is True.range(start, stop, step)generates numbers.breakexits the loop;continueskips one iteration.passdoes nothing — placeholder.for...elserunselseonly if nobreakoccurred.- Use
enumerate()for index + value,zip()for parallel loops.
Interview Questions
Q: Difference between for and while loops?
A: for is used when the number of iterations is known or you're iterating over a sequence. while is used when iterations depend on a condition that may change. for is generally safer and preferred when possible.
Q: What is the difference between break and continue?
A: break exits the entire loop. continue skips the rest of the current iteration and moves to the next. Example: in a loop printing 1-10, continue at 5 skips 5 but keeps printing 6-10; break at 5 stops at 4.
Q: What is the purpose of pass?
A: pass is a null statement that does nothing. It's used as a placeholder when syntax requires a statement but no action is needed yet — e.g., inside an empty function or class.
Q: What does for...else do?
A: The else block executes only if the loop finishes normally (without hitting break). Useful for search operations — you know the item wasn't found if else runs.
Q: How do you loop with an index in Python?
A: Use enumerate(): for i, item in enumerate(my_list): print(i, item). It's cleaner than using range(len(...)).
Want to Master Python?
Join our Python course in Varanasi — practical classes and career support at our Sarnath centre.