🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEpython

python Documentation

LOADING ENGINE...

while Loop

AI & DATA SCIENCE // while-loop

The while loop repeats a block of code for as long as its condition remains truthy, checking the condition again before every iteration, including the first.

Syntax

while condition:
    # code runs repeatedly while condition is truthy

Deep Dive Course

Unlike a for loop, which iterates a predetermined number of times over a known iterable, a while loop keeps running as long as its condition stays true, making it the right tool when the number of iterations isn't known in advance — like waiting for user input, polling until a resource is ready, or processing a queue until it's empty. If the condition never becomes falsy and nothing inside the loop breaks out, it runs forever, producing an infinite loop.

1Understanding while Loop

Unlike a for loop, which iterates a predetermined number of times over a known iterable, a while loop keeps running as long as its condition stays true, making it the right tool when the number of iterations isn't known in advance — like waiting for user input, polling until a resource is ready, or processing a queue until it's empty. If the condition never becomes falsy and nothing inside the loop breaks out, it runs forever, producing an infinite loop.

💡

Deliberate infinite loops are a common, valid pattern — they're typically combined with a break statement inside the body once some internal condition is met, rather than expressing the exit condition in the while line itself.

editor.html
count = 0
while count < 3:
    print(count)
    count += 1
localhost:3000

2Practical Example

Here is a real-world application of while Loop showing how it is used in production Python code.

editor.html
import random
random.seed(1)
attempts = 0
while True:
    attempts += 1
    roll = random.randint(1, 6)
    if roll == 6:
        break
print(f"Got a 6 after {attempts} attempts")
localhost:3000

3Best Practices

Follow these guidelines when working with while Loop:

1. Make sure something inside the loop body actually changes the condition's truth value, to avoid an accidental infinite loop

2. Use a deliberate infinite loop with an internal break for loops whose exit condition is easier to express partway through the body than up front

3. Prefer a for loop over a range when the number of iterations is actually known ahead of time, since it more clearly signals that intent

⚠️

Tip: Deliberate infinite loops are a common, valid pattern — they're typically combined with a break statement inside the body once some internal condition is met, rather than expressing the exit condition in the while line itself.

editor.html
count = 0
while count < 3:
    print(count)
    count += 1
localhost:3000

Examples

Example 01Basic Usage
count = 0
while count < 3:
    print(count)
    count += 1
Example 02Advanced Example
import random
random.seed(1)
attempts = 0
while True:
    attempts += 1
    roll = random.randint(1, 6)
    if roll == 6:
        break
print(f"Got a 6 after {attempts} attempts")

Best Practices

  • Make sure something inside the loop body actually changes the condition's truth value, to avoid an accidental infinite loop
  • Use a deliberate infinite loop with an internal break for loops whose exit condition is easier to express partway through the body than up front
  • Prefer a for loop over a range when the number of iterations is actually known ahead of time, since it more clearly signals that intent

Interview Question

What's the key difference in when you'd reach for a while loop instead of a for loop?

Hint: Think about whether the number of iterations is known in advance.

A for loop is the right choice when you're iterating over a known, finite collection or a fixed count, since it directly expresses 'do this once per item'. A while loop is the right choice when the number of iterations depends on some condition that can only be evaluated at runtime and isn't known ahead of time — like waiting for a specific event, polling a resource, or repeating until user input satisfies some check.

Exercises

MediumPractice using while Loop in a real scenario.
View Solution
count = 0
while count < 3:
    print(count)
    count += 1

Frequently Asked Questions

What's the key difference in when you'd reach for a while loop instead of a for loop?

A for loop is the right choice when you're iterating over a known, finite collection or a fixed count, since it directly expresses 'do this once per item'. A while loop is the right choice when the number of iterations depends on some condition that can only be evaluated at runtime and isn't known ahead of time — like waiting for a specific event, polling a resource, or repeating until user input satisfies some check.

Related Functions

for-loopbreak-statementcontinue-statement