Page 122 -
P. 122

functions


           Return data with the return command


           If you use the return() command within a function, you can send a
           data value back to the calling code.





                    import urllib.request

                    def get_price():
                           page = urllib.request.urlopen("http://www.beans-r-us.biz/prices.html")
                           text = page.read().decode("utf8")           Remove the call to
                           where = text.find('>$')
                           start_of_price = where + 2                  “print()"...
                           end_of_price = start_of_price + 4
                           print(text[start_of_price:end_of_price])
                                                                            ... and replace it with a
                           return(text[start_of_price:end_of_price])        call to “return()" instead.













                                                       Call the “get_price()"
                                                       function.




                        ...
                 price = get_price()                                                           Run the code
                                                                                     get_price()  to determine
                        ...
                                                                                              the current
                                                                                              price.

                                            5.51                            Return the price to
                                                                            the caller.


                                            The value assigned to “price"
                                            is 5.51. The assignment
                                            happens after the code in
                                            the function executes.
                                                                                        you are here 4    87
   117   118   119   120   121   122   123   124   125   126   127