Reputation: 191
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?
Upvotes: 1
Views: 198
Reputation: 792
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.
Upvotes: 0
Reputation: 10912
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')
Upvotes: 0
Reputation: 20414
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)
Upvotes: 0
Reputation: 4664
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'
Upvotes: 2