Python | 参数类型

python中有以下类型的参数:

  1. 必要参数

  2. 默认参数

  3. 关键字/命名参数

  4. 可变长度参数

1)必要参数

如果我们在python中使用参数定义函数,则在调用该函数时-必须发送这些参数,因为它们是必需参数。

# 必填参数
def show(id,name):
    print("Your id is :",id,"and your name is :",name)

show(12,"deepak")
# show() #error
# show(12) #error

输出结果

Your id is : 12 and your name is : deepak

2)默认参数

如果我们将参数定义为默认参数,则即使您不传递参数或传递较少的参数,也不会发生任何错误。

# 默认参数
def show(id="<no id>",name="<no name>"):
    print("Your id is :",id,"and your name is :",name)

show(12,"deepak")
show()
show(12)

输出结果

Your id is : 12 and your name is : deepak
Your id is : <no id> and your name is : <no name>
Your id is : 12 and your name is : <no name>

3)关键字/命名参数

Python具有动态类型–因此,如果我们以错误的顺序发送参数,由于动态类型,它将接受值。但是,此数据不正确,因此为了防止这种情况,我们使用关键字/命名参数。

# 关键字/命名参数
def show(id="<no id>",name="<no name>"):
    print("Your id is :",id,"and your name is :",name)

# 预设/正确顺序 	
show(12,"deepak")
# 关键字顺序
# 无需记住参数序列
# 提供带有名称/参数名称的值
show(name="priya",id=34)

输出结果

Your id is : 12 and your name is : deepak
Your id is : 34 and your name is : priya

4)可变长度参数

通过使用* args,我们可以将任意数量的参数传递给python中的函数。

# 可变长度参数 
def sum(*data):
    s=0
    for item in data:
       s+=item
    print("Sum :",s)

sum()
sum(12)
sum(12,4)
sum(12,4,6)
sum(1,2,3,4,5,6,7,8)
sum(12,45,67,78,90,56)

输出结果

Sum : 0
Sum : 12
Sum : 16
Sum : 22
Sum : 36
Sum : 348