ValueError:值太多

2024-04-18 05:49:43 发布

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

我正在学习python教程。我准确地输入了教程的内容,但它不会运行。我认为问题是教程使用了Python2之类的东西,而我使用的是Python3.5。例如,教程不使用括号后的打印,我不得不和它使用原始输入,我只使用输入。你知道吗

这就是我想做的-

def sumProblem(x, y): 
    print ('The sum of %s and %s is %s.' % (x, y, x+y))


def main(): 
    sumProblem(2, 3) 
    sumProblem(1234567890123, 535790269358) 
    a, b = input("Enter two comma separated numbers: ") 
    sumProblem(a, b)


main()

这是我收到的错误:

ValueError: too many values to unpack (expected 2)

如果我只放两个没有逗号的数字,它会把它们连在一起。我尝试更改为整数,但出现以下错误:

ValueError: invalid literal for int() with base 10: 

当我在这里搜索的时候,答案似乎并不适用于我的问题,他们涉及的更多或者我不明白。你知道吗


Tags: andofthe内容ismaindef错误
2条回答

input(..)返回字符串。字符串是一个iterable,因此您可以用以下方法将其解包:

a, b = input("Enter two comma separated numbers: ") 

但前提是字符串正好包含两个项。所以对于一个字符串,这意味着字符串正好包含两个字符。你知道吗

但是,代码提示您要输入两个整数。我们可以使用str.split()将字符串拆分为“单词”列表。你知道吗

然后我们可以用int作为函数执行mapping:

def sumProblem(x, y): 
    print ('The sum of %s and %s is %s.' % (x, y, x+y))
def main(): 
    sumProblem(2, 3) 
    sumProblem(1234567890123, 535790269358) 
    a, b = map(int, input("Enter two comma separated numbers: ").split(','))
    sumProblem(a, b)
main()

您的输入应如下所示:

a, b = map(int, input('text:').split(','))

^{}返回一行输入-字符串。解析就交给你了。你知道吗

相关问题 更多 >