2

I want to take input like + 2 3 ? 1 20 where the first variable is char and the next will be integers

I have done this

sign,m,n = input().split()
[sign,m,n]=[str(sign),int(m),int(n)]

But i get this error

ValueError: not enough values to unpack (expected 3, got 0)

5
  • Cannot reproduce! Your code-snippet runs just fine. Commented Jan 12, 2019 at 15:58
  • I do not get that error with your input. I do get it when I press Enter without entering some text. Perhaps you forgot to enter something? Commented Jan 12, 2019 at 15:58
  • @ usr2564301 I face that every time when I press Enter both with and without value Commented Jan 12, 2019 at 16:13
  • @G-man This also give me the same error Commented Jan 12, 2019 at 16:15
  • You can accomplish this task with this single line statement too: sign, m, n = [c if i == 0 else int(c) for i, c in enumerate(input().split()[:3])]. Commented Jan 12, 2019 at 16:32

3 Answers 3

1

Your problem lies in sign,m,n = input().split(). You have to treat as a list, not as function which returns 3 values. Here it is a snippet code of what you desire:

stdin = input().split()
sign,m,n = str(stdin[0]),int(stdin[1]),int(stdin[2])

Stdin is a list

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to use your own logic to get it done, then here is the way.

Just append [:3] at the end of first statement to slice the list.

>>> sign, m, n = input().split()[:3]
+ 2 3 ? 1 20
>>>
>>> [sign,m,n] = [str(sign), int(m), int(n)]
>>>
>>> sign
'+'
>>>
>>> m
2
>>>
>>> n
3
>>>

And here is another way to accomplish the same in a single line.

For this you can use the concept of list comprehension.

>>> sign, m, n = [c if i == 0 else int(c) for i, c in enumerate(input().split()[:3])]
+ 2 3 ? 1 20
>>>
>>> sign
'+'
>>> m
2
>>> n
3
>>>

Comments

0

Just adding the enclosing square paranthesis in your first statement works on Python 3.6.7 :

[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> [sign,m,n] = input().split()
- 2 3
>>> [sign,m,n] = [str(sign),int(m),int(n)]
>>> sign
'-'
>>> m
2
>>> n
3

1 Comment

Yeah. This works also. Can you tell me how this square parenthesis works at this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.