While Loop – Control Structure In Python – Free Python Tutorial

While loop is one of the most used loops in almost languages. An if statement is run once if its condition evaluates to True, and never if it evaluates to False.
Whereas a while statement is similar, except that it can be run more than once. The statements inside it are repeatedly executed, as long as the condition holds.
Once the condition evaluates to False, the execution comes out of while loop.

The process in which a code is executed repeatedly is called iteration.

The general prototype of while loop is :

while <condition>:
    Code to execute
    Code to execute
    Code to execute
    Code to execute
    ... contd...

As we know, we have to maintain proper whitespace indentation in Python. Observe the above prototype, we have maintained proper whitespace indentation inside the while loop.

Now let’s take a programming example of while loop :

i = 1
while(i<=5):
   print(i)
   i+=1
print("Finished!")

We have initialized i with the value 1. Now the while loop will run until i reaches the value 6. Inside the while loop, in every execution, the value of i is printed and then the value of i is increased by 1. When i will reach the value 6, the while loop will stop and execution comes out from while loop. Then the string “Finished” is printed.

So the output of the above program is :

>>>
1
2
3
4
5
Finished!

Let’s take another example :

i = 3
while(i>=0):
   print(i)
   i-=1
print("Finished")

We have initialized the variable i with the value 3. Now in the while loop, in every execution, the value of i is printed and after that, the value of i is decreased by 1. The while loop will execute until the value of i becomes less than zero.
After complete execution of while loop, the string “Finished” will be printed.

So as output we will get :

>>>3
2
1
0
Finished

Note : If we give such type of condition in the while loop which is always True, then the while loop will never stops running. Any this kind of loop which never stops running (i.e. a loop whose condition is always True) is known as an infinite loop.

As example :

while(5==5):
  print("In the loop")

The above code is an example of an infinite while loop. Carefully observe the condition in the while loop. As always 5 equals to 5, so the condition of the while loop is True always. When we will run the above code, it will start printing “In the loop” and will not stop unless and until we forcefully stop it.

You can stop the program’s execution by using the Ctrl+C shortcut or by closing the program. Basically, Ctrl+C is a type of interrupt known as KeyboardInterrupt.


Break Statement in Python

To end a while loop prematurely, the break statement can be used. We use the break statement to stop the execution of a loop for some certain conditions.
When the break statement encountered inside a loop,  it causes the loop to finish immediately.

Let’s take an example of break statement :

i = 0
while(1==1):
  print(i)
  i+=1
  if(i>=5):
    print("Breaking")
    break
print("Finished")

We have initialized the variable i with the value zero. Now we have created an infinite while loop here, as the condition we have given is 1==1, which is always True. Now, inside while loop, for every execution, we are printing the value of i and then we are increasing it by 1. Then we have declared an if block which will be executed if the value of i is greater than or equal to 5. When i will reach value 5 execution will enter into this if block, will print “Breaking”, and then due to break statement, the while loop will forcefully be closed. At last step it will print “Finished” and the program will close.

So, though by looking at the condition it seems that this is an infinite loop but it is not. The while loop will run until the value of i is less than 5.

So as output we will get :

>>>
0
1
2
3
4
Breaking
Finished

Note : We can use break statement only inside a loop. Using the break statement outside of a loop causes an error.


Continue Statement in Python

Another statement that can be used within loops is continue. Unlike breakcontinue jumps back to the top of the loop, rather than stopping it.

In simple words, continue statement skips the execution of a loop for a certain condition.

Let’s take an example of continue statement :

i = 0
while(True):
   i+=1
   if(i==2):
      print("Skipping 2")
      continue
   if(i==5):
      print("Breaking")
      break
   print(i)
print("Finished")

We have initialized the variable i with the value zero. Then we have given boolean value True as condition in the while loop, in order to create an infinite loop.

For every execution at first, the value of i will be increased by 1. Then the value is compared inside the first if block with the numeric value 2. If the value of i is equaled to 2 then execution of the first if block will be started. Otherwise, the value of i will be printed and execution of while loop will start with the new value of i.

When the value of i will become 2, execution will enter inside the first if block, at first “Skipping 2” will be printed and then due to the continue statement the current execution will be skipped and the while loop will start executing with the new value of i. Once the first if block is executed, that will never going to execute again as the value of i will never going to be equals to 2 again.

So for the next executions, every time the value of i will be compared with the numeric value 5 inside the second if block. If the value of i become equals to 5 then execution of the second if block will be started, otherwise, the value of i will be printed and execution of while loop will start with the new value of i.

When the value of i will become 5,  execution will enter inside the second if block, “Breaking” will be printed and due to the break statement the while loop will forcefully be closed. When the while loop will enter the second if block, after closing the while loop, “Finished” will be printed, and the program will close.

So, as output we will get :

>>>
1
Skipping 2
3
4
Breaking
Finished

Note : Basically, the continue statement stops the current iteration and continues with the next one. Like break statement, using the continue statement outside of a loop also causes an error.

Leave a Comment

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