Python while loop

The while statement in Python is one of most general ways to perform iteration.
A while statement will execute a single statement or group of statements repeatedly as long as the condition is true.
It is a loop because it will iterate over statements until condition become false.

The general format of a while loop is:

Let’s look at a few simple while loops in action.

a = 0 while a < 5: print('a =',a) print('As a is still less than 5, adding 1 to a') a+=1

a = 0
As a is still less than 5, adding 1 to a
a = 1
As a is still less than 5, adding 1 to a
a = 2
As a is still less than 5, adding 1 to a
a = 3
As a is still less than 5, adding 1 to a
a = 4
As a is still less than 5, adding 1 to a

While loop continued as soon as true condition was met, once a became 5, a==5 became false and loop stopped.

a = 0 while a < 5: print('a =',a) print('As a is still less than 5, adding 1 to a') a+=1 else: print('a is greater than 5 now')
a = 0
As a is still less than 5, adding 1 to a
a = 1
As a is still less than 5, adding 1 to a
a = 2
As a is still less than 5, adding 1 to a
a = 3
As a is still less than 5, adding 1 to a
a = 4
As a is still less than 5, adding 1 to a
a is greater than 5 now

break, continue, pass

We can use break, continue, and pass statements in our loops to add additional functionality for various cases. The three statements are defined by:

break: Breaks current iterating closest enclosing loop.
continue: Goes to the top of the closest enclosing loop.
pass: Does nothing at all.

Thinking about break and continue statements, the general format of the while loop looks like this:

break and continue statements can appear anywhere inside the loop’s body,but we will usually put them with an if statement to perform an action based on some conditions.

Let’s take some example

Break is used when you want to break the loop based on some conditions.

Output:

a = 1
As a is still less than 5, adding 1 to a
a = 2
As a is still less than 5, adding 1 to a

Please note that else statement is not getting executed in this case.
As you can see when a==3 then loop got terminated.
Continue statement is used to skip iterate and continue the loop.
For example:
If a==3 then you would like to continue the loop and won’t print state ment.

a = 1
As a is still less than 5, adding 1 to a
a = 2
As a is still less than 5, adding 1 to a
a = 4
As a is still less than 5, adding 1 to a
a = 5
As a is still less than 5, adding 1 to a
a is greater than 5 now

That’s all about while loop in python.

Leave a Reply

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