Brandon Barry
Brandon Barry

Reputation: 61

Passing values to another function in Python?

I currently have 4 functions, of which I need to connect. I have the first function, which formats a csv file and turns out 4 values, the numbers of (useful) rows and columns and two different lists. Then, the next two functions have to use the values from the first function to calculate some things. Finally, the main function (the last one) will take those calculated values and produce an output. I'm really struggling in learning how to pass the output's of the functions to the other ones. Currently it looks (really roughly) like this:

def formatting():
    ...
    n = 30
    m = 9
    array = [...]
    tot = [...]
    return(n, m, array, tot)

def calculation():
    formatting()
    # a bunch of code that uses n, m, array and tot
    mn = [...]
    mx = [...]
    av = [...]
    sd = [...]
    return(mn, mx, av, sd)

def cor():
   formatting()
   # a bunch of code that uses n, m, array and tot
   rs = [...]
   return(rs)

def main(csvfile):
   calculation()
   cor()
main()

It keeps telling me that there is an error in the first function, saying that m is not defined (first line in which a passed variable is used), meaning that the value from m has not passed to the calculation function and hence won't be usable in any of the other functions. Can someone explain to me how I can pass this correctly?

I also need to have an argument in the main function, which lists the file to be analyzed and I need to pass that onto formatting.

Thank you!

Upvotes: 0

Views: 747

Answers (3)

sandeshdaundkar
sandeshdaundkar

Reputation: 903

def formatting():
    ...
    n = 30
    m = 9
    array = [...]
    tot = [...]
    return(n, m, array, tot)

def calculation():
    n,m,array,tot = formatting()
    # a bunch of code that uses n, m, array and tot
    mn = [...]
    mx = [...]
    av = [...]
    sd = [...]
    return(mn, mx, av, sd)

def cor():
   n,m,array,tot = formatting()
   # a bunch of code that uses n, m, array and tot
   rs = [...]
   return(rs)

def main():
   calculation()
   cor()
main()

When you want to use values from different functions, you should assign them to variable while calling and then use those assigned variables to do calculations.

Upvotes: 1

Jitin
Jitin

Reputation: 344

The concept you are looking for is Python packing and unpacking feature.

Check this out for details on Packing and Unpacking

Upvotes: 0

Heike
Heike

Reputation: 24420

You need to assign the return values of formatting to variables before you can use them in the other function, e.g.

def calculation():
    m, n, array, tot = formatting()
    # a bunch of code that uses n, m, array and tot
    mn = [...]
    mx = [...]
    av = [...]
    sd = [...]
    return(mn, mx, av, sd)

Upvotes: 1

Related Questions