2013-02-15 77 views
13

我想在Python上制作一个退休计算器。这没有什么错的语法,但是当我运行下面的程序:“无法处理的类型:int()<str()”

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() 

任何想法如何,我可以解决这个问题?

回答

31

这里的问题是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)) 
+1

好吧我想通了一切。非常感谢您的时间和精力。我真的很感激。非常感谢你的亲切先生。最后一个问题需要解决,即年费率随着时间的推移而下降。例如,如果我以50%的速度在10年内投入500美元,那么在一年后555.0,555.55,555.5555等会给我550美元......因为它实际上并没有每年执行50%。 – user2074050 2013-02-15 01:22:12

+1

@ user2074050这只是一个数学错误。您正在增加存款,而不是现在的价值。你想'价值* =(1 +利率)'(乘以去年的价值乘以加1)。 – 2013-02-15 02:11:30

0

您需要将您的字符串转换为整数,以一个循环条件中进行比较。用int(time)替换其他时间。最好在循环之前而不是在循环条件内进行替换,因为每次循环迭代时都会将字符串转换为整数。

0

只是一个方面说明,在Python 2.0中,你可以比较任何东西(int到字符串)。由于这并不明确,所以在3.0版中进行了更改,这是一件好事,因为您没有遇到将无意义的值与对方进行比较或者忘记转换类型的麻烦。

相关问题