"不可排序的类型:int()< str()”; [英] "Unorderable types: int() < str()"

查看:93
本文介绍了"不可排序的类型:int()< str()”;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python制作退休计算器。语法没有错,但是当我运行以下程序时:

I'm trying to make a retirement calculator right now on Python. There's nothing wrong with the syntax but when I run the following program:

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

有什么想法可以解决吗?

Any ideas how I could solve this?

推荐答案

这里的问题是 input()在Python 3.x中返回一个字符串,因此当您执行比较中,您正在比较一个字符串和一个定义不明确的整数(如果字符串是一个单词,如何比较一个字符串和一个数字?)-在这种情况下,Python不会猜测,它会抛出一个错误。

The issue here is that input() returns a string in Python 3.x, so when you do your comparison, you are comparing a string and an integer, which isn't well defined (what if the string is a word, how does one compare a string and a number?) - in this case Python doesn't guess, it throws an error.

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

To fix this, simply call int() to convert your string to an integer:

int(input(...))

作为注释,如果您要处理十进制数字,您将要使用 float() decimal.Decimal() (取决于您的准确性和速度需求)。

As a note, if you want to deal with decimal numbers, you will want to use one of float() or decimal.Decimal() (depending on your accuracy and speed needs).

请注意,更Python化的方式是遍历一系列数字(而不是 while 循环和计数)将使用 range()。例如:

Note that the more pythonic way of looping over a series of numbers (as opposed to a while loop and counting) is to use range(). For example:

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

这篇关于&quot;不可排序的类型:int()&lt; str()”;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆