Python函数中如何定义参数

一.位置参数:根据函数定义时的参数位置传递参数
#形参和实参的个数必须一致
def fun1():
   print("运行结果")
print("this is fun1(),no parameters")

fun1()

fun1(1)



def fun2(a,b):
   print("运行结果")
print("this is fun2(),two parameters ")
print("a=%d,b=%d"%(a,b))

#fun2()

#fun2(3)

#fun2(3,4)


二.关键字参数:函数调用时,通过“键-值”形式加以指定,清除了参数的顺序需求

#fun2(a=3,b=4)

#fun2(b=9,a=8)

#fun2(5,b=6)

#fun2(2,a=1)
说明前面的2也被赋值给a
#有位置参数时,位置参数必须在关键字参数前面
#fun2(a=1,2)


三.默认参数:为参数提供默认值,调用函数时可传可不传默认参数的值
#带有默认参数的函数定义时,要使位置参数在前,默认参数灾后

#def fun3(a=1,b):
   #print("运行结果")
#print("this is fun3(),two parameters ,a is default")
#print("a=%d,b=%d" % (a, b))

def fun4(a,b=3):
   print("运行结果")
print("this is fun4(),two parameters ,b is default")
print("a=%d,b=%d" % (a, b))

#fun4(10)

#fun4(7,4)

#fun4(a=0)

#fun4(b=0)


四.可变参数:当在定义函数时,还不能确定调用的时候会传递多少个参数

#包裹位置参数: 在函数内部被存放在以形参名为标识符的元组中
def fun5(*args):
   print("运行结果")
print("this is fun5(), variable parameter")
print(args)

#fun5(1)

#fun5(1,2)

#fun5(1,2,3)

#fun5(a=1,b=2)

#包裹关键字参数:参数在函数内部被存放在以形式名为标识符的dictionary中
def fun6(**kwargs):
   print("运行结果")
print("this is fun6(), variable parameter")
print(kwargs)

fun6(a=1)

fun6(a=1,b=2)

fun6(b=1,a=2,c=3)

fun6(1,2)



原文地址:https://www.cnblogs.com/quxikun/p/7489804.html