Python•Loops
Python While Loops: Syntax, Execution, and Conditions
While loops are ideal when the number of iterations is not known in advance, such as polling a connection, processing queues, or consuming user input until exit.
Syntax
while condition:
# statements
# update condition variable
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| condition | Boolean Expression | Re-evaluated at the start of each iteration. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Python locally:
# Countdown and Accumulation with While Loops
count = 3
print("--- Countdown ---")
while count > 0:
print(f"T-minus {count}...")
count -= 1
print("Liftoff! 🚀")
# Doubling algorithm until threshold
power = 1
steps = 0
while power < 50:
power *= 2
steps += 1
print(f"\nDoubled {steps} times to reach: {power}")Expected Output:
--- Countdown --- T-minus 3... T-minus 2... T-minus 1... Liftoff! 🚀 Doubled 6 times to reach: 64
How It Works: Step-by-Step
- Lines 4-6: Decrements count by 1 each cycle until count == 0.
- Lines 12-14: Doubles power each cycle until value reaches 64 (>= 50).
Key Concepts
- The while loop tests the condition before executing the loop body.
- count -= 1 ensures progress towards termination.
- If the condition evaluates to False on the first check, the body never runs.
Common Mistake: Creating an infinite while loop by forgetting to mutate the condition variable
If the condition variable never updates, the loop runs forever and locks CPU execution.
❌ Incorrect
i = 1
while i <= 5:
print(i) # Infinite: i is never incremented✅ Correct
i = 1
while i <= 5:
print(i)
i += 1Related Python Tutorials & Compiler
Python For Loops and the range() Function
A for loop in Python is used for iterating over a sequence (such as a list, tuple, string, or range).
Python Break, Continue, and Pass Loop Control Statements
Control loop execution flow using break to exit early, continue to skip iterations, and pass as a placeholder.
Python If...Else Conditional Statements with Examples
Decision making in Python is performed using if, elif, and else statements to execute code blocks based on boolean conditions.
Python Online Compiler
Open in Compilra IDE
Run and test Python on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.