python里面的函数
函数定义
def my_abs(x):if x >= 0:return xelse:return -x
如果没有return
语句,函数执行完毕后也会返回结果,只是结果为None
。
return None
可以简写为return
。
...
的提示。函数定义结束后需要按两次回车重新回到>>>
提示符下。
空函数
如果想定义一个什么事也不做的空函数,可以用pass
语句:
def nop():pass
pass
语句什么都不做,那有什么用?实际上pass
可以用来作为占位符,比如现在还没想好怎么写函数的代码,就可以先放一个pass
,让代码能运行起来。
pass
还可以用在其他语句里,比如:
if age >= 18:pass
缺少了pass
,代码运行就会有语法错误。
返回多个值
比如在游戏中经常需要从一个点移动到另一个点,给出坐标、位移和角度,就可以计算出新的新的坐标:
import mathdef move(x, y, step, angle=0):nx = x + step * math.cos(angle)ny = y - step * math.sin(angle)return nx, ny
import math
语句表示导入math
包,并允许后续代码引用math
包里的sin
、cos
等函数。
然后,我们就可以同时获得返回值:
>>> x, y = move(100, 100, 60, math.pi / 6)
>>> print(x, y)
151.96152422706632 70.0
但其实这只是一种假象,Python函数返回的仍然是单一值:
>>> r = move(100, 100, 60, math.pi / 6)
>>> print(r)
(151.96152422706632, 70.0)
原来返回值是一个tuple!但是,在语法上,返回一个tuple可以省略括号,而多个变量可以同时接收一个tuple,按位置赋给对应的值,所以,Python的函数返回多值其实就是返回一个tuple,但写起来更方便。
默认参数
def repeat_str(s, times = 1):
repeated_strs = s * times
return repeated_strs
repeated_strings = repeat_str("Happy Birthday!")
print(repeated_strings)
repeated_strings_2 = repeat_str("Happy Birthday!" , 4)
print(repeated_strings_2)
#不能在有默认参数后面跟随没有默认参数
#f(a, b =2)合法
#f(a = 2, b)非法
#关键字参数: 调用函数时,选择性的传入部分参数
def func(a, b = 4, c = 8):
print('a is', a, 'and b is', b, 'and c is', c)
func(13, 17)
func(125, c = 24)
func(c = 40, a = 80)