Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Python Dictionary

  1. Home
  2. Python Dictionary
  3. while / do-while Loops

while / do-while Loops

Python's while statement repeats a block as long as a condition expression is true. The condition is evaluated before the block executes, so if the condition is false from the start, the block is never executed. Notable features include the pattern of combining an infinite loop (while True:) with break, and an else clause usable just like with a for statement.

Syntax

# Basic syntax
while condition:
    # processing repeated while condition is true

# Infinite loop + break pattern
while True:
    # repeated processing
    if exit_condition:
        break

# else clause: executed when the loop did not end via break.
while condition:
    processing
else:
    # executed only when the loop ended normally.

# do-while equivalent (pattern that executes at least once)
while True:
    # processing that always runs at least once
    if exit_condition:
        break

Keywords Reference

Syntax / KeywordNotes
while condition:Repeats the block while the condition expression is truthy. The condition is evaluated before the block executes.
while True:Makes the condition always true to create an infinite loop. The basic pattern is to exit with break.
breakImmediately terminates the loop. The while's else clause is skipped.
continueSkips the remaining processing and moves to the next condition evaluation.
while ... else:Executes the else block when the loop completes without being interrupted by break.

Sample Code

A basic while loop using a counter. A sample that outputs a Jujutsu Kaisen technique name a fixed number of times.

basic_while.py
# Repeat a specified number of times using a counter.
count = 0

while count < 3:
    print(f"Black Flash activated ({count + 1})")
    count += 1  # forgetting to update the counter causes an infinite loop.

print("Done")
python3 basic_while.py
Black Flash activated (1)
Black Flash activated (2)
Black Flash activated (3)
Done

Combining an infinite loop (while True:) with break. Used when processing needs to repeat until a certain condition is met.

infinite_loop.py
import random

# Simulation of continuously activating a technique until cursed energy hits 0.
cursed_energy = 100

while True:
    # Calculate a random consumption amount each turn.
    cost = random.randint(10, 40)
    cursed_energy -= cost
    print(f"Technique activated: energy -{cost} -> remaining {cursed_energy}")

    # End the loop when cursed energy drops to 0 or below.
    if cursed_energy <= 0:
        print("Out of cursed energy. Stopping technique.")
        break
python3 infinite_loop.py
Technique activated: energy -23 -> remaining 77
Technique activated: energy -35 -> remaining 42
Technique activated: energy -18 -> remaining 24
Technique activated: energy -30 -> remaining -6
Out of cursed energy. Stopping technique.

The else clause is only executed when the loop did not end via break. A sample that determines whether a target cursed spirit was found.

while_else.py
# Search for a cursed spirit of a specific grade in a list.
curses = [
    ("Hanami", 1),
    ("Mahito", 1),
    ("Jogo", 1),
    ("Dagon", 1),
]
target_grade = 2   # grade to search for.
index = 0

while index < len(curses):
    name, grade = curses[index]
    if grade == target_grade:
        print(f"{name} (Special Grade {grade}) found")
        break
    index += 1
else:
    # Executed when the loop ended without break (not found).
    print(f"No cursed spirit of grade {target_grade} was found")
python3 while_else.py
No cursed spirit of grade 2 was found

Python has no do-while statement, but the same behavior can be written with while True: and break. The block is guaranteed to execute at least once.

do_while_pattern.py
# do-while equivalent pattern: execute the block first, then evaluate the condition.
# Simulation that fires Itadori Yuji's consecutive punches at least once.
punch_count = 0
max_punches = 3

while True:
    punch_count += 1
    print(f"Divergent Fist punch {punch_count}")

    # Evaluate the condition at the end of the block (do-while substitute).
    if punch_count >= max_punches:
        break

print(f"Total: {punch_count} punches")
python3 do_while_pattern.py
Divergent Fist punch 1
Divergent Fist punch 2
Divergent Fist punch 3
Total: 3 punches

Skipping specific iterations with continue. A sample that skips processing only on forbidden turns.

while_continue.py
# Advance turns while skipping forbidden ones.
turn = 0
forbidden_turns = {2, 4}   # these turn numbers are forbidden.

while turn < 6:
    turn += 1

    # Skip to the next turn on forbidden turns.
    if turn in forbidden_turns:
        print(f"Turn {turn}: forbidden (skipped)")
        continue

    print(f"Turn {turn}: normal action")
python3 while_continue.py
Turn 1: normal action
Turn 2: forbidden (skipped)
Turn 3: normal action
Turn 4: forbidden (skipped)
Turn 5: normal action
Turn 6: normal action

Notes

The while statement is suited for cases where "the number of iterations is not known in advance". When the count is fixed, a combination of a for statement and range() is more appropriate. See for loops for details.

Infinite loops (while True:) are frequently used in practical situations such as accepting user input or waiting for server requests. However, always providing a break condition is essential. Forgetting update operations (such as incrementing a counter) can result in an unintended infinite loop.

The else clause behaves the same as with a for statement: it does not execute when the loop is terminated by break. It is useful when writing search loops, as it allows determining "whether the target was found or not" without a subsequent flag variable. Python has no do-while statement, but the pattern while True: ... if condition: break expresses equivalent behavior.

Common Mistakes

Forgetting to update the counter, causing an infinite loop

Forgetting to update the counter variable inside a while loop leaves the condition unchanged and causes an infinite loop.

while_infinite_ng.py
# NG pattern: i is never updated, causing an infinite loop
i = 0
while i < 3:
    print("Itadori Yuji")
    # i += 1 is missing
while_infinite_ok.py
# OK pattern: always update the counter
i = 0
while i < 3:
    print("Itadori Yuji")
    i += 1
Itadori Yuji
Itadori Yuji
Itadori Yuji

Off-by-one error (boundary value mistake)

Choosing between < and <= in the condition changes the number of loop iterations by one.

while_offbyone.py
members = ["Itadori Yuji", "Megumi Fushiguro", "Nobara Kugisaki", "Gojo Satoru", "Nanami Kento"]

# NG pattern: <= causes an IndexError
i = 0
while i <= len(members):  # loops up to 5, so members[5] raises an error
    print(members[i])
    i += 1
while_offbyone_ok.py
members = ["Itadori Yuji", "Megumi Fushiguro", "Nobara Kugisaki", "Gojo Satoru", "Nanami Kento"]

# OK pattern: use <
i = 0
while i < len(members):
    print(members[i])
    i += 1
Itadori Yuji
Megumi Fushiguro
Nobara Kugisaki
Gojo Satoru
Nanami Kento

Forgetting break and staying in an infinite loop

In the while True: pattern, not writing break for the exit condition causes the loop to run forever.

while_break.py
# OK pattern: make the exit condition explicit
attempts = 0
while True:
    attempts += 1
    if attempts >= 3:
        print(f"Reached {attempts} attempts. Stopping.")
        break
    print(f"Attempt {attempts}")
Attempt 1
Attempt 2
Reached 3 attempts. Stopping.

If you find any errors or copyright issues, please .