WHILE LOOP IN PYTHON

Photo of author

By Jackson Taylor

Home » Electronics Topics » Python & OpenCv » WHILE LOOP IN PYTHON

A while loop in Python repeats a block of code for as long as a condition stays true. It is the right tool when you do not know in advance how many times something needs to run, such as waiting for user input, reading data until it runs out, or counting until a limit is reached.

This guide covers the syntax, a simple working example, and the keywords that control a loop (break, continue and else). It also covers the most common mistake, the infinite loop. If you are new to the language, getting started with Python is a good place to begin first.

How a while loop works

Python checks the condition before every pass through the loop. If the condition is true, the indented block runs. When the block finishes, Python goes back and checks the condition again. Once the condition is false, the loop ends and the program continues with the next line after it.

The basic syntax looks like this:

Hardware Hack

Stop Buying New Batteries for Your Tech

Electronics are expensive, but their power sources don't have to be. Discover the simple engineering trick to recondition dead batteries and bring your gadgets back to 100% capacity.

Watch the Free Video
while condition:
    # code to repeat

Three things matter here:

  • The line with while must end with a colon.
  • The code inside the loop must be indented, usually by four spaces.
  • Something inside the loop must eventually make the condition false, or the loop will never stop.

A basic while loop example

The program below prints the word "hai" six times. It starts with n set to 6 and reduces it by one on each pass, so the loop stops when n reaches 0.

Program

n=6
while n>0:
    n=n-1
    print('hai')

Output

hai
hai
hai
hai
hai
hai

On the first pass n is 6, which is greater than 0, so the block runs and n becomes 5. This repeats until n becomes 0. At that point the condition n>0 is false and the loop ends, after exactly six prints.

Note that older Python 2 code wrote this as print 'hai'. In Python 3, print is a function and needs parentheses, as shown above.

See also
IF - STATEMENT IN PYTHON

You can find more examples on a related page.

Using a counter and a running total

Most while loops follow the same pattern: set a starting value, test it, and change it inside the loop. Here is a loop that adds the numbers from 1 to 10:

total = 0
i = 1
while i <= 10:
    total = total + i
    i = i + 1
print(total)

The output is 55. The variable i is the counter, and total collects the result. Writing i += 1 is a shorter way to do the same update.

Controlling a loop with break, continue and else

break: stop the loop early

The break statement exits the loop immediately, even if the condition is still true. It is often used with while True to create a loop that runs until something specific happens.

while True:
    answer = input("Type quit to exit: ")
    if answer == "quit":
        break
    print("You typed:", answer)

The loop keeps asking for input and only stops when the user types quit. The test inside the loop is a normal if statement in Python.

continue: skip to the next pass

The continue statement skips the rest of the current pass and goes straight back to checking the condition. This loop prints only the odd numbers up to 9:

Sustainable Tech

Keep Toxic E-Waste Out of Landfills

Don't throw away your failing laptop, phone, or car batteries. Learn how to recondition them at home in just a few hours. It's better for the planet—and your wallet.

Learn How It Works
n = 0
while n < 9:
    n += 1
    if n % 2 == 0:
        continue
    print(n)

The output is 1, 3, 5, 7 and 9, each on its own line. Whenever n is even, continue skips the print call. The counter is updated before the continue, which matters: if you put the update after it, the loop could get stuck.

else: run code when the loop ends normally

A while loop can have an else block. It runs once when the condition becomes false, but it is skipped if the loop was ended by break.

n = 3
while n > 0:
    print(n)
    n -= 1
else:
    print("Loop finished")

This prints 3, 2, 1 and then "Loop finished". The else clause is useful for search-style loops, where you want to do something only if nothing triggered a break.

Avoiding infinite loops

An infinite loop happens when the condition never becomes false. The most common cause is forgetting to update the variable the condition depends on:

n = 6
while n > 0:
    print("hai")

Here n never changes, so "hai" prints forever. If this happens while you are running a script in a terminal, press Ctrl+C to interrupt it.

See also
ADVANCED TRAFFIC CONTROL AND RESCUE SYSTEM

A few habits help prevent the problem:

  • Before you run the loop, check that something inside it changes the condition.
  • Use <= and < carefully so the loop stops where you expect.
  • When you use while True, make sure there is a reachable break.
  • Test with small values first, such as a counter that stops at 3.

While loop vs for loop

Both loops repeat code, but they suit different jobs. Use a for loop when you already have a collection or a known number of repeats, for example going through a list or running something 10 times. Use a while loop when the number of repeats depends on a condition that can change as the program runs. If you want to compare them, see our guide to the for loop in Python.

While loops are common in programs that keep checking something, such as reading a sensor repeatedly. A practical example is displaying temperature in Python from an Arduino, where a loop keeps reading new values.

Frequently asked questions

What is a while loop in Python?

It is a loop that keeps running its indented block as long as a given condition is true. When the condition becomes false, Python moves on to the next statement after the loop.

How do I stop a while loop?

Make the condition false, for example by changing a counter, or use break to leave the loop immediately. If a loop is stuck, press Ctrl+C in the terminal.

Can a while loop run zero times?

Yes. The condition is checked before the first pass, so if it is false from the start, the block never runs.

Does Python have a do-while loop?

No. Python has no built-in do-while statement. The usual workaround is a while True loop with a break placed where you want to test the exit condition.

Revive Your Dead Electronics

Got a drawer full of dead gadgets or a failing car battery? Instead of paying a premium for replacements, use this simple trick to easily recondition them right from home.

See How It Works