Python 3.14 Β·
β verified by execution on 2026-07-22
An if runs its block once when a condition is true. A while loop runs its block over and over, as long as the condition stays true β rechecking before every pass. Itβs how you repeat work without copying and pasting lines.
python
count = 0while count < 3: print(count) count += 1
Output
0
1
2
Your output
Exiting Early with break
Sometimes you want to stop looping before the condition turns false. A break statement immediately exits the loop, skipping anything left in the current pass.
python
n = 5while n > 0: if n == 3: break print(n) n -= 1
Output
5
4
Your output
Skipping Iterations with continue
python
i = 0while i < 3: i += 1 if i == 2: continue print(i)
Output
1
3
Your output
The while-else Construct
A while loop can have an else block. It runs once, when the loop finishes because its condition became false β but not if the loop was cut short by a break. That makes else a handy βwe finished without stopping earlyβ signal.
python
x = 0while x < 2: print(x) x += 1else: print('Done')
Output
0
1
Done
Your output
Common Misconceptions
Myth: A while loop stops on its own even if you never change the condition.
Reality: If the condition never becomes false and nothing breaks, you get an infinite loop. Always make sure something inside the loop moves it toward finishing.
Myth: The else block runs when the loop ends by a break.
Reality: Itβs the opposite β else runs only when the loop ends normally. A break skips the else.
Edge Cases
Condition is false initially -> The loop body executes zero times.
Infinite loops -> Must be manually interrupted or handled with timeouts.
Under the Hood
Watch how the program counter jumps back to the condition check at the end of each iteration, and how a break statement jumps out of the loop entirely:
python Β· visualize
n = 3while n > 0: if n == 1: break print(n) n -= 1print("Done")
Check yourself
What happens if a while loop's condition never becomes False and there is no break statement?
Reveal answer
It creates an infinite loop that runs forever until interrupted. β Unlike some bounded loops, a while loop will continuously execute as long as its condition evaluates to True. This results in an infinite loop if unhandled.
What is the purpose of the 'break' statement in a while loop?
Reveal answer
To exit the loop immediately, regardless of the condition. β The break statement terminates the loop completely, jumping execution to the first statement after the loop body.
When does the 'else' block of a while loop execute?
Reveal answer
When the loop's condition becomes False. β The else block executes only when the while condition is evaluated to False. If the loop is terminated by a break statement, the else block is skipped.
Challenges
Challenge 1 +50 XP
Use a while loop to print the numbers 10, 9, 8, 7, in that order.
python
Test 1 β expects "10\n9\n8\n7"
Need a hint? (β25% XP)
Use a while loop that checks if n is greater than 6, and remember to decrement n inside the loop.
Show solution (0 XP)
n = 10while n > 6: print(n) n -= 1
Challenge 2 +100 XP
Given `i = 1`, use a while loop to print odd numbers less than 6.
python
Test 1 β expects "1\n3\n5"
Need a hint? (β25% XP)
Increment i by 2 in each iteration.
Show solution (0 XP)
i = 1while i < 6: print(i) i += 2
Go deeper
Array or Linked List? Score the Workload, Not the Table β Everyone memorises the table - arrays index fast, linked lists insert fast - and still cannot pick one. Run both structures against the same operations here and watch the totals swap places depending only on what the code actually does.
Stacks and Queues, Shown Doing the Jobs They Exist For β Knowing that a stack is last-in-first-out explains nothing about why anyone wanted one. Here a stack matches brackets and catches the error a counter would miss, and a queue runs a ring buffer whose values never move at all.
The Same Seven Numbers, Two Trees: Why Insert Order Decides Lookup Cost β Insert seven numbers into a binary search tree in sorted order and you get a seven-level chain. Insert the same seven in a different order and you get three levels. Build both here, and watch what the shape costs on every lookup afterwards.
A Rotation Is Just Re-Hanging Three Subtrees, and the Order Never Changes β Self-balancing trees are usually taught as four case names before anyone says what a rotation does. Insert the same values with rebalancing on and off here, and watch a tree that would be seven levels deep stay at three.
Breadth-First and Depth-First Are the Same Loop, One Line Apart β BFS and DFS get taught as two algorithms because one is usually written with a queue and the other with recursion. Run both here from one shared loop, changing only which end of the frontier the next node comes from, and watch the paths diverge.
Union-Find Has Two Optimisations Because It Has Two Different Failures β Union by size and path compression are usually presented as one improvement after another. They rescue unrelated cases - and each is useless against the other's. Toggle them independently here and watch which merge order defeats which.
Play the Cache: Why LRU Sometimes Scores Zero β A cache has to decide what to throw away before it knows what will be asked for next. Take the eviction decision yourself here, scored live against LRU and against the best any policy could possibly do.
Find the Wasted Calls: the Skill Behind Every Memoisation β Memoisation is easy to explain and hard to apply, because the difficult part is noticing that a subproblem repeats at all. Here the recursion tree is drawn and you have to find the repeats yourself, scored, with wrong clicks counted.