2

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?

jerry
  • 2,743
  • 9
  • 41
  • 61

3 Answers3

8

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)
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
2

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() 
utdemir
  • 26,532
  • 10
  • 62
  • 81
0

if a function return more values you can use

a,b = zip(*function_calling())
Shahir Ansari
  • 1,682
  • 15
  • 21