【问题标题】:Python: return statement still returns none from functionPython:return 语句仍然没有从函数返回
【发布时间】:2015-06-11 19:55:00
【问题描述】:

我已经查看了此处的所有其他“不返回”问题,但似乎没有一个可以解决我的问题。

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

它们本身的功能工作正常,输出是这样的:

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

ror 是正确的值,但是为什么当我把它写在那里return ror 时它没有被返回??对我来说没有任何意义

【问题讨论】:

  • 您的date_initialize 函数中没有return。因此它隐式返回 None。
  • 更不用说由于第 5 行代码会产生的语法错误。
  • Still @McLean :如果您发布代码,它应该没有语法错误。俗话说:当你在罗马,做罗马人。
  • @csharpcoder 我一定是在缩进所有内容时不小心删除了括号,因为它永远不会按照应有的方式复制。我的错。

标签: python function return


【解决方案1】:

这里也需要退货

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)

【讨论】:

    【解决方案2】:

    date_initialize 中,您需要返回返回所需值的函数。明确地,将您的呼叫从

    rate_of_return_calc(date_new_i, date_i)
    

    return rate_of_return_calc(date_new_i, date_i)
    

    您对date_initialize 的第一次调用没有返回任何内容。因此,当您调用rate_of_return_calc 时,您会收到该值,然后将其丢弃。您需要将其返回以将值传递给您的主函数。

    【讨论】:

      【解决方案3】:

      你还需要返回 date_initialize 中的值:

      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)
      

      【讨论】:

        猜你喜欢
        • 2011-10-26
        • 1970-01-01
        • 1970-01-01
        • 2011-06-06
        • 1970-01-01
        • 2011-10-02
        相关资源
        最近更新 更多