I am familiar with how the split() function works if you implement it like this:
def sayHello():
name = input("whats you ́re name?:" )
print("hello", name)
In this case the input function only wants one input from user. But what actually happens in this case?
def test():
str1, str2 = input().split()
print(str1, str2)
The syntax:
a, b = input()
Is this a way to ask the user for 2 inputs at the same time or when would you use this?
-
This is a special case of assignment described in the reference ('If the target list is a comma-separated list of targets...') and commonly referred to as unpacking.bereal– bereal2016年11月11日 11:01:16 +00:00Commented Nov 11, 2016 at 11:01
3 Answers 3
This does different things on Python 2 and Python 3.
Python 3's input() is Python 2's raw_input(), and will always return a string.
When you do a tuple unpacking as in a, b, = (1, 2), the amount of elements on the right must match the amount of names on the left. If they don't, you'll get a ValueError. As strings are iterable, a, b = input() will work, if the user enters a two character long string. Any other string will crash your program.
To ask your user for more than one input at once, clearly define the format in the prompt, e.g., inp = input('Please input your first and last name, separated by a comma: '), then parse the input afterwards: first_name, last_name = inp.split(',').
Note that this will still crash your program if they enter an incorrect string, with more or less than one comma, but that's reasonably simple to check for, notify the user, and try again.
On Python 2, input() attempts to coerce the value to a natural Python value, so if the user inputs [1, 2], input() will return a Python list. This is a bad thing, as you will still need to validate and sanitise the user data yourself, and you may have wanted "[1, 2]" instead.
2 Comments
2, 3 causes input() to return "2, 3", which is a string, an iterable, of length 4. c, d = "2, 3" sets c = "2", d = "3", then runs out of variables, but still has some string left to consume. What you'll want to do is c, d = input().split(',') or inp = input() then c, d = inp.split(',') if that makes more sense to you.This is only working with a string of length 2.
Just try such things in ipython:
In [9]: a, b = input()
"hallo"
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-9-3765097c12c0> in <module>()
----> 1 a, b = input()
ValueError: too many values to unpack
In [10]: a, b = input()
"ha"
In [11]: a
Out[11]: 'h'
In [12]: b
Out[12]: 'a'
In [13]: a, b = input()
"a"
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-13-3765097c12c0> in <module>()
----> 1 a, b = input()
ValueError: need more than 1 value to unpack
So no, this not a correct way to ask for 2 inputs.
Comments
input("What Your Name: ")