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

Need to create while loop in Python?

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

To start, here is the structure of the 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:

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

Example-2: Use a Break

Sometimes you can use a break….

I’m not talking about a break from life, but using 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:

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

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:

While Loop in Python

Example-4: Counting Up with a Break

We were on 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:

While Loop in Python