标签:
>>> def func():
... print("this is a func()")
...
>>> func()
this is a func()
多个参数:
>>> def add(a,b):
... print(a+b)
...
>>> add(3,5)
8
默认参数:
>>> def add(a,b=3):
... print(a+b)
...
>>> add(3,4)
7
>>> add(3)
6
不定长参数:
>>> def func1(*arg):
... print(arg)
... print(type(arg))
...
>>> func1(1,‘a‘,5)
(1, ‘a‘, 5)
<class ‘tuple‘>
>>> def func2(**arg):
... print(arg)
... print(type(arg))
...
>>> func2(a=1,b=4,name="xiaofan")
{‘b‘: 4, ‘name‘: ‘xiaofan‘, ‘a‘: 1}
<class ‘dict‘>
>>> def func2(*arg,**args):
... print(arg)
... print(type(arg))
... print(args)
... print(type(args))
...
>>> func2(‘a‘,1,2,3,x=1,y=10)
(‘a‘, 1, 2, 3)
<class ‘tuple‘>
{‘x‘: 1, ‘y‘: 10}
<class ‘dict‘>
>>> func2(‘a‘,1,2,3)
(‘a‘, 1, 2, 3)
<class ‘tuple‘>
{}
<class ‘dict‘>
>>> func2(x=1,y=10)
()
<class ‘tuple‘>
{‘x‘: 1, ‘y‘: 10}
<class ‘dict‘>
函数返回值:return
>>> def func0():
... return 1,2
...
>>> func0()
(1, 2)
>>> print(type(func0()))
<class ‘tuple‘>
>>> def func1(*arg,**args):
... return arg,args
...
>>>
>>> a,b=func1(1,2,3,x=1,y=2)
>>> a
(1, 2, 3)
>>> b
{‘x‘: 1, ‘y‘: 2}
>>>
显式修改函数返回值:
>>> def func1(*arg,**args):
... return list(arg),args
...
>>> a,b=func1(1,2,3,x=1,y=2)
>>> a
[1, 2, 3]
>>> b
{‘x‘: 1, ‘y‘: 2}
函数多态:
>>> def add(a,b):
... print(a+b)
...
>>> add(1,2)
3
>>> add("xaiofan","b")
xaiofanb
>>> add([1,2,3],[‘x‘,‘y‘,‘z‘])
[1, 2, 3, ‘x‘, ‘y‘, ‘z‘]
函数作用域:
>>> x = 1
>>> def f():
... x = 10
... print("it is inside x:",x)
...
>>> f()
it is inside x: 10
global语句的意义是用来在函数内部修改全局变量。
>>> x = 10
>>> def f1():
... global x
... x = 100
... print(x)
...
>>> f1()
100
>>> print(x)
100
标签:
原文地址:http://www.cnblogs.com/fanxuanhui/p/5836874.html