What’s unscathed for python?

Asked

Viewed 73 times

4

I wonder what exactly is wrong with this python code:

import urllib.request
page = urllib.request.urlopen("http://beans-r-us.appspot.com/prices-loyalty.html")
    text = page.read().decode('utf8')

price = 99.99
while price > 4.74:
    where = text.find('>$')
    preçoinicial = where + 1
    preçofinal = preçoinicial + 5
    price = text[preçoinicial:preçofinal]
print("Buy")

The error message is as follows:

Traceback (most recent call last):
File "starbuzzpreçocafe.py", line 7, in <module>
while price > 4.74:
TypeError: unorderable types: str() > float()

1 answer

5


Are you comparing string with float after the first iteration.

The solution is to convert the extracted text always to float:

price = float( text[preçoinicial:preçofinal] )
        ^^^^^

Thus remaining:

import urllib.request
page = urllib.request.urlopen("http://beans-r-us.appspot.com/prices-loyalty.html")
    text = page.read().decode('utf8')

price = 99.99
while price > 4.74:
    where = text.find('>$')
    preçoinicial = where + 1
    preçofinal = preçoinicial + 5
    price = float( text[preçoinicial:preçofinal] )
print("Buy")

Note: as noted by @Miguel, in the comments, it would have to be:
preçoinicial = where + 2
not to catch the $ which is located by the find, and the preçofinal adjusted according to the number of digits you are waiting for, so that no more characters come.

Also, you need to be careful if there is no lower price than indicated, something like:

price = 99.99
where = 0
while price > 4.74 and where >= 0:
    where = text.find('>$')

There’s an even better way, which is to put the test of where within the while, then need to see what is best for your real case. Maybe you want to do some logic to not show the "buy" if the where is negative.

  • 1

    I would also suggest avoiding characters like ç variables. It even works, but it can give you some headache depending on the code editor and system you open. If you stick to ASCII characters, you’ll have one less worry.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.