Search code examples
python-3.xfunctionnameerror

defined function call returns name not defined error


I have defined a following function:

def create_table(table,L):
    table={'BBGTicker':L}
    table=pd.DataFrame(table)
    return table

trying to execute for example:

c=create_table(c,put_options_create)

where put_options_create is a list returns following error:

name 'c' is not defined.

If I was to write:

c={'BBGTicker':put_options_create}
c=pd.DataFrame(c)

this would work and give me a table.

What is wrong with the above function?


Solution

  • The first parameter of create_table is useless. table, the parameter, is immediately overwritten by table={'BBGTicker':L}, so there's no point in having that parameter.

    Just change the function to:

    def create_table(L):
        table={'BBGTicker':L}
        table=pd.DataFrame(table)
        return table
    

    and then call it as

    c=create_table(put_options_create)
    

    To answer why this is the case though: the variables between the () during a function call must already exist. If you haven't already assigned c a value, create_table(c,put_options_create) doesn't make sense. You only supply data there that you're giving a function. You don't specify in the parameter list data that you expect to get back*.


    * It is possible to "return" data via parameters via mutation of objects, but that isn't what you're attempting to do here.