Join my course at Udemy (Python Programming Bible-From beginner to advanced )

Blogger templates

Monday 18 May 2020

Python While Statement


Python While loop is a compound statement that allows block of statement inside the WHILE block. Block of statement inside While statement runs until the While condition is True. The control comes out of while loop when condition is False.

Following is the syntax for While Statement:

While Statement

Syntax

Following are the set of rules for writing While statement
  • When test1 condition is True  then statement1 and statement2 will be executed.
  • When test1 condition is False then statement1 and statement2 will not be executed.
  • Else statement with While loop is optional.
  • If Else statement is defined with While loop then then it will be always be executed except for one scenario. 
  • If the control comes out of While loop because of break inside While loop then Else statement will not be executed.

Example1 : While + Else statement

a=0; b=5
while a < b:
    print ("A, B ",a,b)
    a = a+1
else:
    print ('Out of while LOOP’)



A, B  0 5
A, B  1 5
A, B  2 5
A, B  3 5
A, B  4 5
Out of while LOOP

In the above code, while statement will return TRUE as long as the value of a is less than b.  Note that the  value is incremented inside the loop for every iteration.  When the value of a is greater then  then the control comes out of while loop. After the control comes out of while loop then else block code is executed and "Out of while LOOP" is printed.

Example2 : While + Break + Else statement

a=0; b=5
while True:
    print ("A, B ",a,b)
    a = a + 1
    if a > 4:
        break;
else:
    print ('Out of while LOOP’)


A, B  0 5
A, B  1 5
A, B  2 5
A, B  3 5
A, B  4 5 

Above code is similar to Example1 with slight change in while loop by adding break statement. The only difference between Example1 and Example2 is that in Example2, control comes out of while loop because because of break statement. And because of this Else statement will not be executed and that's why "Out of while LOOP"  will not be printed in this case.

Summary

While statement is comparatively easier loop in Python and it's functionality is similar to any other programming language like C, C++ and JAVA. Similar to While, python provides For loop that we will cover in our next blog post.
Share:

0 comments:

Post a Comment

Feature Top (Full Width)

Pageviews

Search This Blog