python3与输入的2个整数求和。ValueError:基为10的int()的文本无效:“1 1”

2024-04-25 08:06:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用输入在Python3中添加2个整数。在

def sum(x,y):
    return x+y
a = int(input("Enter first number"))
b = int(input("Enter second number"))
print("The sum of a and b is", sum(a,b))

得到以下错误

^{pr2}$

另一个问题是这在我的Jupyter笔记本上正常工作, 但对于另一个在线实践中心,它显示了这个错误。在


Tags: ofthenumberinputreturndef错误整数
3条回答

你的代码是有效的,但不适用于实践中心给出的特定输入。进行以下修改:

nums = [int(x) for x in input("Enter numbers: ").split()]
print("The sum of a and b is", sum(nums))

顺便说一下,sum是一个内置函数,所以您不必自己编写它。唯一真正改变的是:

^{pr2}$

nums将是一个数字列表,顾名思义。下一部分是列表理解。input("Enter numbers: ").split()将接受输入并在任何空白处拆分它。例如,'hello world'将变成一个带有['hello', 'world']的列表。在这种情况下,'1 1'将变成一个带有['1', '1']的列表。然后,通过列表理解,将每个元素转换为一个整数(['1', '1']->;[1, 1])。然后,将这个列表传递到sum。此外,这与列表理解的作用相同:

nums = list(map(int, input("Enter numbers: ").split()))

你选择哪一个并不重要。如果你想得到真正的幻想,你可以用一句话来完成整个事情:

print("The sum of a and b is", sum(map(int, input("Enter numbers: ").split())))

假设您的输入本身带有空格,您可以使用replace命令替换这些空格。在

def sum(x,y):
    return x+y

a = int(input("Enter first number: ").replace(" ",""))
b = int(input("Enter second number: ").replace(" ",""))
print("The sum of a and b is: ", sum(a,b))

对于你的具体情况,这应该行得通。我在这里所做的是,我将像'835255'这样的输入转换成'835255',它本身稍后会很容易地转换成int,并且会完美地工作。在

删除复制品以及伴侣。在

如果要将所有值输入到与11相同的行中,则应使用split()

def sum(x,y):
    return x+y

a, b = map(int, input("Enter numbers ").strip().split())
print("The sum of a and b is", sum(a,b))

输出:

^{pr2}$

如果需要单独输入值:

def sum(x,y):
    return x+y

a = int(input("Enter first number ").strip())
b = int(input("Enter second number ").strip())

print("The sum of a and b is", sum(a,b))

输出:

^{pr2}$

相关问题 更多 >