【问题标题】:Insert multiple numbers on the same line (Python)在同一行插入多个数字(Python)
【发布时间】: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,我不明白我做错了什么。请帮帮我好吗?

【问题讨论】:

标签: python split line


【解决方案1】:

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

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

该错误是由 Python 尝试将字符串 n1 和整数 1 连接为字符串引起的:

n1 + 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 2017-11-02
    • 2016-02-15
    • 1970-01-01
    • 1970-01-01
    • 2012-11-20
    • 2013-10-08
    相关资源
    最近更新 更多