【问题标题】:Basic math in python [duplicate]python中的基本数学[重复]
【发布时间】:2022-01-23 17:56:41
【问题描述】:

下面的代码返回 25,输入为 3 和 4。显然应该是 7。这对学校来说是个问题,我无法编辑前 3 行或最后一行。我在这里错过了什么?

total_owls = 0
num_owls_A = input()
num_owls_B = input()
num_owls_A = int(input())
num_owls_B = int(input())
total_owls = (num_owls_A + num_owls_B)
print('Number of owls:', total_owls)

【问题讨论】:

  • int(input())

标签: python python-3.x


【解决方案1】:

input() 将输入值作为字符串返回。所以,你基本上是在连接字符串而不是整数。

如果要将它们添加为数字,则需要先将它们转换为数字,如下所示

num_owls_A = int(input())
num_owls_B = int(input())

同样,如果您输入一个非数字值,这将产生错误,因此您需要在这种情况下处理异常。

【讨论】:

    猜你喜欢
    • 2012-07-07
    • 1970-01-01
    • 2015-05-24
    • 1970-01-01
    • 2012-08-10
    • 1970-01-01
    • 2019-08-12
    • 2013-10-30
    • 2021-12-25
    相关资源
    最近更新 更多