use*_*050 17 python calculator
我正试图在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))
Run Code Online (Sandbox Code Playgroud)
它告诉我:
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()
Run Code Online (Sandbox Code Playgroud)
我有什么想法可以解决这个问题?
Gar*_*tty 36
这里的问题是input()在Python 3.x 中返回一个字符串,所以当你进行比较时,你要比较一个字符串和一个整数,它没有很好地定义(如果字符串是一个单词,怎么比较一个字符串和数字?) - 在这种情况下Python不猜,它会引发错误.
要解决此问题,只需调用int()将您的字符串转换为整数:
int(input(...))
Run Code Online (Sandbox Code Playgroud)
作为一个注释,如果你想处理十进制数,你会想要使用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))
Run Code Online (Sandbox Code Playgroud)