while

A loop that repeats a block of code while a condition is true.

On this page

Example

#
Python
fuel = 3

while fuel > 0:
    print(f"Lesson completed, fuel left: {fuel - 1}")
    fuel -= 1

print("Out of fuel, come back tomorrow!")
Resultsaved result, you can check it
Lesson completed, fuel left: 2
Lesson completed, fuel left: 1
Lesson completed, fuel left: 0
Out of fuel, come back tomorrow!

Definition and usage

#

A while loop checks the condition before each pass and runs the block for as long as the condition is true. It is useful when you do not know in advance how many times you need to repeat an action.

Something inside the block must eventually make the condition false, for example decreasing a counter. Otherwise the loop will run forever.

The while True: pattern with a break inside is popular for loops that should end once a condition checked partway through the block is met, for example when asking the user for a valid answer.

Syntax

#
Syntax
while condition:
    ...

More examples

#
A loop with a break in the middle
Python
level = 1
exp = 0
while True:
    exp += 40
    if exp >= 100:
        level += 1
        break
print(f"Level {level}, EXP {exp}")
Resultsaved result, you can check it
Level 2, EXP 120

Good practices

#
  • When you know the number of repetitions, or you are looping over a collection, choose for. It is more readable and safer.
  • In while True, always make sure some path leads to a break.

Related entries

#

Spotted a mistake or missing an example? Write to us.