1、创建函数,使用def 开头
>>> def hello(name):
... return 'hello ' + name
...
>>> print hello('yilia') # 调用
hello yilia
2、callable判断函数是否可以调用
>>> import math
>>> x = 1
>>> y = math.sqrt
>>> callable(x)
False
>>> callable(y)
True
3、记录函数
如果在函数的开头写下字符串,它就会在哦位函数的一部分进行存储,这成为文档字符串
>>> def square(x):
... 'calculates the square of the number x'
... return x*x
...
>>> square.__doc__ # 调用
'calculates the square of the number x'
>>> help(square) # 内建函数help, 进入help后输出q退出
Help on function square in module __main__:
square(x)
calculates the square of the number x
(END)
4、 作用域
例1: x =1
print 'x = ', x
def foo():
x = 42
foo()
print 'foo x = ', x
输出: x值不发生变化
x = 1
foo x = 1
例2: >>> def try_to_rename(n):
... n = 'Mrs. yan'
...
>>> name = 'yilia'
>>> print try_to_rename(name) #无返回值
None
>>> name # name的值不变
'yilia'
注:字符串(以及数字和元组)是不可以变的,即无法被修改(也就是说只能用心的值覆盖)
例3: >>> def change(n):
... n[0]='Mr.Gumby'
...
>>> name = ['Mr. Entity', 'Mr. Thing']
>>> change(name)
>>> name # 数组发生变化
['Mr.Gumby', 'Mr. Thing']
注:当两个参数同时引用同一个列表时,它们的确是同时引用一个列表
>>> name = ['Mr. Entity', 'Mr. Thing']
>>> n = name
>>> n[0] = 'yilia'
>>> name
['yilia', 'Mr. Thing']
>>> n
['yilia', 'Mr. Thing']
-------------区别------------------------------------------------------------
>>> x = 5
>>> y = x
>>> y =3
>>> x # x的值不变
5
>>> y
3
注:避免上面的情况出现,可以复制一个副本
>>> name = ['Mr. Entity', 'Mr. Thing']
>>> n = name[:]
>>> n is name
False
>>> n == name
True
>>> n[0] = 'yilia'
>>> n
['yilia', 'Mr. Thing']
>>> name
['Mr. Entity', 'Mr. Thing']
>>> change(name[:]) # 调用参数的副本,则原始的列表是安全的
>>> name
['Mr. Entity', 'Mr. Thing']
例4 >>> me = 'Magnus Lie Hetland'
>>> storage = {}
>>> storage['first'] = {}
>>> storage['middle'] = {}
>>> storage['last'] = {}
>>> storage # 字典是无序的
{'middle': {}, 'last': {}, 'first': {}}
>>> storage['first']['Magnus']=[me]
>>> storage['middle']['Lie']=[me]
>>> storage['last']['hetland']=[me]
>>> storage
{'middle': {'Lie': ['Magnus Lie Hetland']}, 'last': {'hetland': ['Magnus Lie Hetland']}, 'first': {'Magnus': ['Magnus Lie Hetland']}}
5、关键字参数和默认值
>>> def hello(greet, name):
... print('%s, %s!', greet, name) # 当前print格式不对,参考hello_2中的print
...
>>> hello('hello', 'yilia') # 调用hello函数
('%s, %s!', 'hello', 'yilia')
>>> def hello_2(greet, name):
... print '%s, %s' %(greet, name)
...
>>> hello_2('hello', 'world') # 调用hello_2函数
hello, world
>>> def hello_3(name='yilia', greet='hello'): #参数带有默认值的函数定义
... print '%s, %s' %(greet, name)
...
>>> hello_3('yilia','hello')
hello, yilia
6、收集参数
函数定义中可以让用户提供任意数量的参数, *的意思就是"收集其余的位置参数"
>>> def print_params(*params):
... print params
...
>>> print_params('a')
('a',)
>>> print_params('a','b')
('a', 'b')
** 能处理关键字参数的“收集”操作
>>> def print_params_2(data, **params):
... print data
... print params
...
>>> print_params_2('print', 'a') # 调用报错
>>> print_params_2('print', a =1) # 正确调用方法, 返回字典
print
{'a': 1}
7、字典和元组作为参数的另一种表示方法
>>> def add(x, y):
... return x+y
...
>>> params=(1,2)
>>> add(*params)
3