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 desk4 min

Python Loops: How to Repeat Actions Without Repeating Code

Python’s for loop visits items; its while loop repeats while a condition is true. Learn range(), loop control, and common mistakes.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a for loop when you want to process each item in an iterable, such as a list or string. Use a while loop when you want to repeat code as long as a condition is true. The key difference is whether your repetition is driven by available items or by a condition.

Use a for loop to process each item

A Python for loop takes items from an iterable one at a time and runs its body for each one. The Python Tutorial puts it this way: “The for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.” (Python Tutorial, section 4.2.)

names = ["Ari", "Bo", "Cy"]
for name in names:
    print(f"Hello, {name}!")

On each pass, name is bound to the next value: first "Ari", then "Bo", then "Cy". You do not need to create or update a counter just to visit every name. A for loop works with many iterables, not only lists; for example, it can process characters in a string.

Use range() when numbers are the items

When you need a sequence of numbers—for example, to repeat an operation a set number of times—use range():

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
for number in range(1, 6):
    print(number)

This prints 1 through 5. The stop value, 6, is excluded. Likewise, range(5) supplies 0, 1, 2, 3, and 4: five values, not the numbers 1 through 5. You can provide a start, stop, and step, including a negative step for a descending sequence. A range represents an arithmetic progression and supplies its values as you iterate rather than building a list of every value up front. See the Python Tutorial’s discussion of range().

Do not use range(len(items)) by default when the items themselves are what you need. Prefer for item in items. If you need both each item and its position, use enumerate():

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

Use while when a condition controls repetition

A while loop tests a condition and runs its body while that condition is true. The condition is checked before each pass, so a false condition at the start means the body does not run at all.

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

Here, remaining -= 1 changes the state that the condition checks. Eventually remaining > 0 becomes false, and the loop ends. The Python language reference specifies how while conditions and loop bodies work.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

Before writing a while loop, identify what will make its condition false or what deliberate exit will stop it. Some loops intentionally wait for a sentinel value or user action; an accidental loop that never changes its condition may run indefinitely.

Choose the loop that matches the task

Question Use Example
Do you have items to process, in order? for for name in names:
Should repetition continue while a condition stays true? while while remaining > 0:
Do you need a numeric progression? for with range() for number in range(1, 6):
Do you need an item’s position as well as its value? for with enumerate() for index, name in enumerate(names):

Stop or skip work with break and continue

Use break to leave a loop as soon as you have what you need. This example stops searching after the first match:

target = "Bo"
for name in names:
    if name == target:
        print("Found", name)
        break

break exits only the innermost enclosing for or while loop. In nested loops, an inner-loop break does not automatically exit the outer loop.

Use continue when you want to skip the rest of the current pass and move on to the next iteration:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
for number in range(5):
    if number == 2:
        continue
    print(number)

This skips printing 2; the remaining values are still processed. In a while loop, continue returns control to the condition check, so make sure the loop can still make progress rather than repeating the same state forever. The Python language reference defines the behavior of both statements.

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

Use loop else for normal completion without break

A loop may have an optional else suite. It runs when a for iterator is exhausted or a while condition becomes false. It is skipped if the loop ends with break; a return or raised exception also bypasses it.

target = "Dee"
for name in names:
    if name == target:
        print("Found", name)
        break
else:
    print("No match")

In this search, else means no item matched before the loop completed. Indent it at the same level as for, not under the if: the else belongs to the loop, not to the conditional. The Python Tutorial explains this pattern in its sections on loop statements.

Avoid common loop mistakes

  • Expecting the stop value in range(): the stop endpoint is excluded, so range(5) ends at 4.
  • Counting when you can process the item directly: write for item in items unless you genuinely need an index; use enumerate(items) when you need both.
  • Changing a collection while iterating over it: deleting or adding entries to the same collection during traversal can produce confusing results. The Python Tutorial recommends iterating over a copy or building a new collection instead. Its collection-mutation example shows both approaches.
  • Forgetting how a while loop ends: check that its condition changes or that a deliberate exit path can occur.
  • Assuming break leaves every nested loop: it exits only the innermost loop.
  • Reading loop else as an if alternative: it belongs to the loop and runs only after normal completion without break.

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.

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

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
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair 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.