我收到以下错误: TypeError:+:'float‘和'str’不支持的操作数类型
我完全按照"Python编程:计算机科学入门“这本书中写的代码,第44-45页。(见下文)。我哪里错了?
# investment calculator
def main():
print ("this program calculates the future value")
print ("of a 10-year investment.")
principal = input("Enter the initial principal: ")
apr = input("Enter the Annual Interest rate: ")
for i in range (10):
principal = principal * (1.0 + apr)
print ("The value in 10 years is: "), principal
main()发布于 2020-04-25 10:41:54
您需要将这些值中的一些转换为整数,因为输入被视为字符串。要更改这一点,您可以将输入包装在int()函数中,如下所示:
principal = int(input("Enter the initial principal: "))
apr = int(input("Enter the Annual Interest rate: "))如果这个程序正在被其他人使用,你应该把它封装在try/except块中,以防有人给出的值不是int。它看起来像这样:
while True:
try:
principal = int(input("Enter the initial principal: "))
apr = int(input("Enter the Annual Interest rate: "))
break
except TypeError:
print("Value is not an integer")https://stackoverflow.com/questions/61420329
复制相似问题