Page 125 -
P. 125

buy it now




                                               Using the new get_price() function, you were asked to write a
                                               new version of the price-checking program that does this:

                                               1. Ask the user to indicate if the price is required immediately (Y/N).
                                               2. If the user chooses “Y” for “yes,” find the current price and display it
                Your code may look a little    on the screen.
                 different from this, but that's   3. Otherwise, check the price every 15 minutes until it falls below
                 OK. As long as it does the same   $4.74, then (and only then), display the price on screen.
                 thing, you're doing fine.
                                          import urllib.request

                                          import time


                                          def get_price():

                                              page = urllib.request.urlopen(“http://www.beans-r-us.biz/prices.html")

                                              text = page.read().decode(“utf8")

                                              where = text.find(‘>$')

                                              start_of_price = where + 2
                                              end_of_price = start_of_price + 4

                                              return float(text[start_of_price:end_of_price])
                  You need to ask the user
                  if the price is required    price_now = input(“Do you want to see the price now (Y/N)? ")
                  immediately.
                                          if price_now == “Y":

             If the user chooses “Y", display        print(get_price())
             the value that the get_price()    else:
             function gives you.
                                              price = 99.99

                                              while price > 4.74:
               If the user decides to wait for
               the price to drop, get the price           time.sleep(900)
               using the get_price() function,
               then use the given value to            price = get_price()
               decide whether or not it's time
              to buy coffee.                  print(“Buy!")




           90    Chapter 3
   120   121   122   123   124   125   126   127   128   129   130