Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 117 - 2615_KEC
P. 117

    statements until the condition becomes false. If the initial condition is false, then the control will
                     not enter the loop block. The syntax of while loop is as follows:
                     while(condition):

                         statement(s)
                         increment/decrement
                     In Scratch, the repeat until block works similarly to a while
                                                                                         when    clicked
                     loop by repeatedly performing an action as long as a condition
                     is true. For example, imagine you have a sprite and you want        repeat until  touching  edge  ?
                     it  to  keep  moving forward  until it  touches  the edge  of the
                                                                                          move  10  steps
                     stage. You use a repeat loop to tell the sprite to move as long
                     as the condition not touching edge is true. Once the sprite
                     touches the edge, the loop stops and the sprite stops moving.

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

                         Program10.py
                      File  Edit  Format   Run    Options   Window    Help
                      #Program to demonstrate the use of a while loop

                      # Initialize a variable
                      count = 1
                      #test expression
                      while count < 5:
                          print("Count is:", count)
                      #increment/decrement
                          count += 1

                         Output

                      Count is: 1
                      Count is: 2
                      Count is: 3
                      Count is: 4

                     Program 11: To print numbers from 1 to 5 using a while loop.

                         Program11.py                                              Output
                      File  Edit  Format  Run    Options  Window    Help        1
                                                                                2
                      count = 1
                                                                                3
                      while count <= 5:
                                                                                4
                          print(count)
                                                                                5
                          count = count + 1

                                                                                            Control Structures in Python  115

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