问题描述:下面这段函数,返回值为什么是None?
def complex_function(x):
if x > 0:
if x % 2 == 0:
return "x 是正数且为偶数"
else:
if x % 2 == 0:
return "x 是正数但不是偶数"
else:
return "x 是非正数"
result = complex_function(5)
print(result)
建议这样写:
def complex_function(x):
if x > 0:
if x % 2 == 0:
return "x 是正数且为偶数"
else:
return "x 是正数但不是偶数"
else:
return "x 是非正数"
result = complex_function(5)
print(result)
在Python中,return语句会导致函数立即退出,因此,在else块中,如果包含if语句并不会以你的工作方式,如果你想根据条件返回不同的值,你应该直接在if
语句中使用return
语句。
def get_value(condition):
if condition:
return "True case"
else:
if some_other_condition:
return "Other condition met"
else:
return "False case"
在这个例子中,如果condition
为真,则返回"True case"
。如果condition
为假且some_other_condition
为真,则返回"Other condition met"
。如果两个条件都不满足,则返回"False case"
。
def get_value(condition):
if condition:
return "True case"
elif some_other_condition:
return "Other condition met"
else:
return "False case"
return:
1、return语句就是把执行结果返回到调用的地方,并把程序的控制权一起返回程序运行到所遇到的第一个return即返回(退出def块),不会再运行第二个return。
def haha(x,y):
if x==y:
return x,y
print(haha(1,1))
2、但是也并不意味着一个函数体中只能有一个return 语句,例如:
def test_return(x):
if x > 0:
return x
else:
return 0
print(test_return(2))
3、函数没有 return,默认 return一个 None 对象。
递归函数中没有return 的情况:
分析:else 中没有 return 就没有出口,这个程序是自己内部运行,程序没有返回值,
def recurve(a,b):
if a%b==0:
return b
else:
gcd(b,a%b)
4、
在交互模式下,return的结果会自动打印出来,而作为脚本单独运行时则需要print函数才能显示。
python中什么是交互模式:结尾有3个>符号(>>>)。>>>被叫做Python命令提示符(prompt)
输入一行python代码就会执行该代码,这种模式就叫做Python交互模式(interactive mode)
5、默认情况下,遇见 return 函数就会返回给调用者,但是 try,finally情况除外:
def func():
try:
print(666)
return 'ok'
finally:
print(666)
print(func())
6、函数作为返回值返回:(其实是个闭包函数)
def sum1(*args):
def sum2():
x=0
for i in args:
x=x+i
return x
return sum2
sum1(1,2,3)
a=sum1(1,2,3)
print(a())
结果:6=1+2+3
7、返回一个函数列表:
def count():
fs = []
for i in range(1,4):
def f():
return i*i
fs.append(f)
return fs
f1, f2, f3 = count()
print(f1())
print(f2())
print(f3())
输出:
9
9
9