‘’’ 形式参数:指的是函数创建和定义过程中小括号里面的参数 实际参数:指的是函数在调用时传递进去的参数 ‘’’ #函数文档 ‘’’ 给函数写文档是为了更加的容易理解函数,类似于注释
def MyfirstFunction(name): ‘函数定义过程中的name是叫形式参数’ #因为它至少一个形式,表示占据一个参数位置 print(‘传递进来的’ + name + ‘叫做实际参数,因为它是具体的参数值!’)
MyfirstFunction(‘lq’)
传递进来的 lq 叫做实际参数,因为它是具体的参数值!
查看注释:
MyfirstFunction.doc
‘函数定义过程中的name是叫形式参数’
也可使用print查看文档
print.doc “print(value, …, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)\n\nPrints the values to a stream, or to sys.stdout by default.\nOptional keyword arguments:\nfile: a file-like object (stream); defaults to the current sys.stdout.\nsep: string inserted between values, default a space.\nend: string appended after the last value, default a newline.\nflush: whether to forcibly flush the stream.”
‘’’
#关键字参数 ‘’’
def SaySome(name,words): print(name + ‘->’ + words)
SaySome(‘Jane’,‘girl’) Jane->girl
指定参数
SaySome(words=‘Jane’,name=‘girl’) girl->Jane
‘’’
#默认参数 ‘’’ 在定义时赋值
def SaySome(name=‘nice’,words=‘girls’): print(name + ‘->’ + words)
直接调用函数,不带参数,运行如下:
SaySome() nice->girls
给他一个参数,运行如下:
SaySome(‘Many’) Many->girls
SaySome(‘Many’,‘girls and boys’) Many->girls and boys
‘’’
#收集参数(也称可变参数,原因解决函数需要多个参数) ‘’’
def test(*params): print(‘参数的长度是:’,len(params)); print(‘第二个参数是:’,params[1]);
test(1,‘你好’,3.14,5,6,7,8) 参数的长度是: 7 第二个参数是: 你好
##形参前面加 * 号 为收集参数 把标志为收集参数的参数用元组打包起来,放到params的元组名字中去。 如果收集参数需要加其他定制的参数,在调用函数时需要使用关键字参数来定制,否则会把后面的参数全部列为收集参数的范畴
例:
def test (*params,exp): print(‘参数的长度是:’,len(params),exp); print(‘第二个参数是:’,params[1]);
test(1,‘你好’,3.14,5,6,7,8) Traceback (most recent call last): File “<pyshell#35>”, line 1, in test(1,‘你好’,3.14,5,6,7,8) File “<pyshell#34>”, line 2, in test print(‘参数的长度是:’,len(params),exp); NameError: name ‘exp’ is not defined
需要使其正常运行则需要如下添加
test(1,‘你好’,3.14,5,6,7,exp = 8) 参数的长度是: 6 8 第二个参数是: 你好
##print本身就有一个收集参数 print(*objects)
