# Python函数定义及参数详解

## 函数定义

```#!/usr/bin/env python
#coding=utf-8
'''
Created on 2016年9月4日下午2:37:31
@author: Flowsnow
@file: D:/Workspaces/eclipse/HelloPython/main/FibonacciSeries.py
@function: 定义函数-输出给定范围内的斐波拉契数列
'''
def Fibonacci(n):
#print "success"
a=0
b=1
while a<n:
print a,
a,b=b,a+b
#call the function Fibonacci
Fibonacci(2000)
print '\n',
print Fibonacci
f=Fibonacci
f(100)
print '\n',
print Fibonacci(0)```

<!–more–>

```0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
<function Fibonacci at 0x000000000258D9E8>
0 1 1 2 3 5 8 13 21 34 55 89
None```

```#!/usr/bin/env python
#coding=utf-8
'''
Created on 2016年9月4日下午3:07:06
@author: Flowsnow
@function: 函数定义-返回斐波拉契数列，而不是直接打印
'''
def Fibonacci(n):
a=0
b=1
result=[]
while a<n:
result.append(a)
a,b=b,a+b
return result
result=Fibonacci(2000)
for x in result:
print x,```

## 参数详解

Python 的内建标准类型有一种分类标准是分为可变类型与不可变类型

• 可变类型：列表、字典
• 不可变类型：数字、字符串、元组

### 默认参数

```#!/usr/bin/env python
#coding=utf-8
'''
Created on 2016年9月5日下午2:50:12
@author: Flowsnow
@function: 测试默认参数的使用
'''
while True:
ok = raw_input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
if ok in ('n', 'no', 'nop', 'nope'):
return False
retries = retries - 1
if retries < 0:
raise IOError('refusenik user')
print complaint```

```ask_ok('OK to overwrite the file?')
ask_ok('OK to overwrite the file?', 2)
ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')
```

```i = 5
def f(arg=i):
print arg
i = 6
f()```

```def f(a, L=[]):
L.append(a)
return L
print f(1)
print f(2)
print f(3)```

```[1]
[1, 2]
[1, 2, 3]```

```def f(a, L=None):
if L is None:
L = []
L.append(a)
return L```

```[1]
[2]
[3]```

### 位置参数*args

```def argTest(arg1,*args):
print arg1
print('~start to print *args~')
for x in args:
print x,
argTest(1,'two',3)```

```1
~start to print *args~
two 3```

args被解释为包含多个变量的元组tuple。因此也可用如下写法：

```def argTest(arg1,*args):
print arg1
print('~start to print *args~')
for x in args:
print x,
#argTest(1,'two',3)
args=['two',3]
argTest(1,*args)```

### 关键字参数**kwargs

```def argTest(arg1,**kwargs):
print 'arg1',arg1
for key in kwargs:
print key,kwargs[key]
argTest(1,arg2='aa',arg3='bb')
argTest(arg1=1,arg2='aa',arg3='bb',arg4='cc')
arg={'arg2':'bb','arg3':'cc','arg4':'dd'}
argTest(arg1='ss',**arg)
argTest(arg1='ss',**arg)```

```arg1 1
arg2 aa
arg3 bb
arg1 1
arg2 aa
arg3 bb
arg4 cc
arg1 ss
arg2 bb
arg3 cc
arg4 dd
arg1 ss
arg2 bb
arg3 cc
arg4 dd```