5.1 函数定义
函数定义语法:
def 函数名([参数列表]):
▢‘’‘注释’‘’
▢函数体
注意事项:
1.函数形参不需要声明其类型,也不需要指定函数返回值类型
2.即使该函数不需要接受任何参数,也必须保留一对空的圆括号
3.括号后面的冒号必不可少
4.函数体相对于def关键字必须保持一定的空格缩进
5.Python允许嵌套定义函数(尽量避免嵌套)
生成斐波那契数列的函数定义和调用
>>> def fib(n):
... a,b = 0,1
... while a>> fib(100)
0 1 1 2 3 5 8 13 21 34 55 89
>>>
>>>
>>> def fib(n):
... a,b = 1,1
... while a>> fib(100)
1 1 2 3 5 8 13 21 34 55 89
>>> def func():
... print(func.x) #查看函数func的成员x
...
>>> func() #目前还没有成员x,出错
Traceback (most recent call last):
File "", line 1, in
File "", line 2, in func
AttributeError: 'function' object has no attribute 'x'
>>> func.x = 3 #动态为函数增加新成员
>>> func()
3
>>> func.x
3
>>> del func.x
>>> func.x
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'function' object has no attribute 'x'
>>> dunc()
Traceback (most recent call last):
File "", line 1, in
NameError: name 'dunc' is not defined
>>> def addOne(a):
... print(id(a),' : ',a)
... a+=1
... print(id(a),' : ',a)
...
>>> v = 3
>>> id(v)
140709150224704
>>> addOne(v)
140709150224704 : 3
140709150224736 : 4
>>> v
3
>>> id(v)
140709150224704
列表、字典、集合内的数据是可变的~
>>> def modify(v): #修改列表元素的值
... v[0] = v[0] + 1
...
>>> a = [2]
>>> modify(a)
>>> a
[3]
>>> def modify(v,item): #为列表增加元素
... v.append(item)
...
>>> a = [2]
>>> modify(a,3)
>>> a
[2, 3]
>>> def modify(d): #修改字典元素或为字典增加元素
... d['age'] = 38
...
>>> a = {'name':'Dong','age':37,'sex':'Male'}
>>> modify(a)
>>> a
{'name': 'Dong', 'age': 38, 'sex': 'Male'}
5.3 参数类型
>>> def test(x:int,y:int) -> int:
... '''x and y must be integers,return an integer x+y'''
... assert isinstance(x,int),'x must be integer'
... assert isinstance(y,int),'y must be integer'
... z = x+y
... assert isinstance(z,int),'z must be integer'
... return z
...
>>> test(1,2)
3
>>> test(1,3.0) #类型不符合,assert函数会抛出异常
Traceback (most recent call last):
File "", line 1, in
File "", line 4, in test
AssertionError: y must be integer
>>> def demo(a,b,c):
... print(a,b,c)
...
>>> demo(1,2,3)
1 2 3
>>> demo(1,2,3,4)
Traceback (most recent call last):
File "", line 1, in
TypeError: demo() takes 3 positional arguments but 4 were given
5.3.1 默认值参数
>>> def say(message,time = 1):
... print(message * time)
...
>>> say('hello')
hello
>>> say('6',6)
666666
>>> def join(List,sep = None):
... return (sep or ' ').join(List)
...
>>> aList = ['a','b','c']
>>> join(aList)
'a b c'
>>> join(aList,',')
'a,b,c'
>>> def demo(newitem,old_list = []):
... old_list.append(newitem)
... return old_list
...
>>> print(demo('5',[1,2,3,4]))
[1, 2, 3, 4, '5']
>>> print(demo('aaa',['a','b']))
['a', 'b', 'aaa']
>>> print(demo('a'))
['a']
>>> print(demo('b'))
['a', 'b']
这是为什么呢?
def demo(newitem,old_list = None): #如果是空值
if old_list is None: #则给他创建一个空列表
old_list = []
new_list = old_list[:] #把一个切片赋给new_list
new_list.append(newitem)
return new_list
print(demo('5'),[1,2,3,4])
print(demo('aaa',['a','b']))
print(demo('a'))
print(demo('b'))
['5'] [1, 2, 3, 4]
['a', 'b', 'aaa']
['a']
['b']
>>> i = 3
>>> def f(n = i): #参数n的值仅取决于i的当前值
... print(n)
...
>>> f()
3
>>> i = 5 #函数顶以后修改i的值不影响参数n的默认值
>>> f()
3
>>> f.__defaults__ #查看函数默认值参数的值不影响参数n的默认值
(3,)