Python – while loop

After reading this Python while loop topic, you will know the while loop flowchart, theory, and examples, and you will understand how to use while loop with else.

Python while loop executes statements as long as expression evaluates true condition and when the expression evaluates false condition, the while loop gets terminate.

General Form (Syntax):

The syntax of while loop is given below,

while expression:
  statement(s)

As the while loop starts, first expression gets evaluated and when the evaluated condition is true, the statement(s) under while will execute.

while loop flowchart:

The flow chart of while loop is given below,

Example 

Program (1): To print a message “how are you” five times using while loop.

i=1
while i<=5:
  print("How are you")
  i+=1

Output (1) 

How are you
How are you
How are you
How are you
How are you

Here, variable i is initialized (assigned) to value 1 and after that, this value is evaluated in expression i<=5. The expression will result true (1 is less than or equal to 5) and hence a message “How are you” will be printed for the first time. Now the control transferred to statement i+=1 which increment variable i value by 1 and transfer the control again to expression i<=5 for further evaluation and this process run for five times. When variable i value equals to 6 the while loop gets terminated and the message “How are you” will get printed for five times.

while loop with else

When a while loop finished due to its condition being false, its associated else block executes.

Program (1): To print a message “how are you” five times using while/else.

i=1
while i<=5:
  print("How are you")
  i+=1
else:
    print("Have a nice day")

Output (3)

How are you
How are you
How are you
How are you
How are you
Have a nice day

Explanation

When a while loop finished and print the message “How are you” for five times, its associated else block executes and print the message “How are you” at the end.

Published by

Electrical Workbook

We provide tutoring in Electrical Engineering.

Leave a Reply

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