tags:

views:

116

answers:

3

I'm trying to learn python. I am using 3.1.2 and the o'reilly book is using 3.0.1 here is my code:

import urllib.request

price = (99.99)

while price > 4.74:
    page = urllib.request.urlopen ("http://www.beans-r-us.biz/prices-loyalty.html")
    text = page.read().decode("utf8")

    where = text.find('>$')

    start_of_price = where + 2
    end_of_price = start_of_price + 6

    price = float(text[start_of_price:end_of_price])

print ("Buy!")

Here is my error:

Traceback (most recent call last):
  File "/Users/odin/Desktop/Coffe.py", line 14, in <module>
    price = float(text[start_of_price:end_of_price])
ValueError: invalid literal for float(): 4.59</
>>> 

What is wrong?

+5  A: 

The problem is that you have extra characters at the end of your float, probably because the content of the page changed since the code was written (the number appears to change every fifteen minute). You could try changing the following line to make the code slightly more robust:

end_of_price = text.find('<', start_of_price)

For an even better solution you should use something like BeautifulSoup to parse the HTML.

Mark Byers
More precisely, why did you pick 6 in the line `end_of_price = start_of_price + 6`? In this case the size is 4, and it is possible that the size is not fixed.
Kathy Van Stone
thank you for helping
Jeremy
6 was used because when i used 4 for the previous assignment I only got the dollar amount and decimal, it did not give me the cents amount.
Jeremy
+1  A: 

You should never use float for money. Read accepted answer: http://stackoverflow.com/questions/61872/use-float-or-decimal-for-accounting-application-dollar-amount

Pyrolistical
+1  A: 

You are calculating end_of_price as start_of_price + 6. Actually your price value seems to be only 4 characters long, so that you also include the two characters following in the string you want to convert to a float. Python then complains that 4.59</ is not a number.

If you instead set end_of_price to start_of_price + 4 it should work.

sth
thank you. when I do as you say I now have this errorTraceback (most recent call last): File "/Users/odin/Desktop/Coffe.py", line 14, in <module> price = float(text[start_of_price:end_of_price])ValueError: could not convert string to float: !DOC:(
Jeremy
I sent tried again and now it works? im not sure exactly what the problem is but as far and right this second it works. whos know about tomorrow... haha thank you so much sir, now i can continue this chapter!
Jeremy