Page 115 -
P. 115
reuse code
Here‛s the existing code for Starbuzz. You needed to modify the program
to add an emergency report feature which will immediately report the
current price. Which parts of the code can you reuse to generate the
emergency report? You were to circle the part of the code you think you
might reuse as well as state why you might need to reuse it:
import urllib.request
Here's the code you
import time
can reuse.
price = 99.99
while price > 4.74:
time.sleep(900)
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
Whether you wait for the
price = float(text[start_of_price:end_of_price])
right price or request an
emergency order, you'll need
print ("Buy!") this code in each case.
Does that mean we have to
duplicate the code for each
option? Is this a good idea?
If you just copy and paste the same code,
it could make your program very long. And
hard to maintain. That’s why you don’t want Imagine if you
to duplicate the code. had to maintain a
program this length.
80 Chapter 3