Python While Loops

Learn how to use while loops in Python to repeat code execution based on conditions.

Python Loops

Python has two primitive loop commands:

  • while loops
  • for loops

The while Loop

With the while loop we can execute a set of statements as long as a condition is true.

Example - Print i as long as i is less than 6:

i = 1
while i < 6:
    print(i)
    i += 1

Note: remember to increment i, or else the loop will continue forever.

The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, which we set to 1.

The break Statement

With the break statement we can stop the loop even if the while condition is true:

Example - Exit the loop when i is 3:

i = 1
while i < 6:
    print(i)
    if i == 3:
        break
    i += 1

The continue Statement

With the continue statement we can stop the current iteration, and continue with the next:

Example - Continue to the next iteration if i is 3:

i = 0
while i < 6:
    i += 1
    if i == 3:
        continue
    print(i)

The else Statement

With the else statement we can run a block of code once when the condition no longer is true:

Example - Print a message once the condition is false:

i = 1
while i < 6:
    print(i)
    i += 1
else:
    print("i is no longer less than 6")

Practical Examples

Countdown Timer

countdown = 5
while countdown > 0:
    print(f"Countdown: {countdown}")
    countdown -= 1
print("Blast off!")

User Input Validation

password = ""
while password != "secret":
    password = input("Enter password: ")
    if password != "secret":
        print("Incorrect password, try again.")
print("Access granted!")

Sum of Numbers

total = 0
number = 1
while number <= 10:
    total += number
    number += 1
print(f"Sum of numbers 1 to 10: {total}")

Finding Factors

num = 12
factor = 1
factors = []

while factor <= num:
    if num % factor == 0:
        factors.append(factor)
    factor += 1

print(f"Factors of {num}: {factors}")

Infinite Loops

Be careful with while loops! If the condition never becomes false, the loop will run forever:

Example - This will run forever:

i = 1
while i < 6:
    print(i)
    # i is never incremented, so it will always be 1

To avoid infinite loops:

  • Always ensure the loop variable is modified inside the loop
  • Make sure the condition can eventually become false
  • Use a counter or maximum iterations as a safety measure

Example - Safe loop with maximum iterations:

i = 1
max_iterations = 100
iterations = 0

while i < 6 and iterations < max_iterations:
    print(i)
    i += 1
    iterations += 1

if iterations >= max_iterations:
    print("Loop stopped due to maximum iterations")

Nested While Loops

You can have while loops inside while loops:

Example - Multiplication table:

i = 1
while i <= 3:
    j = 1
    while j <= 3:
        print(f"{i} x {j} = {i * j}")
        j += 1
    print("---")
    i += 1

While Loop vs For Loop

When to use while loops vs for loops:

Use While Loop When:

  • You don't know how many iterations you need
  • The loop depends on a condition that may change unpredictably
  • You need to loop until user input meets criteria
  • You're waiting for an external condition

Use For Loop When:

  • You know the number of iterations in advance
  • You're iterating over a collection (list, string, etc.)
  • You need a counter variable
  • You're working with ranges of numbers

break, continue, and else

n = 0
while n < 10:
    n += 1
    if n == 3:
        continue     # skip the rest of this iteration
    if n == 6:
        break        # exit the loop entirely
    print(n)         # prints 1 2 4 5

# a while-else runs only if the loop finished WITHOUT break
x = 0
while x < 3:
    x += 1
else:
    print("done")    # runs

Avoid Infinite Loops

Every while needs a condition that eventually becomes false. Forgetting to update the loop variable hangs your program.

# BUG: n never changes -> runs forever
# n = 0
# while n < 5:
#     print(n)

# FIX: update the variable
n = 0
while n < 5:
    print(n)
    n += 1

If a program hangs, press Ctrl+C to stop it, then check that your loop variable is being updated toward the exit condition.

Try It Yourself

Exercise 1: Print the numbers 5 down to 1 using a while loop.

Show solution
n = 5
while n >= 1:
    print(n)
    n -= 1

Exercise 2: Keep doubling 1 until it exceeds 100, printing each value.

Show solution
x = 1
while x <= 100:
    print(x)
    x *= 2       # 1 2 4 8 16 32 64

Key Takeaways

  • while repeats while a condition is true — use it when the count is unknown.
  • break exits, continue skips to the next iteration.
  • Always move toward the exit condition to avoid infinite loops.

📘 Real-World Deep Dive

<code>while</code> is the right tool when the number of iterations is unknown up front — polling for state, retrying a flaky I/O call, or stepping toward a numeric goal.

Real-Life Scenario

Polling an HTTP endpoint with exponential backoff until it returns 2xx or you give up.

Real-Life Example

import random, time

def flaky_request(simulate):
    if random.random() < simulate["fail_rate"]:
        return random.choice([500, 503, 504])
    return 200

def fetch_with_backoff(simulate, *, max_tries=6):
    delay = 0.5
    for try_ in range(1, max_tries + 1):
        code = flaky_request(simulate)
        if 200 <= code < 300:
            return code, try_
        print(f"try {try_}: got {code}, sleeping {delay:.1f}s")
        time.sleep(delay)
        delay *= 2                                 # exponential backoff
    return code, max_tries

sim = {"fail_rate": 0.6}
final_code, tries = fetch_with_backoff(sim)
print(f"final code: {final_code}, attempts: {tries}")

Expected Output

try 1: got 503, sleeping 0.5s
try 2: got 500, sleeping 1.0s
try 3: got 504, sleeping 2.0s
try 4: got 200, sleeping ...
final code: 200, attempts: 4

Common mistakes

  • Forget to update the loop variable and you'll spin forever — Python does not warn.
  • time.sleep is exact in tests but slow; inject a sleep function for unit tests.
  • Retry loops must always have a hard upper bound (max_tries) — otherwise an outage wedges the worker.

🚀 Performance & Best Practices

  • while x: is faster than while x is not None: when the existence is what you mean.
  • For exponential backoff, jitter avoids "thundering herd" — sleep delay * random.random().
  • When polling, use asyncio.sleep instead of time.sleep so other tasks can run.

🧪 Try It Yourself

  1. Add jitter to the backoff delay and re-run.
  2. Cap backoff at 30 s and re-run.
  3. Replace the loop body with tenacity or backoff library decorators.

FAQ: Python While Loops

Common questions about this page.

What is Python While Loops?

Python While Loops is a Python Tutorial lesson that explains python while loop in Python. Learn how to use while loops in Python to repeat code execution based on conditions. Copy the samples and run them in the Python editor. It is written for beginners who want a clear definition and working examples.

Should I run python while loop examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn python while loop in this Python Tutorial Python lesson (Python While Loops).

How do I use python while loop in Python?

To use python while loop in Python, follow the examples on this StudyGrid page. Copy a snippet, run it in the browser, then Download and run it locally for better learning. Change the values and compare the output.

What is the syntax of python while loop?

This Python While Loops tutorial shows python while loop syntax with short Python examples. Use the code blocks in this lesson for the exact statements, then try them in your editor.

Python While Loops example for beginners

Yes. This page includes a beginner python while loop example you can copy and run. It is designed for searches such as "python while loop for beginners", "python while loop example", and "how to use python while loop".

What are common mistakes with python while loop?

Common python while loop mistakes include wrong syntax, mixing types, and skipping practice. Work through this Python Tutorial chapter in order, run every example, and check the output before moving on.

Why should I learn python while loop?

Python While Loops is used in real Python work. Learning python while loop helps you write clearer programs and continue the Python Tutorial tutorial on StudyGrid.

Is Python While Loops free to learn online?

Yes. You can learn python while loop free on StudyGrid (studygrid.in). This chapter is part of the Python Tutorial path and includes examples, syntax, and next-step links.