return 语句就是讲结果返回到调用的地方,并把程序的控制权一起返回
程序运行到所遇到的第一个return即返回(退出def块),不会再运行第二个return。
要返回两个数值,写成一行即可:
def a(x,y): if x==y: return x,y print a(3,3)<br><br>>>> 3,3
但是也并不意味着一个函数体中只能有一个return 语句,例如:
def test_return(x): if x > 0: return x else: return 0
函数没有 return,默认 return一个 None 对象。
递归函数中没有return 的情况:
def gcd(a,b): if a%b==0: return b else: gcd(b,a%b)
分析:else 中没有 return 就没有出口,这个程序是自己内部运行,程序没有返回值,
python 和 print 的区别:
x = 1 y = 2 def add (x, y): z = x + y return z print (add(x,y) x = 1 y = 2 def add (x, y): z = x + y print z print (add(x,y))
在交互模式下,return的结果会自动打印出来,而作为脚本单独运行时则需要print函数才能显示。