首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我收到以下错误: TypeError:+:'float‘和'str’不支持的操作数类型

我收到以下错误: TypeError:+:'float‘和'str’不支持的操作数类型
EN

Stack Overflow用户
提问于 2020-04-25 10:40:30
回答 1查看 82关注 0票数 1

我收到以下错误: TypeError:+:'float‘和'str’不支持的操作数类型

我完全按照"Python编程:计算机科学入门“这本书中写的代码,第44-45页。(见下文)。我哪里错了?

代码语言:javascript
复制
# 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()
EN

回答 1

Stack Overflow用户

发布于 2020-04-25 10:41:54

您需要将这些值中的一些转换为整数,因为输入被视为字符串。要更改这一点,您可以将输入包装在int()函数中,如下所示:

代码语言:javascript
复制
principal = int(input("Enter the initial principal: "))
apr = int(input("Enter the Annual Interest rate: "))

如果这个程序正在被其他人使用,你应该把它封装在try/except块中,以防有人给出的值不是int。它看起来像这样:

代码语言:javascript
复制
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")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61420329

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档