Skip to content
Home » Blog » Python While Loops now in a Simplified Version

Python While Loops now in a Simplified Version

In this article, we will be discussing Python While Loops and how to use them. First, we start off by creating a While loop. Then we move on to the keywords that are used in while loops and use else in while loops. Then we end the post by looking at some basic examples.

If you are new to programming, you must be having some issues understanding the while loops than the for loops, and that’s totally fine. It’s just that you need to learn it differently, and guess what? We will make sure you master the basics about while loops.

Python While Loops

Now that you’re ready, lets jump right in.

Python While Loops

As long as the statement is True, the loop gets executed, and once False it breaks

We can make a while loop by typing in the following code

i = 5
while i>0:
    print(i)
    i -=1

Here until i’s value is greater than 0, i’s value gets printed, once it reaches 0, the loop breaks.

The output of the program will be…

5
4
3
2
1

Unlike the For Loop, where we can use range, While loop requires a variable

Break in Python While Loops

Using break, we can break the while loop. This is usually used with conditions where we say, in this condition we exit the loop.

The Break keyword will break the loop no matter what the condition is, True or False

Let’s use it in a code

i = 10
while True:
    print(i)
    i += 5

    if i >20: break

    i -= 3

Here once i’s value exceeds 20, the loop breaks

10
12
14
16

Continue in Python While Loops

With the continue statement we can stop the current iteration, and continue with the next, for instance, if we want to output all the numbers from 1 to 10 except for, let’s say, 5, we would have to run the following code.

i = 0

while i<=10:
    i+=1
    if i == 5:
        continue
    print(i)

Here when i takes the value of 5, the current iteration stops, but unlike the break statement, it continues with the next iteration, that is, with 6.

1
2
3
4
6
7
8
9
10

Else in Python While Loop

When we use the else statement along with the while loop, the code under the else will be executed, once the while condition turns False.

For instance,

i = 0

while i<5:
    print(i)
    i+=1

else:
    print(f"The value of i is {i}")

And we get…

0
1
2
3
4
The value of i is 5

To Sum Up

In today’s post, we’ve discussed While Loops in Python, looked at its syntax and how to use them. We have also taken a look into 2 keywords used in the while loop, break and continue, and saw how to use the else statement in loops. If you are on your way to becoming a Pythonista, you might find our site really helpful. Hit this link for more python related posts
Check it out, it’s Simply the Best Code.

Leave a Reply

Your email address will not be published. Required fields are marked *