简体   繁体   中英

Passing variables between functions in Python

Ok so I am having a tough time getting my head around passing variables between functions:

I can't seem to find a clear example.

I do not want to run funa() in funb().

def funa():
    name=input("what is your name?")
    age=input("how old are you?")
    return name, age

funa()

def funb(name, age):
    print(name)
    print(age)

funb()

Since funa is returning the values for name and age, you need to assign those to local variables and then pass them into funb:

name, age = funa()
funb(name, age)

Note that the names within the function and outside are not linked; this would work just as well:

foo, bar = funa()
funb(foo, bar)

Think of it as passing objects around by using variables and function parameters as references to those objects. When I updated your example, I also changed the names of the variables so that it is clear that the objects live in different variables in different namespaces.

def funa():
    name=input("what is your name?")
    age=input("how old are you?")
    return name, age                   # return objects in name, age

my_name, my_age = funa()               # store returned name, age objects
                                       # in global variables

def funb(some_name, some_age):         # a function that takes name and 
                                       # age objects
    print(some_name)
    print(some_age)

funb(my_name, my_age)                  # use the name, age objects in the
                                       # global variables to call the function

As it is returning a tuple, you can simply unpack it with * :

funb(*funa())

It should look something like this:

def funa():
  # funa stuff
  return name, age

def funb(name, age):
  # funb stuff
  print ()

funb(*funa())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM