[英]"Unorderable types: int() < str()"
我现在正在尝试在 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 中返回一个字符串,所以当你进行比较时,你是在比较一个字符串和一个没有明确定义的整数(如果字符串是一个单词,怎么办?比较字符串和数字?) - 在这种情况下,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))
顺便提一下,在 Python 2.0 中,您可以将任何内容与任何内容进行比较(int 到 string)。 由于这不是明确的,它在 3.0 中进行了更改,这是一件好事,因为您不会遇到相互比较无意义值或忘记转换类型的麻烦。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.