【问题标题】:"Unorderable types: int() < str()"“不可排序的类型:int() < str()”
【发布时间】:2013-01-30 23:11:41
【问题描述】:

我现在正在尝试在 Python 上制作一个退休计算器。语法没有问题,但是当我运行以下程序时:

def main():
    print("Let me Retire Financial Calculator")
    deposit = input("Please input annual deposit in dollars: $")
    rate = input ("Please input annual rate in percentage: %")
    time = input("How many years until retirement?")
    x = 0
    value = 0
    while (x < time):
        x = x + 1
        value = (value * rate) + deposit
        print("The value of your account after" +str(time) + "years will be $" + str(value))

它告诉我:

Traceback (most recent call last):
  File "/Users/myname/Documents/Let Me Retire.py", line 8, in <module>
    while (x < time):
TypeError: unorderable types: int() < str()

有什么办法可以解决这个问题吗?

【问题讨论】:

    标签: python calculator


    【解决方案1】:

    这里的问题是input() 在 Python 3.x 中返回一个字符串,所以当你进行比较时,你是在比较一个字符串和一个整数,这没有很好的定义(如果字符串是一个单词怎么办? ,如何比较字符串和数字?) - 在这种情况下,Python 不会猜测,它会抛出错误。

    要解决这个问题,只需调用int() 将您的字符串转换为整数:

    int(input(...))
    

    请注意,如果您想处理十进制数,您需要使用float()decimal.Decimal() 之一(取决于您的准确性和速度需求)。

    请注意,循环一系列数字(与 while 循环和计数相反)的更 Pythonic 方式是使用 range()。例如:

    def main():
        print("Let me Retire Financial Calculator")
        deposit = float(input("Please input annual deposit in dollars: $"))
        rate = int(input ("Please input annual rate in percentage: %")) / 100
        time = int(input("How many years until retirement?"))
        value = 0
        for x in range(1, time+1):
            value = (value * rate) + deposit
            print("The value of your account after" + str(x) + "years will be $" + str(value))
    

    【讨论】:

    • 好的,我想通了。非常感谢您的时间和精力。我真的很感激。非常感谢您的好意先生。最后一个需要解决的问题是年利率会随着时间的推移而降低。例如,如果我在 10 年内以 50% 的利率输入 500 美元,它在一年后给我 550 美元,555.0、555.55、555.5555 等......因为它实际上并没有每年达到 50%。
    • @user2074050 这只是一个数学错误。您正在增加存款,而不是当前价值。您想要value *= (1 + rate)(将去年的值乘以比率加一)。
    【解决方案2】:

    顺便说一句,在 Python 2.0 中,您可以将任何东西与任何东西(int 到 string)进行比较。由于这不是明确的,因此在 3.0 中进行了更改,这是一件好事,因为您不会遇到相互比较无意义的值或忘记转换类型的麻烦。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-08
      • 2014-08-14
      • 2016-12-18
      • 1970-01-01
      相关资源
      最近更新 更多