Page 119 -
P. 119

order matters


                              Code Magnets Solution

                              Before you amend the existing coffee bean program code, let’s see
                              if you can create a function to display the current bean price.  You
                              were to rearrange the magnets in the correct order to create the
                              function:


             You still need to import libraries
             before using them in a function.


                         import urllib.request
                                                         You need a colon after
                                                         the function name.
           The function
           definition     def     get_price()      :
           starts here.

                              page = urllib.request.urlopen("http://www.beans-r-us.biz/prices.html")
        The body of the function  text = page.read().decode("utf8")
        needs to be indented.  where = text.find('>$')
                              start_of_price = where + 2
                              end_of_price = start_of_price + 4
        The function needs
        to be declared         print(    text[start_of_price:end_of_price]          )
        before it's called.
                                                       The function
                           get_price()                 definition ends here.




                  This line isn't indented,
                  because it is part of
                  the main program.





           Always get things in the right order


           When it comes to functions, the order in which you do things
           really matters. The get_price() function needs to be   The order in which
           defined before you call it. And because the function relies upon   you do things is
           some code in the urllib.request library, you need to make   really important.
           sure that the import line appears before the function, too.
           Let’s see if your new code works.


           84    Chapter 3
   114   115   116   117   118   119   120   121   122   123   124