Page 120 - TP_Play_V2.1_class8
P. 120

THE WHILE STATEMENT

                  The while statement executes a set of statements repeatedly, until the logical expression evaluates
                  to true. When the condition becomes false, the control comes out of the loop. The syntax of
                  while statement is given below:
                  while (test expression):

                         Statements
                         Increment/Decrement

                   Program 5: To demonstrate the use of a while loop.


                      Program5.py
                   File  Edit  Format    Run   Options   Window    Help

                   #Program to demonstrate the use of a while loop

                   # Initialize a variable                                                 Output
                   count = 1
                                                                                        Count is: 1
                   #test expression
                   while count < 5:                                                     Count is: 2
                       print("Count is:", count)                                        Count is: 3
                       count += 1                                                       Count is: 4




                   Clickipedia


                    Any non-zero value in the while loop indicates always a true condition, whereas zero indicates
                    always a false condition.


                  The while Loop using else Statement

                  Python enables the use of else statement with the while loop. The else block is executed when
                  the condition given in the while statement becomes false.

                   Program 6: To demonstrate the use of while loop with else statement.


                      Program6.py

                   File  Edit  Format   Run    Options   Window    Help

                   #Program to demonstrate the use of while loop with else statement
                   i = 1
                   while (i <= 5):
                       print(i)
                       i += 1
                   else:
                       print('The While loop ends here!')





                  118       Play (Ver. 2.1)-VIII
   115   116   117   118   119   120   121   122   123   124   125