【问题标题】:python: cannot get final returnpython:无法获得最终回报
【发布时间】:2013-11-08 10:45:07
【问题描述】:

声明:这是一个任务。我尝试了不同的组合来在我的代码中移动变量 [totalExposure] 以获得返回但失败了。 问题:利用递归求一段时间内的辐射暴露量。 问题:我可以正确地得到所有计算[我在在线python执行器中检查过]但是当过程到最终返回时,结果是[无]。我不知道为什么我的代码不能返回最终的计算结果。 希望:那里的一些大师可以给我一些线索谢谢。

global totalExposure
totalExposure=0 

def f(x):
    import math
    return 10*math.e**(math.log(0.5)/5.27 * x)

def radiationExposure(start, stop, step):

    time=(stop-start)
    newStart=start+step

    if(time!=0):
        radiation=f(start)*step
        radiationExposure(newStart, stop, step) 
        global totalExposure
        totalExposure+=radiation   
    else:
        return totalExposure

【问题讨论】:

  • 在递归调用之前添加returnreturn radiationExposure(newStart, stop, step)

标签: python return


【解决方案1】:

为了执行递归,您必须在radiationExposure 中返回调用:

return radiationExposure(newStart, stop, step)

【讨论】:

  • 哇,它又快又好听。问题解决了。非常感谢
  • 这里也不需要任何全局变量。
  • 很高兴知道如何做到这一点。事实上,我尝试不使用全局变量,但我无法获得累积的结果并且总是得到未绑定的错误。无论我在哪里移动 totalExposure 变量,它总是以初始化值开始,即 0。并返回最后一次递归的结果。在其他作业中,我对变量的范围也有同样的问题。
猜你喜欢
  • 2020-11-06
  • 2014-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多