Page 56 -
P. 56

starting to code


           Python uses indents to connect paths


           The code inside the if and else statements is indented. This isn’t just
           to make the code pretty. In Python, indents matter. Let’s consider a
           different piece of example code: something that will decide if you can
           drive downtown. Python uses indents to connect a sequence of commands
           together to form paths.




                           The INDENTs tell Python that
                           the commands are in the same path
         This is the    if fuel > 3:
         TRUE path.       print("It's OK")

                          print("You can drive downtown.")
                      else:
        This is the        print("Sorry")
        FALSE path.       print("You don't have enough fuel")
                      print("What's next?")
                                 This command is not on the
                                 FALSE path because it is not
                                  indented. So it will always run.




           So how do you connect branches together? You simply indent the
           second branch in by one more level.
                                                                                         Indents matter
             The first if branch                                                      in Python.

                         if fuel > 3:                                                 Be careful how
                                                                                      you indent code in
                             print("It's OK")
                             print("You can drive downtown.")                         Python; if you don’t
                         else:                                             indent your code correctly, your
      This second if branch                                                code might do something wildly
                             if money > 10:
       is connected to the                                                 different from what you expect.
                                 print("You should buy some gas.")
      “false" path of the        else:
      first if branch.           print("You better stay at home.")
                         print("What's next?")
                           Notice the extra
                           indentation.



          You should now have enough information to go fix the code, but
           before we do that, let’s take a look at how IDLE helps you indent
           code.

                                                                                        you are here 4    21
   51   52   53   54   55   56   57   58   59   60   61