简体   繁体   中英

Python: return statement still returns none from function

I've looked at all of the other "Returns none" questions on here and none of them seem to solve my problem.

rates = []
for date in unformatted_returns: # Please ignore undefined variables, it is redundant in this context
    if date[0] >= cutoff_date:
        date_i = unformatted_returns.index(date)
        r = date_initialize(date[0], date_i)
        print "r is returned as:", r
        rates.append(r)
        print date[0]
    else:
        continue

def date_initialize(date, date_i):
        print " initializing date configuration"
        # Does a bunch of junk
        rate_of_return_calc(date_new_i, date_i)

def rate_of_return_calc(date_new_i, date_i):
        r_new = unformatted_returns[int(date_i)] # Reverse naming, I know
        r_old = unformatted_returns[int(date_new_i)] # Reverse naming, I know
        if not r_new or not r_old:
            raise ValueError('r_new or r_old are not defined!!')
            # This should never be true and I don't want anything returned from here anyhow
        else:
            ror = (float(r_new[1])-float(r_old[1]))/float(r_old[1])
            print "ror is calculated as", ror
            return ror

The functions them selves work fine, the output is like so:

initializing date configuration
('2014-2-28', u'93.52')
ror is calculated as -0.142643284859
r is returned as: None
2015-2-2
>>> 

ror is the correct value, but why does it not get returned when I have it written right there return ror ?? Doesn't make any sense to me

You need to return it here too

def date_initialize(date, date_i):
        print " initializing date configuration"
        # Does a bunch of junk
        return rate_of_return_calc(date_new_i, date_i)

In date_initialize , you need to return the function that is returning the value that you want. Explicitly, change your call from

rate_of_return_calc(date_new_i, date_i)

to

return rate_of_return_calc(date_new_i, date_i)

Your first call, to date_initialize , does not return anything. Therefore, when you call rate_of_return_calc , you receive the value and then throw it away. You need to return it to pass the value along to your main function.

You need to return the value in date_initialize too:

def date_initialize(date, date_i):
    print " initializing date configuration"
    # Does a bunch of junk
    return rate_of_return_calc(date_new_i, date_i)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM