Learn Python Programming  /  Control Flow  /  While Loop

While Loop

A while loop repeats a block of code for as long as a condition stays True. Use it when you do not know in advance how many times you need to loop.

Basic while Loop

R Code
count = 1

while count <= 5:
    print(count)
    count += 1   # same as count = count + 1
Output
1
2
3
4
5
⚠ Common Mistake
Forgetting to update the loop variable inside the loop body creates an infinite loop, since the condition never becomes False. Always double-check that something inside the loop moves it closer to stopping.

Using break to Exit Early

R Code
n = 1
while True:
    if n > 3:
        break
    print(n)
    n += 1
Output
1
2
3

Using continue to Skip an Iteration

R Code
n = 0
while n < 5:
    n += 1
    if n % 2 == 0:
        continue   # skip even numbers
    print(n)
Output
1
3
5

Advanced: while Loop for Iterative Convergence

🚀 Advanced Example
while loops are the natural choice for iterative numerical methods that stop once a result is precise enough, rather than after a fixed number of steps.
R Code
x = 10
guess = 1
tolerance = 1e-6

while abs(guess**2 - x) > tolerance:
    guess = (guess + x / guess) / 2

print(round(guess, 6))
Output
3.162278

Key Points

  • while condition: checks the condition BEFORE each pass, so the loop may run zero times.
  • Something inside the loop body must eventually make the condition False, or you get an infinite loop.
  • break exits the loop immediately; continue skips straight to the next iteration.