1.函数结构
def MyFunction():
代码块
def MyFunction(name): #带一个参数的函数
print(name+'2333')
MyFunction('Amy')
Amy2333
def add(num1,num2): #带两个参数的函数
return (num1+num2) #括号可有可无
print(add(2,3))
5
2.形参parameter,实参argument
形参:函数定义过程中
实参:传递的具体参数值
3.函数文档
def MyFunction():
'这里是函数文档'
#这里是注释
print('2333')
MyFunction._doc_ #打印函数文档,属性._doc_
'这里是函数文档'
4.关键字参数
def MyFunction(fir,sec):
print(fir + '->' + sec)
MyFunction(fir='第一个',sec='第二个') #关键字参数,指定参数,避免顺序错误的问题
第一个->第二个
5.默认参数
def test(fir='aaa',sec='bbb') #默认参数
print(fir+'->'+sec)
test() #直接打印默认参数
aaa->bbb
test('ccc') #如果传递其他实参,则会打印实参而不是默认参数
ccc->bbb
6.收集参数,可变参数
def test(*params):
print('the length of parameters is ',len(params));
print('the second parameter is ',params[1]);
test(1,2,3,4,5,6,7)
the length of parameters is 7
the second parameter is 2
def test2(*params,exp=8): #如果有不是收集参数的参数,请设定为默认参数避免出错
print('the length of parameters is ',len(params),exp);
test(1,2,3,4,5,6,7)
the length of parameters is 7,8
注:本文章是根据小甲鱼的学习视频所写的笔记,侵删。