Python Forum
Passing data between functions, got it working, but need clarification please
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Passing data between functions, got it working, but need clarification please
#4
(Apr-18-2018, 06:52 AM)digitalmatic7 Wrote: Does this mean that all the code from test1 is merged within test2?
Not merged test1 do only one task that is to return df.
When you do test2(test1()) is test1 a argument that get passed to function test2.

Here another example how to send just function object,also showing a better way to document with docstrings.
Because functions are objects(like string,int,dict,list..ect) you can pass them as arguments to other functions.
import pandas as pd

def test1():
    '''test1 function creates the dataframe'''
    list1 = [
        "item1", "item2", "item3", "item4", "item5", "item6",
        "item7", "item8", "item9", "item10", "item11", "item12"
        ]
    df = pd.DataFrame(list1, columns=['Col 0:'])
    df.insert(1, 'Col 1:', "")
    df.insert(2, 'Col 2:', "")
    return df

def test2(df):
    '''
    test2 function calls the dataframe from test1()
    makes a change to the cell data and prints df
    '''
    df = df() # now call test1 inside test2
    df.iloc[5, 2] = "NEW CELL DATA"
    print(df)

if __name__ == '__main__':
    test2(test1)
Output:
Col 0: Col 1: Col 2: 0 item1 1 item2 2 item3 3 item4 4 item5 5 item6 NEW CELL DATA 6 item7 7 item8 8 item9 9 item10 10 item11 11 item12
Quote:Python’s functions are first-class objects.
You can assign them to variables, store them in data structures,
pass them as arguments to other functions,
and even return them as values from other functions.
Reply


Messages In This Thread
RE: Passing data between functions, got it working, but need clarification please - by snippsat - Apr-18-2018, 08:28 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Having trouble setting the X-Ticks for a data set I am working with. Mr_OHagan 1 566 Jan-22-2024, 09:12 PM
Last Post: deanhystad
  I'm working onn below code to extract data from excel using python kiran 1 3,322 Oct-24-2017, 01:42 PM
Last Post: kiran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020