定义函数
def my_abs(x):#求绝对值的my_abs函数
  if x >= 0:
      return x
  else:
      return –x
def nop():#空函数
pass#占位符
参数检查
>>> my_abs(1, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: my_abs() takes exactly 1argument (2 given)#参数个数不对
>>> my_abs('A')#参数类型不对,无法检查
'A'
>>> abs('A')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs():'str'
>>> my_abs('A')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in my_abs
TypeError: bad operand type#错误的参数类型
返回多个值
Python的函数返回多值其实就是返回一个tuple
import math
def move(x, y, step, angle=0):
  nx = x + step * math.cos(angle)
  ny = y - step * math.sin(angle)
return nx, ny
>>> x, y = move(100, 100, 60,math.pi / 6)
>>> print x, y
151.961524227 70.0
函数的参数
def power(x):#计算x2的函数
return x * x
>>> power(5)
25
def power(x, n):#计算xn
    s = 1
    while n > 0:
        n = n - 1
        s = s * x
return s
def power(x, n=2): #第二个参数n的默认值设定为2
   s= 1
  while n > 0:
      n = n - 1
      s = s * x
  return s
默认参数降低了函数调用的难度,而一旦需要更复杂的调用时,又可以传递更多的参数来实现。无论是简单调用还是复杂调用,函数只需要定义一个。
def enroll(name, gender, age=6,city='Beijing'):
  print 'name:', name
  print 'gender:', gender
  print 'age:', age
  print 'city:', city
enroll('Bob', 'M', 7)# 与默认参数不符的学生才需要提供额外的信息
enroll('Adam', 'M', city='Tianjin')
有多个默认参数时,调用的时候,既可以按顺序提供默认参数,比如调用enroll('Bob', 'M', 7),意思是,除了name,gender这两个参数外,最后1个参数应用在参数age上,city参数由于没有提供,仍然使用默认值。
默认参数的误区
def add_end(L=[]):#传入一个list
  L.append('END')#添加一个END再返回
  return L
>>> add_end([1, 2, 3])
[1, 2, 3, 'END']
>>> add_end(['x', 'y', 'z'])
['x', 'y', 'z', 'END']
>>> add_end()
['END']
>>> add_end()
['END', 'END']
>>> add_end()
['END', 'END', 'END']
Python函数在定义的时候,默认参数L的值就被计算出来了,即[],因为默认参数L也是一个变量,它指向对象[],每次调用该函数,如果改变了L的内容,则下次调用时,默认参数的内容就变了,不再是函数定义时的[]了。所以,定义默认参数要牢记一点:默认参数必须指向不变对象!要修改上面的例子,我们可以用None这个不变对象来实现:
def add_end(L=None):
  if L is None:
      L = []
  L.append('END')
return L
可变参数
def calc(numbers):#计算a2 + b2 +c2 + ……
  sum = 0
  for n in numbers:
      sum = sum + n * n
  return sum#调用时,要先组装list或tuple
>>> calc([1, 2, 3])
14
def calc(*numbers):#函数的参数改为可变参数
  sum = 0
  for n in numbers:
      sum = sum + n * n
  return sum
>>> calc(1, 2, 3)
14
>>> nums = [1, 2, 3]#已有list或tuple,调用可变参数
>>> calc(*nums)
14
关键字参数
关键字参数允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict
def person(name, age, **kw):#函数除必选参数name和age,还接受关键字参数kw
  print 'name:', name, 'age:', age, 'other:', kw
>>> person('Michael', 30)#调用函数时,可以只传入必选参数
name: Michael age: 30 other: {}
>>> person('Bob', 35,city='Beijing')#可传入任意个数的关键字参数
name: Bob age: 35 other: {'city':'Beijing'}
>>> kw = {'city': 'Beijing','job': 'Engineer'}#组装出一个dict
>>> person('Jack', 24, **kw)#把dict转换为关键字参数传进去
name: Jack age: 24 other: {'city': 'Beijing','job': 'Engineer'}
参数组合
def func(a, b, c=0, *args, **kw):#必选参数、默认参数、可变参数和关键字参数
print 'a =', a,'b =', b, 'c =', c, 'args =', args, 'kw =', kw
>>> func(1, 2)# 自动按照参数位置和参数名把对应的参数传进去
a = 1 b = 2 c = 0 args = () kw = {}
>>> func(1, 2, c=3)
a = 1 b = 2 c = 3 args = () kw = {}
>>> func(1, 2, 3, 'a', 'b')
a = 1 b = 2 c = 3 args = ('a', 'b') kw = {}
>>> func(1, 2, 3, 'a', 'b', x=99)
a = 1 b = 2 c = 3 args = ('a', 'b') kw ={'x': 99}
>>> args = (1, 2, 3, 4)#tuple和dict,也可以调用该函数
>>> kw = {'x': 99}
>>> func(*args, **kw)
a = 1 b = 2 c = 3 args = (4,) kw = {'x':99}
对于任意函数,都可以通过类似func(*args, **kw)的形式调用它,无论它的参数是如何定义的。
递归函数
一个函数在内部调用自身本身,这个函数就是递归函数。
fact(n) = n! = 1 x 2 x 3 x ... x (n-1) x n= (n-1)! x n = fact(n-1) x n
def fact(n):#fact(n) = n! = fact(n-1) x n
  if n==1:
      return 1
return n *fact(n - 1)
使用递归函数需要注意防止栈溢出。在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出。如:
>>> fact(1000)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in fact
 ...
File "<stdin>", line 4, in fact
RuntimeError: maximum recursion depthexceeded
解决递归调用栈溢出的方法是通过尾递归优化,在函数返回的时候,调用自身本身,并且,return语句不能包含表达式。这样,编译器或者解释器就可以把尾递归做优化,使递归本身无论调用多少次,都只占用一个栈帧,不会出现栈溢出的情况.即:
def fact(n):
  return fact_iter(1, 1, n)
def fact_iter(product, count, max):
  if count > max:
      return product
  return fact_iter(product * count, count + 1, max)
