October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

How Do Python Loops Repeat Code? For, While, and Control Flow

Understand Python loops by tracing each iteration, choosing between for and while, and building small examples for totals, word counts, filtering, and searches.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Python loops repeat a block of code: a for loop handles each value supplied by an iterable, while a while loop continues as long as a condition is true. Use for to process items or a known range of values; use while when repetition should end after some state changes. Understanding what advances each loop makes it easier to trace iterations and avoid infinite loops and off-by-one errors.

How does a for loop work in Python?

A for loop asks an iterable—such as a list or string—for its values one at a time. For each value, Python assigns it to the loop variable and runs the indented body. When there are no more values, the loop ends.

As an Amazon Associate I earn from qualifying purchases.

names = ["Ada", "Grace", "Linus"]
for name in names:
    print(name)

The passes are: first, name is "Ada"; next, it is "Grace"; finally, it is "Linus". Python then reaches the end of the list and stops. The loop is driven by the iterable’s values, not by an automatic numeric counter.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

These explanatory examples follow the behavior described in the Python 3.14.8 tutorial on control flow.

Use range() for a sequence of numbers

range() represents an immutable arithmetic sequence. Its stop value is excluded, which means range(5) supplies 0, 1, 2, 3, and 4—not 5.

for number in range(1, 4):
    print(number)  # 1, 2, 3

With two arguments, the first is the start and the second is the excluded stop. Add a third argument to set the step:

for number in range(2, 9, 2):
    print(number)  # 2, 4, 6, 8

Because the stop is excluded, check the endpoints when a loop appears to run one time too few or too many.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When do you need an index?

If you need both a value and its position, use enumerate() rather than managing a separate counter:

for index, name in enumerate(names):
    print(index, name)

Use range(len(items)) only when the index itself is needed for an operation. If you only need each item, iterate over the items directly; it is clearer and avoids unnecessary indexing.

When should you use for versus while?

Loop What drives another pass How it ends Typical use
for The next value from an iterable The iterable runs out of values Processing a collection or a known sequence of values
while A Boolean condition that remains true The condition becomes false Repeating until an event or state change

Choose based on what determines the next pass. A list of prices naturally calls for for; a prompt that should continue until the user enters a valid response naturally calls for while.

Trace a while loop

remaining = 3
while remaining > 0:
    print(remaining)
    remaining -= 1

On the first pass, remaining is 3; after printing, it becomes 2. On the second pass it prints 2, then becomes 1. The third pass prints 1 and changes the value to 0. The next condition check is false, so the loop ends.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The update is essential: if the condition stays true and nothing changes the state it depends on, the loop may never terminate. Decide what will eventually make the condition false, and update that state inside the loop.

How do break, continue, and loop else work?

break stops the current loop

break exits the innermost enclosing loop immediately. In this search, Python prints Found when it reaches Grace and does not inspect Linus:

for name in names:
    if name == "Grace":
        print("Found")
        break

In nested loops, a break exits only the innermost loop—not every loop around it.

continue skips the rest of this pass

continue skips the remaining statements in the current pass and moves to the next item or condition check. For example, this prints only positive values:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
values = [3, 0, -2, 5]
for value in values:
    if value <= 0:
        continue
    print(value)

Loop else means no break occurred

A loop’s optional else suite runs when a for loop exhausts its iterable or a while condition becomes false. It does not run if the loop exits through break. The else is aligned with the loop, not with an if inside it.

target = "Grace"
for name in names:
    if name == target:
        print("Found")
        break
else:
    print("Not found")

When the target is Grace, the loop breaks and the else is skipped. If the target is absent, the loop reaches the end of names normally and prints Not found.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How can you use loops in small projects?

Add up receipt prices

Keep a running total and add each price as the loop visits it:

prices = [2.50, 3.25, 1.75]
total = 0
for price in prices:
    total += price
print(f"Total: ${total:.2f}")

The first pass changes total from 0 to 2.50; the second adds 3.25, making 5.75; the third makes it 7.50. The formatted output is Total: $7.50.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Count words

Split a sentence on whitespace, then update a dictionary once for each word:

sentence = "loops make work repeat"
counts = {}
for word in sentence.split():
    counts[word] = counts.get(word, 0) + 1
print(counts)

The first two passes add "loops": 1 and "make": 1. Later passes add "work": 1 and "repeat": 1. If a word appears again, its existing count increases.

Build a filtered list

When keeping only items that meet a condition, create a new list instead of removing values from the list being traversed:

numbers = [1, 2, 3, 4, 5]
evens = []
for number in numbers:
    if number % 2 == 0:
        evens.append(number)
print(evens)  # [2, 4]

The first value, 1, is not added; the second, 2, is. The loop continues over the original list while building evens. If you need to modify a collection during traversal, iterating over a copy is another option. Changing the collection being traversed can lead to surprising logic.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Make a guessing loop end clearly

A guessing game can use while because it repeats until the player’s input matches the answer or the player quits. Validate input and provide a clear exit path:

secret = 7
while True:
    response = input("Guess 1–10, or type q to quit: ").strip().lower()
    if response == "q":
        print("Goodbye")
        break
    if not response.isdigit():
        print("Enter a whole number or q.")
        continue
    guess = int(response)
    if not 1 <= guess <= 10:
        print("Choose a number from 1 to 10.")
        continue
    if guess == secret:
        print("Correct")
        break
    print("Try again")

For a guess of 4, the loop prints Try again and asks again; a later guess of 7 prints Correct and breaks. Typing q also exits. Non-numeric and out-of-range entries do not end the game; continue returns to the prompt.

What loop mistakes should you watch for?

  • Including the stop value: range(start, stop) excludes stop. Adjust the endpoint only when the desired sequence actually includes that number.
  • Forgetting to change a while condition: update the counter or other relevant state, or provide a deliberate exit such as break.
  • Expecting break to leave every nested loop: it exits only the innermost enclosing loop.
  • Indenting loop else as if it belonged to an if: align it with the loop; it describes normal loop completion without break.
  • Removing items from a collection as you iterate over it: use a copy or build a separate collection to avoid skipping or mishandling values.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.