本节内容
- 函数
- 参数
- 作用域
注意事项:笔者使用的版本是 python3.5
1 函数(function)
先想一个问题:为什么需要函数?
1.1 创建函数
1 fibs = [0, 1]
2 for i in range(8)
3 fibs.append(fibs[-2] + fibs[-1])
4
5 #使用函数,使得代码灵活
6 def fibs(num):
7 result = [0, 1]
8 for i in range(num-2):
9 result.append(result[-2] + result[-1])
10 return result
定义函数需要有 def
但不需要有return,有的话也可以起结束作用
def test():
print ('Hello,follow me')
return #函数在这里就结束
print ('Ahhhh?')
如果需要传参数就往括号里加参数
1.2 文档化
如果给函数写文档,让其他人使用该函数能够理解,可以在def的另一行加”’ ”’,例如
def example():
'''
This is an example
'''
print ('Hello,example!')
>>> example.__doc__
'\n This is exmaple\n '
>>> help(example)
Help on function example in module __main__:
example()
This is exmaple
2 参数(parameter)
写在def语句中函数后面的变量通常叫作函数的形参
而调用函数的时候提供的值是实参
函数的值通过实参来获得,形参只是个该函数内的变量(参数存在局部作用域中)
可以理解实参的入口是形参
类别
- 位置参数
- 关键字参数
- 默认值
- 收集参数
def hello_l(greeting, name):
print ('%s.%s' % (greeting, name))
def hello_r(name, greeting):
print('%s.%s' %(name, greeting))
>>> hello_l('Hello','world')
Hello.world
>>> hello_r('Hello','world')
Hello.world
参数的顺序有时候很难记住,但可以提供函数的名字。这样一来,顺序就毫无印象
>>> hello_l(greeting='Hello',name='world')
Hello.world
关键字更厉害的地方是可以提供默认值
>>> hello(name='world',greeting='hello')
hello.world!
收集参数
问题:
def one(name):
print (name)
def two(*name):
print(name)
>>> one(10)
10
>>> two(12)
(12,) #这里是一个元组
def three(name, *name1):
print(name)
print(name1)
>>> three('parament',5,2,0)
parament
(5, 2, 0)
如果使用 ** 的参数呢?
def four(**name):
print(name)
>>> four(x=1,y=2,z=3)
{'z': 3, 'x': 1, 'y': 2}
返回的是字典,而不是元祖
结合着这些,可以做的事情就很多呢!