Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 116 - 2620_Birla Open Mind C-8
P. 116

    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
                      count = 1
                                                                                             Output
                      #test expression
                      while count < 5:                                                    Count is: 1
                          print("Count is:", count)                                       Count is: 2
                          count += 1                                                      Count is: 3
                      #increment/decrement                                                Count is: 4

                                                                      Hintbot

                           Any non-zero value in the while loop indicates always a true condition, whereas zero indicates
                                                            always-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!')

                  On running the above program, we get the following output:

                       Output

                    1
                    2
                    3
                    4
                    5
                    The While loop ends here!

                      114  Premium Edition-VIII

| 111 112 113 114 115 116 117 118 119 120 121 |