17

私は今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()

どうすればこれを解決できるか考えてみてください。

4

2 に答える 2

37

ここでの問題はinput()、Python 3.xで文字列を返すことです。したがって、比較を行うときは、文字列と、明確に定義されていない整数を比較しています(文字列が単語の場合、どのように比較しますか?文字列と数値?)-この場合、Pythonは推測せず、エラーをスローします。

これを修正するには、単に呼び出しint()て文字列を整数に変換します。

int(input(...))

注意として、10進数を処理する場合は、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))
于 2013-02-15T01:09:28.823 に答える