[SOLVED] How to pass object across functions?

Issue

learning and incorporating functions into a web-scraping project in python and ran into this problem. Basically I want to pass an object (pandas dataframe) to another function / across functions. Basically I want to pass y to out across functions: out.append(y).

def do_inner_thing(y):
    y = y + 1
    out.append(y)
    
def do_outer_thing():
    out = []
    x = 2
    do_inner_thing(x)
    print(out)

do_outer_thing()

#Desired Output: 3

Solution

You want a return statement – have the function return an object using statement of the same name. Also, variables inside functions are local, not global, so they can’t be accessed from other functions. You’ll need to pass your list as well. Something like:

def do_inner_thing(y, out):
    y = y + 1
    out.append(y)
    return out
    
def do_outer_thing():
    out = []
    x = 2
    out = do_inner_thing(x, out)
    print(out)

do_outer_thing()

Answered By – AlecZ

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.