Need to create While Loop in Python?
If so, I’ll show how to create this loop using 4 simple examples.
To start, here is the While Loop structure that you may apply in Python:
while condition is true: perform an action
In the next section, we’ll see how to use this structure.
Create While Loop in Python
Let’s now review 4 examples that will help us understated how to create While Loop in Python.
Example-1: Create a Countdown
In the first example, we’ll 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, our 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 result as expected:
Example-2: Use a Break
Sometimes you can use a break.
I’m not talking about a break from life, but using the ‘break’ statement to end the loop when a specific condition is met.
We can achieve the same outcome as in example 1 by including a break as follows:
countdown = 10 while countdown > 0: print ('CountDown = ', countdown) countdown = countdown - 1 if countdown == 3: break
And when you run that code, you’ll indeed get the same result as in our first example:
Example-3: Counting Up
We saw how to count down, but how about counting up?
In this example, we will start counting from 1, and then stop at 9 (each time increasing the value of the count by 1).
And so, in this case, our condition will be:
10 > increment > 0
Putting everything together, our Python code would look like this:
increment = 1 while 10 > increment > 0: print ('Increment = ', increment) increment = increment + 1
And the result:
Example-4: Counting Up with a Break
We were on a break!
Let’s now see how we can use a ‘break’ to get the same result as example 3:
increment = 1 while increment > 0: print ('Increment = ', increment) increment = increment + 1 if increment == 10: break
Indeed we got the same results as in the third example: