How to Create While Loop in Python

To create a while loop in Python:

while condition is true:
perform an action

4 Examples of While Loop in Python

Example 1: Create a Countdown

To start, 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 results 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).

Here, the condition is:

 10 > increment > 0

Putting everything together:

increment = 1

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

And the results:

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

Now use a ‘break‘ statement to get the same results 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

Leave a Comment