Reputation: 2789
I'm trying to figure out if it's possible to assign two different returned values from a python function to two separate variables.
Here's the function, which returns a name and city value.
def authenticate():
name = raw_input("What is your name? ")
city = raw_input("What city do you live in? ")
if name != "Jerry Seinfeld" or city != "New York":
print """
Access denied
"""
else:
print """
Authenticated
"""
return name and city
Now, I want to assign the returned values to two variables, a and b.
I only know how to assign one value, like this.
a = authenticate()
(this actually assigns the city value to a, which I'm guessing is because "return name" comes before "return city" in the code)
Is what I'm trying to do possible?
Upvotes: 2
Views: 594
Reputation: 1848
if a function return more values you can use
a,b = zip(*function_calling())
Upvotes: 0
Reputation: 27216
You should change return name and city
(because "and"s use is logical expressions) to return (name, city)
for returning a tuple. Now you can assign values with tuple unpacking:
name,city = authenticate()
Upvotes: 2
Reputation: 798686
Python supports tuple unpacking.
def foo():
return 'bar', 42
a, b = foo()
It even works with other sequences.
a, b = [c, d]
Python 3.x extends the syntax.
a, b, *c = (1, 2, 3, 4, 5)
Upvotes: 8