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.
while loop?
A while loop repeats a block of code
as long as a condition is True. The condition is
checked before each iteration.
count = 1
while count <= 5:
print(count)
count += 1
Set a starting value (like a counter).
The loop runs while this stays True.
Change variables so the loop can eventually stop.
i = 0 # A) initialization
while i < 3: # B) condition
print("i =", i)
i += 1 # C) update
If you forget to change the loop variable, the condition may never become False. That causes an infinite loop.
i = 0
while i < 5:
print(i)
# i += 1 β missing update -> infinite loop
i = 1
while i <= 10:
print(i, end=" ")
i += 1
i = 10
while i >= 1:
print(i, end=" ")
i -= 1
while True:
s = input("Type something (q to quit): ")
if s.lower() == "q":
break
print("You typed:", s)
n = int(input("Enter a positive number: "))
while n <= 0:
print("Invalid. Try again.")
n = int(input("Enter a positive number: "))
print("Accepted:", n)
n = 10
total = 0
i = 1
while i <= n:
total += i
i += 1
print("Sum =", total)
break and continuebreak (exit the loop immediately)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)i = 0
while i < 10:
i += 1
if i % 2 == 1:
continue
print(i, end=" ")
# Output: 2 4 6 8 10
A nested loop means a loop inside another loop. Common uses: tables, grids, patterns.
i = 1
while i <= 5:
j = 1
while j <= 5:
print(i * j, end="\t")
j += 1
print()
i += 1
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.
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")
Run Python directly in your browser using Pyodide (Python compiled to WebAssembly).
Tip: Use print(). In this page,
input() is redirected to a simple browser prompt.
input() in browser
When you call input(), you will see a popup prompt.
Cancel returns an empty string.
while.while.while.n terms using
while.
while.0, then print the
sum of all inputs.