在同一行插入多个数字 (Python)

Insert multiple numbers on the same line (Python)

我试图在此程序中的同一行中输入两个数字,但是当我写入 2 个数字(由 space 分隔)时出现以下错误:

Traceback (most recent call last):
  File "(the file path)", line 3, in <module>
    for x in range(1, n1 + 1):
TypeError: can only concatenate str (not "int") to str

这是我的代码:

n1, n2 = input("Insert two numbers: ").split()
sum1 = 0
for x in range(1, n1 + 1):
    sum1 += x ** n2
    print(f'{x} to the power of {n2} is {x ** n2}')
print('The total sum is:', sum1)

我不明白为什么会出现该错误。我做错了什么?

在第一行的输入中,我尝试添加“str”以防错误解决:

n1, n2 = str(input("Insert two numbers: ").split())

但现在 returns 我在写 2 个数字时又犯了一个错误:

Traceback (most recent call last):
  File "(the file path)", line 1, in <module>
    n1, n2 = str(input("Insert two numbers: ").split())
ValueError: too many values to unpack (expected 2)

我不常使用Python,我不明白我做错了什么。你能帮我一下吗?

您需要将两个数字都转换为 int:

n1, n2 = [int(x) for x in input("Insert two numbers: ").split()]

错误是由于 Python 试图将字符串 n1 和整数 1:

连接为字符串造成的
n1 + 1