为什么在将输入与数字进行比较时会出现“不可排序的类型:int()<str()”或“'int'和'str'的实例之间不支持'<'”?[重复]
- 2025-03-26 09:10:00
- admin 原创
- 13
问题描述:
我有这个代码:
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()
我该如何修复它?
解决方案 1:
这里的问题是input()
返回 Python 3.x 中的字符串,因此当您进行比较时,您是在比较字符串和整数,这没有明确定义(如果字符串是一个单词,如何比较字符串和数字?) - 在这种情况下,Python 不会猜测,它会引发错误。
要解决此问题,只需调用int()
将字符串转换为整数:
int(input(...))
需要注意的是,如果您要处理十进制数,则需要使用其中一个float()
或decimal.Decimal()
(取决于您的准确性和速度需求)。
请注意,循环一系列数字(而不是while
循环和计数)的更 Python 方式是使用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))
解决方案 2:
顺便提一下,在 Python 2.0 中,您可以将任何内容与任何内容进行比较(int 与 string)。由于这一点并不明确,因此在 3.0 中进行了更改,这是一件好事,因为您不必再遇到将无意义的值相互比较或忘记转换类型的麻烦。
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD