πŸ” Python while Loop β€” Comprehensive Lesson + Practice Editor

Learn how while loops work (conditions, counters, sentinels, break/continue, nested loops), avoid infinite loops, and run code instantly using Pyodide.

1) What is a while loop?

A while loop repeats a block of code as long as a condition is True. The condition is checked before each iteration.

Basic pattern
count = 1
while count <= 5:
    print(count)
    count += 1

2) Anatomy of a while loop (must-have parts)

A Initialization

Set a starting value (like a counter).

B Condition

The loop runs while this stays True.

C Update

Change variables so the loop can eventually stop.

Initialization β†’ Condition β†’ Update
i = 0                 # A) initialization
while i < 3:          # B) condition
    print("i =", i)
    i += 1            # C) update

Common mistake: forgetting the update

If you forget to change the loop variable, the condition may never become False. That causes an infinite loop.

Infinite loop example (DON'T RUN in real terminal)
i = 0
while i < 5:
    print(i)
    # i += 1  ❌ missing update -> infinite loop

3) Classic patterns you should master

βœ… Pattern 1: Counting loop (counter-controlled)
Count from 1 to 10
i = 1
while i <= 10:
    print(i, end=" ")
    i += 1
βœ… Pattern 2: Countdown loop
Countdown 10 to 1
i = 10
while i >= 1:
    print(i, end=" ")
    i -= 1
βœ… Pattern 3: Sentinel-controlled loop (stop on a special value)
Stop when user enters 'q'
while True:
    s = input("Type something (q to quit): ")
    if s.lower() == "q":
        break
    print("You typed:", s)
βœ… Pattern 4: Input validation loop
Keep asking until a positive number
n = int(input("Enter a positive number: "))
while n <= 0:
    print("Invalid. Try again.")
    n = int(input("Enter a positive number: "))
print("Accepted:", n)
βœ… Pattern 5: Accumulator loop (sum/average)
Sum 1..n using while
n = 10
total = 0
i = 1
while i <= n:
    total += i
    i += 1
print("Sum =", total)

4) break and continue

break (exit the loop immediately)

Stop early when found
i = 1
while i <= 10:
    if i == 6:
        break
    print(i, end=" ")
    i += 1
# Output: 1 2 3 4 5

continue (skip to next iteration)

Skip odd numbers
i = 0
while i < 10:
    i += 1
    if i % 2 == 1:
        continue
    print(i, end=" ")
# Output: 2 4 6 8 10

5) Nested while loops

A nested loop means a loop inside another loop. Common uses: tables, grids, patterns.

Multiplication table (1..5) using while
i = 1
while i <= 5:
    j = 1
    while j <= 5:
        print(i * j, end="\t")
        j += 1
    print()
    i += 1

6) while ... else (rare but useful)

Python supports while ... else. The else block runs only if the loop ends normally (condition becomes False). If you exit using break, the else does not run.

Search example with while-else
nums = [3, 7, 11, 20]
target = 9
i = 0

while i < len(nums):
    if nums[i] == target:
        print("Found at index", i)
        break
    i += 1
else:
    print("Not found")

7) Try it yourself β€” Pyodide Python Editor

Run Python directly in your browser using Pyodide (Python compiled to WebAssembly).

Python code
Loading Pyodide…

Tip: Use print(). In this page, input() is redirected to a simple browser prompt.

Output stdout / errors

About input() in browser

When you call input(), you will see a popup prompt. Cancel returns an empty string.

8) Practice assignments (while loop)

  1. Print numbers from 1 to 100 using while.
  2. Print all even numbers from 1 to 50 using while.
  3. Find the factorial of a number using while.
  4. Print the Fibonacci sequence up to n terms using while.
  5. Reverse a number (e.g., 1234 β†’ 4321) using while.
  6. Keep taking input until the user enters 0, then print the sum of all inputs.