Page 139 - Touchpad_Plus_V3.2_Class 8
P. 139

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
                                                                                       Count is: 2
                  while count < 5:
                      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!')






                                                                                               Loops in Python       137
   134   135   136   137   138   139   140   141   142   143   144