Python中的无序类型错误是什么意思?

2024-06-21 20:36:37 发布

您现在位置:Python中文网/ 问答频道 /正文

from urllib.request import urlopen
page1 = urlopen("http://www.beans-r-us.biz/prices.html")
page2 = urlopen("http://www.beans-r-us.biz/prices-loyalty.html")
text1 = page1.read().decode("utf8")
text2 = page2.read().decode("utf8")
where = text2.find(">$")
start_of_price = where + 2
end_of_price = where + 6
price_loyal = text2[start_of_price:end_of_price]
price = text1[234:238]
password = 5501
p = input("Loyalty Customers Password? : ")
passkey = int(p)

if passkey == password:
    while price_loyal > 4.74:
        if price_loyal < 4.74:
            print("Here is the loyal customers price :) :")
            print(price_loyal)
        else:
            print( "Price is too high to make a profit, come back later :) ")
else:
    print("Sorry incorrect password :(, here is the normal price :")
    print(price)
input("Thanks for using our humble service, come again :), press enter to close this window.")

我的问题是它一直运行到我得到4.74部分。然后它停下来抱怨一个不可排序的类型。我完全搞不懂那是什么意思。


Tags: ofhttpiswwwpasswordwherepriceurlopen
2条回答

price_loyal是试图与数值(4.75)进行比较的字符串(即使它包含使用find找到的数字)?供你比较

float(price_loyal)

更新(感谢@agf):

使用Pythonv 3.x可以得到您提到的错误消息。

>>> price_loyal = '555.5'
>>> price_loyal  > 5000.0
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    price_loyal > 5000.0
TypeError: unorderable types: str() > float()
>>> 

鉴于

>>> float(price_loyal) > 5000.0
False

在这种情况下,Python的版本会有所不同,所以最好总是提到自己使用的版本。以前。。。使用Pythonv 2.x

如果不首先将string转换为float,您的比较将关闭。E、 g

price_loyal
'555.5'

与string和float的比较给出了True

price_loyal > 5000.0
True

这种与float和float的比较给出了False应该的结果

float(price_loyal) > 5000.0
False

可能还有其他问题,但这看起来像一个。

我不是Python代码编写者,但它看起来好像在抱怨你试图将字符串与浮点数进行比较,我猜Python不会为你变戏法。

您应该将字符串转换为浮点数,但这是在Python中完成的。

相关问题 更多 >