Home > Mobile >  function doesn't return values, code is working
function doesn't return values, code is working

Time:06-23

I have this code written down which returns a bunch of ratios each line works fine when executed alone however I am having trouble with putting the code inside a function which should return the values as a dictionary

example of the output: { " less than high school" :0.2 , "high school" :0.39 ...}

def education ():
    total = sum (df["CHILDNM"])
    edult12 = df[['EDUC1','CHILDNM']].where(df['EDUC1'] == 1, 0)
    nlt12=sum( edult12["CHILDNM"])
    edu12 = df[['EDUC1','CHILDNM']].where(df['EDUC1'] == 2, 0)
    n12= sum( edu12["CHILDNM"])
    edumt12 = df[['EDUC1','CHILDNM']].where(df['EDUC1'] == 3, 0)
    nmt12=sum( edumt12["CHILDNM"])
    educollege = df[['EDUC1','CHILDNM']].where(df['EDUC1'] == 4, 0)
    ncollege = sum( educollege["CHILDNM"])
    lt12ratio = nlt12/total
    edu12ratio = n12 / total
    edumt12ratio = nmt12 / total
    educollegeratio = ncollege/total
    values = print (lt12ratio, edu12ratio,edumt12ratio, educollegeratio )
    print (values)

CodePudding user response:

Your code is missing the return statement!

Add something like

return { "less than high school" :0.2 , "high school" :0.39 }

(replace numbers with your actual calculated values)

CodePudding user response:

It seems you do not have any "return" statement. So this means the function will not give back any value.

def education ():
    somedict = {'url': 'https://stackoverflow.com/'}
    return somedict 


save_return_value = education()

The "save_return_value" could then include the return value

CodePudding user response:

Well, you assign to values the result of calling print which is None. Then you simply print out the content of values which should print None. Finally, you don't have any return statement and so your education function will always return None

CodePudding user response:

You need to assign the variables (lt12ratio, edu12ratio,edumt12ratio, educollegeratio) to values, not print.

If you want to print them, then you use print(value). Finally, you need to return the values variable.

This is how your function should be:

def education():
    total = sum (df["CHILDNM"])
    edult12 = df[['EDUC1','CHILDNM']].where(df['EDUC1'] == 1, 0)
    nlt12=sum( edult12["CHILDNM"])
    edu12 = df[['EDUC1','CHILDNM']].where(df['EDUC1'] == 2, 0)
    n12= sum( edu12["CHILDNM"])
    edumt12 = df[['EDUC1','CHILDNM']].where(df['EDUC1'] == 3, 0)
    nmt12=sum( edumt12["CHILDNM"])
    educollege = df[['EDUC1','CHILDNM']].where(df['EDUC1'] == 4, 0)
    ncollege = sum( educollege["CHILDNM"])
    lt12ratio = nlt12/total
    edu12ratio = n12 / total
    edumt12ratio = nmt12 / total
    educollegeratio = ncollege/total

    values = (lt12ratio, edu12ratio,edumt12ratio, educollegeratio)
    print(values)
    return values
  • Related