我现在正在尝试用 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()

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

答案

这里的问题是input()在Python 3.x中返回一个字符串,所以当你进行比较时,你正在比较一个字符串和一个整数,这是没有明确定义的(如果字符串是一个单词怎么办,如何比较字符串和数字?

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

int(input(...))

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

请注意,循环一系列数字的更 Pythonic 方式(而不是while循环和计数)是使用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))

来自: stackoverflow.com