What is illegible for python?

4

I would like to know 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()
    
asked by anonymous 19.11.2016 / 14:45

1 answer

5

You are comparing string with float after the first iteration.

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

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

Looking like this:

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
    to not get the $ that is found by find, and preçofinal adjusted according to the number of digits you are expecting, so that no more characters come.

In addition, you must 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('>$')

It's even better, which is to put the test of where inside while , then you need to see what is best for your real case. You may want to make some logic not to show "buy" if where is negative.

    
19.11.2016 / 14:49