1
string, integer = input("Enter a word and an integer: ")

Python3 returns that ValueError: too many values to unpack (expected 2). What can I do to fix that?

1
  • 1
    string, integer = input("Enter a word and an integer: ").split() Commented Mar 21, 2019 at 19:49

4 Answers 4

2

input() method returns a single string value unless you split it into parts with split()(by default splits where spaces are).

>>> string, integer = input("Enter a word and an integer: ")
Enter a word and an integer: test 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
>>> string, integer = input("Enter a word and an integer: ").split()
Enter a word and an integer: test 5
>>> string
'test'
>>> integer
'5'
Sign up to request clarification or add additional context in comments.

1 Comment

yes because it was split from a string. It is needed to be cast to an integer if needed as an integer and this was totally out of the question.
0

You can unpack any iterable into variables.

A string is a variable, so for instance, you could do:

a,b = 'yo'

which gives a = 'y' and b = 'o'.

If you wish to unpack two "words", you must split your string on spaces to obtain a list of the two words.

I.e.

'hello user'.split()

Gives ['hello', 'user'].

You can then unpack this list into two variables.

This is what you want, but splitting the string returned from input().

I.e.

string, integer = input("Enter a word and an integer: ").split()

Is what you are looking for.

Oh, and if you want the integer variable to actually be an integer, you should convert it to one after:

integer = int(integer)

Comments

0

There are several ways of doing this, I think that what may sound right is to impose a given type to the user:

def typed_inputs(text, *types):
    user_input = input(text).split()
    return tuple(t(v) for t, v in zip(*types, user_input))

Which can be used as follows:

>>> types = (int, float, str)
>>> message = f"Input the following types {types} :"
>>> print(typed_inputs(message, types))
Input the following types (<class 'int'>, <class 'float'>, <class 'str'>) : 1 2.1 test
(1, 2.3, 'test')

Comments

0

Following would work but both will be strings.

string, integer = input("Enter a word and an integer: ").split()

You need to have something like this.

string_val, integer_val = raw_input("String"), int(raw_input("Integer"))

It would fail if user doesn't enter an int. You might wanna user Try catch and inform the user.

Comments

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.