Page 64 -
P. 64

starting to code


           Python’s while loop


           Programming languages have lots of different ways of creating loops,
           but one of the simplest ways in Python is to use a while loop. Here’s
           an example:
       We want to make                                             The loop body is the
        sure the loop runs
        the first time.                  The loop condition        the “while” line.
                                                                   indented code following
                   answer = "no"
                   while answer == "no":
                       answer = input("Are we there? ")
                                                                         The loop body is just one line of code
                   print("We're there!")
                                                                         in this example, but the loop body can
                                                                         include branches and other loops.
           This is what the loop looks like when you write it as a Python while loop.  be many lines of code. It might even
           The code keeps asking the question “Are we there?” until the user types
           something other than no. This is what it looks like when it runs:



















                                             As soon as we type something
                                             other than “no", the loop
                                             body ends.






           Did you notice that you had to set the value of the answer variable to
           something sensible before you started the loop? This is important, because
           if the answer variable doesn’t already have the value no, the loop
           condition would have been false and the code in the loop body would
           never have run at all.
           Bear that in mind. It might be useful in this next exercise...


                                                                                        you are here 4    29
   59   60   61   62   63   64   65   66   67   68   69