-1

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()
AHC
  • 31
  • 1
  • 2
  • 2
    Daniel is right, but this is the sort of thing you'd pick up from reading an introduction to Python, or a tutorial on variables and functions. – SwiftsNamesake Oct 10 '16 at 16:25

3 Answers3

4

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)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
2

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
tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • thank you this is very clear but I still do not get why use a function in the first place and not just use a global var if name and age end up as global anyway? – AHC Oct 10 '16 at 16:35
  • It depends on what your goals for the program are. As a program grows, it becomes unmanageable unless you encapsulate data - and that means avoiding global variables. Other concerns are about how you use the function. Suppose in the future that you want to maintain a `dict` of name:age pairs. Now your name, age global variables are problematic. You would have to change the function and all of the places where the data are used. – tdelaney Oct 10 '16 at 16:58
0

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())
lycuid
  • 2,555
  • 1
  • 18
  • 28