for, while, range & break/continue
Loop over sequences and ranges and stop or skip at the right moment.
By Invicly Tech, , in Python Programming from Zero. About 12 minutes to read.
In short
Loops repeat work. A for loop walks through each item of a sequence or range; a while loop repeats as long as a condition stays true. break stops a loop early and continue skips to the next round.
Explained simply
Loops let a program repeat work without copying code. A for loop says "for each item in this collection, do this". It works on lists, strings (letter by letter), ranges of numbers, dictionaries, and even files (line by line).
range() produces numbers on demand. range(5) gives 0, 1, 2, 3 and 4: it starts at 0 and stops just before the number you give. Use it when you need to repeat something a fixed number of times or count in steps.
A while loop repeats as long as a condition stays True. Use it when you do not know in advance how many rounds you need, such as asking again until the user types something valid. Something inside the loop must eventually make the condition False, or it runs forever.
break leaves a loop early and continue skips to the next round. Helpers like enumerate() (adds a counter) and zip() (walks two lists side by side) keep loops short and clear, so you almost never need to manage index numbers by hand.
Press Play on a diagram to walk through it one step at a time.
- 1Ask for next item
The loop pulls the next value from the iterable
- 2Bind loop variable
for item in ... assigns it to item
- 3Run the body
continue jumps back, break exits entirely
- 4Repeat or stop
No items left? The loop ends
- Back to step 1
- Walks a known collection
- Stops automatically at the end
- Great with range(), enumerate()
- Hard to loop forever by mistake
- Repeats while a condition holds
- You must update the condition
- Good for unknown repeat counts
- Easy to create infinite loops
- Leaves the loop at once
- Skips the loop's else block
- Use when the job is done early
- Skips the rest of this round
- The loop goes on with the next item
- Use to ignore bad items
- Runs when the loop ends without break
- Perfect for "not found"
- Read it as "no break"
- list or tuple
- Each item in order
- str
- Each character
- dict
- Keys by default
- items() for key and value
- range
- Numbers, made on demand
- open file
- Each line, newline included
- zip or enumerate
- Tuples you can unpack
In depth
What a for loop really does
A for loop works with any iterable, which means any object that can hand out its items one at a time. Behind the scenes Python calls iter() on the object to get an iterator, then calls next() on that iterator again and again. Each value is bound to the loop variable and the body runs. When the iterator has nothing left, it raises a special signal called StopIteration and the loop ends quietly.
This one protocol is why the same for syntax works on lists, strings, sets, dict keys, file lines and range objects. It is also why some things can only be looped over once: a file or a zip object is its own iterator, and once it is used up, a second loop gets nothing.
One more detail: the loop variable is an ordinary variable. After the loop it still holds the last value, and assigning to it inside the loop does not change the list.
- for loop to str "ab": iter("ab")1iter("ab")
- str "ab" to for loop: Here is an iterator2Here is an iterator
- for loop to iterator: next(): gives "a", run body3next(): gives "a", run body
- for loop to iterator: next(): gives "b", run body4next(): gives "b", run body
- for loop to iterator: next() again5next() again
- iterator to for loop: StopIteration: loop ends6StopIteration: loop ends
range() in depth
range has three forms: range(stop), range(start, stop) and range(start, stop, step). The stop value is never included, which makes range(len(x)) and range(0, 10, 2) line up neatly with indexes. A negative step counts down: range(10, 0, -2) gives 10, 8, 6, 4, 2.
A range does not build a list of numbers. It stores only start, stop and step and calculates each number when asked, so range(1_000_000_000) uses almost no memory, and len() and in on it are instant. Wrap it in list() when you want to see the numbers.
A common beginner habit is for i in range(len(items)) followed by items[i]. Loop over the items directly instead, use enumerate() when you also need the position, and reversed(items) to walk backwards. Keep range for real counting jobs: repeat ten times, every third number, a countdown.
- list(range(3)) is [0, 1, 2]
- range(5, 0, -1) gives 5, 4, 3, 2, 1
- range(0) and range(5, 2) are empty: the body never runs
while loops, exit conditions and the loop else
Every while loop needs a clear answer to "what makes this stop?". Usually it is a variable that changes each round (a counter, the remaining input) or a break when you have what you need. The ask-until-valid pattern is while True: with a break on success; the condition is always True, so break is the only exit and is easy to spot.
If a loop runs away, press Ctrl+C. Python raises KeyboardInterrupt and stops.
for and while loops can also have an else block. It runs only when the loop ends normally, without break. That fits search loops perfectly: break when you find the item, and put the "not found" code in else. No extra found flag is needed. It reads strangely at first; think of it as "no break".
- 1Ask
input() returns the typed text
- 2Try to convert
int() or another check
- 3Valid?
Yes: break out of the loop
- 4Invalid
Print a helpful message
- 5Go again
while True starts the next round
- Back to step 1
enumerate, zip and looping over dicts
enumerate(items) yields pairs of (position, item); start=1 makes it count from 1 for humans. zip(a, b) yields pairs of items taken side by side and stops at the end of the shortest input, silently dropping leftovers. From Python 3.10, zip(a, b, strict=True) raises ValueError instead, which catches mismatched data early.
You can unpack nested pairs right in the for line: for i, (name, score) in enumerate(zip(names, scores)):. dict(zip(keys, values)) builds a dictionary from two lists.
Looping over a dict gives its keys. Use d.values() for values and d.items() for (key, value) pairs. Wrap any of these in sorted() to loop in a defined order, for example sorted(d.items()) for alphabetical keys.
Changing a collection while looping over it
Removing items from a list while a for loop walks over it skips elements. The loop keeps an internal position; when you remove the current item, everything after it shifts left and the next item is jumped over. Try it: with nums = [1, 2, 2, 3], removing every 2 inside the loop leaves [1, 2, 3].
The fix is to build a new list with the items you want to keep, or to loop over a copy (for n in nums[:]) while changing the original. Dictionaries and sets are stricter: changing their size during a loop raises RuntimeError. Loop over list(d) when you need to delete keys.
Also remember that for x in nums: x = x * 2 changes nothing in nums, because x is only a name for each item. To change items in place, assign through the index, or build a new list.
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Loop over lists and strings with for~35m
- 2Generate numbers with range()~35m
- 3Write while loops with clear exit conditions~35m
- 4Use break and continue correctly~35m
- 5Iterate with enumerate() and zip()~35m
Key points
- range(start, stop, step) excludes stop: range(3) gives 0, 1, 2.
- enumerate(items) gives (index, item) pairs; zip(a, b) pairs items from two lists.
- break leaves the loop immediately; continue skips the rest of this iteration.
- Every while loop needs something inside that eventually makes its condition False.
Key terms
Tap a card to flip it. 0/5 known
Examples
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits, start=1):
print(i, fruit)
for n in range(10):
if n % 2 == 0:
continue # skip even numbers
if n > 7:
break # stop at 9
print(n) # 1 3 5 7
count = 3
while count > 0:
print("T-minus", count)
count -= 1Ranking players with zip and enumerate
You have names and scores in two lists in the same order. Step 1: zip() pairs them, putting the score first so it is used for sorting. Step 2: sorted(..., reverse=True) puts the highest score first. Step 3: enumerate(..., start=1) adds the place number. Step 4: unpack the nested tuple right in the for line, so the body reads naturally. No index arithmetic anywhere.
names = ["Ana", "Bo", "Cy"]
scores = [88, 95, 70]
ranked = sorted(zip(scores, names), reverse=True)
for place, (score, name) in enumerate(ranked, start=1):
print(f"{place}. {name:<4} {score}")
# 1. Bo 95
# 2. Ana 88
# 3. Cy 70Three tries to enter a valid number
The user gets three attempts to pick a number from 1 to 10. Step 1: the while condition limits the attempts. Step 2: continue skips the rest of the round when the text is not a number. Step 3: break leaves the loop as soon as the value is valid. Step 4: the loop's else block runs only if the user used all three attempts without a break, so the failure message needs no extra flag variable.
attempts = 0
while attempts < 3:
text = input("Pick 1-10: ").strip()
attempts += 1
if not text.isdigit():
print("Digits only, please")
continue
n = int(text)
if 1 <= n <= 10:
print("Thanks, you picked", n)
break
print("Out of range")
else:
print("Too many tries, giving up")Quick reference
- range(10, 0, -2) gives 10, 8, 6, 4, 2: a negative step counts down, stop excluded
- for i, item in enumerate(items, start=1) gives a counter without range(len(...))
- zip(a, b, strict=True) raises ValueError when the lengths differ (Python 3.10+)
- for k, v in d.items() loops over a dict's keys and values together
- A loop's else block runs only if the loop finished without break
- while True: ... break is the standard pattern for ask-until-valid loops
- Never remove items from a list you are looping over; build a new list instead
- Ctrl+C stops a runaway loop in the terminal by raising KeyboardInterrupt
Common mistakes
- Forgetting to change the variable a while loop tests, causing an infinite loop.
- Off-by-one errors: range(1, 10) stops at 9, not 10.
- Adding or removing items from a list while looping over it.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Print the 7 times table from 7 x 1 to 7 x 10. Then print only the results that are even.
- Exercise 2medium
Given words = ["go", "python", "is", "fun", "stop", "never"], print each word with its position starting at 1. Skip words shorter than 3 letters and stop completely when you reach "stop".
- Exercise 3hard
Write a guessing game: pick a secret number from 1 to 100 with random.randint, answer each guess with Higher or Lower, allow at most 7 guesses, and use the loop's else to reveal the number if the player runs out.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- How do I loop over a list backwards in Python?
- Use for item in reversed(items), or items[::-1] if you want a reversed copy. range(len(items) - 1, -1, -1) also works but is harder to read.
- How do I get the index in a for loop?
- Use for i, item in enumerate(items). Use range(len(items)) only when you really need just the index, for example to change items in place.
- Does Python have a do-while loop?
- No. Write while True:, put the body first, and end it with if condition: break, so the body always runs at least once.
- How do I stop an infinite loop?
- Press Ctrl+C in the terminal, which raises KeyboardInterrupt. Then make sure something inside the loop changes the condition or reaches a break.