Loops in Python (for & while)
A loop repeats a block of code so you don't have to copy-paste it. Python has two kinds. A for loop repeats over a sequence; a while loop repeats as long as a condition stays True:
# for loop: print numbers 1 to 5
for i in range(1, 6):
print(i)
# while loop: count down from 3
n = 3
while n > 0:
print(n)
n -= 1
Let's understand each one.
The for loop
A for loop walks through each item in a sequence — a list, a string, or a range of numbers:
# Loop over a list of names
names = ["Asha", "Ravi", "Meena"]
for name in names:
print(f"Hello, {name}")
# Loop over the characters of a string
for letter in "Python":
print(letter)
To repeat a fixed number of times, use the built-in range():
# range(5) gives 0, 1, 2, 3, 4 — it stops BEFORE the end number
for i in range(5):
print(i)
# range(start, stop, step)
for i in range(2, 11, 2): # even numbers: 2, 4, 6, 8, 10
print(i)
A key point about range(): it stops before the end value. range(1, 6) gives 1, 2, 3, 4, 5 — not 6.
The while loop
A while loop keeps running as long as its condition is True. Use it when you don't know in advance how many times you'll repeat:
# Keep asking until the user types "quit"
command = ""
while command != "quit":
command = input("Enter a command (type 'quit' to stop): ")
print(f"You said: {command}")
print("Goodbye!")
The danger here is the infinite loop: if the condition never becomes False, the loop never ends. Always make sure something inside the loop moves you toward stopping.
Want to learn this properly?
Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.
Browse coursesbreak and continue
Two keywords give you finer control:
breakexits the loop immediately.continueskips the rest of the current iteration and jumps to the next one.
# Stop at the first number divisible by 7
for n in range(1, 100):
if n % 7 == 0:
print(f"First multiple of 7 is {n}")
break # leave the loop now
# Print only odd numbers, skip the even ones
for n in range(1, 11):
if n % 2 == 0:
continue # skip even numbers
print(n)
Looping with an index using enumerate()
When you need both the item and its position, enumerate() is cleaner than tracking a counter yourself:
fruits = ["apple", "banana", "cherry"]
# enumerate gives (index, value) pairs
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# 0: apple
# 1: banana
# 2: cherry
A complete example
# Sum the numbers a user enters until they type 0
total = 0
while True: # loop forever...
text = input("Enter a number (0 to finish): ")
num = int(text)
if num == 0:
break # ...until we hit 0
total += num # add to the running total
print(f"The total is {total}")
Common mistakes
- Infinite while loops: Forgetting to update the loop variable (e.g. missing
n -= 1) means the condition never becomesFalse. If your program hangs, press Ctrl+C to stop it. - Off-by-one with range:
range(1, 5)gives1, 2, 3, 4— not1to5. Remember it stops before the second number. - Modifying a list while looping over it: Removing items from a list inside its own
forloop can skip elements. Loop over a copy instead, or build a new list. - Wrong indentation: Code that should be inside the loop must be indented under it. A line at the wrong indent level runs only once, after the loop.
- Using a while loop when for is clearer: If you're counting a known number of times,
for i in range(n)is simpler and safer than awhilewith a manual counter.
FAQ
When should I use for vs while?
Use for when you know the items or count (looping over a list, or a fixed range). Use while when you loop until some condition changes, like waiting for user input.
Can loops be nested?
Yes. A loop inside a loop is common — for example, looping over rows and then columns of a grid. Each break or continue affects only its own loop.
What is else on a loop?
A loop can have an else block that runs only if the loop finished without hitting break. It's an advanced feature you'll meet later.
Loops pair naturally with collections. Read Lists in Python to see what you'll most often loop over, and If-Else Statements in Python for the conditions inside loops. Explore more on the Python learning hub.
Want to learn this properly? Join the waitlist for our Python course — taught in Jalgaon, beginner-friendly.
Want to learn this properly?
Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.
Browse coursesInstructor, Infoplanet
Kedar Kabra teaches Python at Infoplanet, helping beginners become confident programmers through hands-on, project-first practice.
Related guides
Dictionaries in Python
Understand Python dictionaries — storing data as key-value pairs — including adding, accessing, updating, looping, and safely reading values with .get().
Exception Handling in Python
Handle errors gracefully in Python with try, except, else, and finally — so your program responds to problems instead of crashing.
File Handling in Python
Read from and write to files in Python using with open() — covering file modes, reading line by line, appending, and safe file handling.
