【发布时间】:2021-02-01 06:04:48
【问题描述】:
我试图在这个程序的同一行中输入两个数字,但是当我写这两个数字(用空格分隔)时出现以下错误:
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())
但现在当我写 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,我不明白我做错了什么。请帮帮我好吗?
【问题讨论】:
-
这能回答你的问题吗? How can I read inputs as numbers?