How to Create While Loop in Python (with 4 Examples)

Need to create a while loop in Python?

If so, you’ll see how to create this type of loop using 4 simple examples.

To start, here is the structure of a while loop in Python:

while condition is true:
    perform an action

In the next section, you’ll see how to apply this structure in practice.

Create While Loop in Python – 4 Examples

Example-1: Create a Countdown

In the first example, you’ll see how to create a countdown, where:

  • The countdown will start at 10
  • The value of the countdown will decrease by intervals of 1
  • The countdown will stop at 4

Based on the above rules, the condition for the countdown is therefore:

 countdown > 3

And so long as this condition is true, the countdown will decrease by intervals of 1.

Here is the full Python code to perform the while loop for our example:

countdown = 10

while countdown > 3:
    print ('CountDown = ', countdown)
    countdown = countdown - 1

Once you run the code, you’ll get the following countdown:

CountDown = 10
CountDown =  9
CountDown =  8
CountDown =  7
CountDown =  6
CountDown =  5
CountDown =  4

Example-2: Use a Break

Sometimes you may want to use a ‘break’ statement to end the loop when a specific condition is met.

You can then achieve the same outcome as in example 1 by including a break statement as follows:

countdown = 10

while countdown > 0:
    print ('CountDown = ', countdown)
    countdown = countdown - 1
    if countdown == 3:
        break

And when you run the code, you’ll indeed get the same result as in the first example:

CountDown = 10
CountDown =  9
CountDown =  8
CountDown =  7
CountDown =  6
CountDown =  5
CountDown =  4

Example-3: Counting Up

You just saw how to count down, but what if you want to count up?

In this example, you’ll start counting from 1, and then stop at 9 (each time increasing the value of the count by 1).

And so, in this case, the condition will be:

 10 > increment > 0

Putting everything together, the Python code would look like this:

increment = 1

while 10 > increment > 0:
    print ('Increment = ', increment)
    increment = increment + 1

And the result:

Increment =  1
Increment =  2
Increment =  3
Increment =  4
Increment =  5
Increment =  6
Increment =  7
Increment =  8
Increment =  9

Example-4: Counting Up with a Break

Let’s now see how to use a ‘break’ statement to get the same result as in example 3:

increment = 1

while increment > 0:
    print ('Increment = ', increment)
    increment = increment + 1
    if increment == 10:
        break

Run the code and you’ll indeed get the same results as in the third example:

Increment =  1
Increment =  2
Increment =  3
Increment =  4
Increment =  5
Increment =  6
Increment =  7
Increment =  8
Increment =  9