Page 108 - modular4.0
P. 108

Chapter Profile
                         THE WHILE STATEMENT


                  The while statement executes a set of statements repeatedly, as long as 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!')





                106  Modular (Ver. 4.0)-VIII
   103   104   105   106   107   108   109   110   111   112   113