代码错误 - Python中的未来投资价值

时间:2013-09-22 01:54:03

标签: python string int pow

我是python的初学者,这个作业要求我获得投资的未来价值。

p = raw_input("[How much did you invest?]:")
r = str(raw_input("[How much is the interest rate?]:"))
n = raw_input("[How long have you been investing?]:")
future_value = p*(1+1)**n
print "\n\n\tYour future value of your investment is: %s\n" % future_value

错误代码:

unsupported operand type(s) for ** or pow(): 'int' and 'str'

任何帮助?

2 个答案:

答案 0 :(得分:1)

您需要将输入转换为int,因为raw_input函数返回string

如果在交互式终端中键入help(raw_input),您应该看到定义:

raw_input(...)
    raw_input([prompt]) -> string

固定代码:

p = int(raw_input("[How much did you invest?]:"))
r = float(raw_input("[How much is the interest rate?]:"))
n = int (raw_input("[How long have you been investing?]:"))
future_value = p*(1+1)**n
print "\n\n\tYour future value of your investment is: %s\n" % future_value

答案 1 :(得分:1)

错误消息告诉您正在尝试将整数提升为字符串幂。那必须是代码的这一部分:

(1+1)**n

确实,1 + 1是一个整数(它是2 - 如果你想要2,为什么不写2而不是1+1?)。

那是什么nn来自raw_input()来电。实际上,raw_input()总是返回一个字符串。如果您想将该字符串更改为整数(您这样做),请改为:

n = int(raw_input("[How long have you been investing?]:"))