Python 为什么这个函数不返回值?
在Python中,函数默认返回Python 为什么这个函数不返回值?,python,function,recursion,Python,Function,Recursion,在Python中,函数默认返回None 缩进有问题,因此函数radio意外结束,随后的代码块被认为是独立的,不属于radio。要解决此问题,请按如下方式修复缩进: total=0 def f(x): import math return 10*math.e**(math.log(0.5)/5.27 * x) def radio(start,stop,step): time=stop-start newstart=start+step if time !=0:
None
缩进有问题,因此函数radio
意外结束,随后的代码块被认为是独立的,不属于radio
。要解决此问题,请按如下方式修复缩进:
total=0
def f(x):
import math
return 10*math.e**(math.log(0.5)/5.27 * x)
def radio(start,stop,step):
time=stop-start
newstart=start+step
if time !=0:
rad=f(start)*step
global total
total+=rad
radio(newstart,stop,step)
else:
return total
print radio(0, 5, 1)
print radio(5, 11, 1)
print radio(0, 11, 1)
print radio(40, 100, 1.5)
在python中,函数必须给出任何返回值,如果未指定返回值,则默认情况下返回
None
第一次调用radio function nothing时,它再次调用自身,因此未返回任何内容
为了避免这个问题,因为您使用的是递归调用,所以每个函数对另一个函数都有返回值,所以在调用同一个函数时使用return
def radio(start,stop,step):
time=stop-start
newstart=start+step
if time !=0:
rad=f(start)*step
global total
total+=rad
radio(newstart,stop,step)
else:
return total
输出:
total=0
def f(x):
import math
return 10*math.e**(math.log(0.5)/5.27 * x)
def radio(start,stop,step):
time=stop-start
newstart=start+step
if time !=0:
rad=f(start)*step
global total
total+=rad
return radio(newstart,stop,step)
else:
return total
print radio(0, 5, 1)
因为您正在调用显式不返回任何内容的
radio
函数,所以默认情况下它隐式返回None
。
39.1031878433