Python
Python的第十四天-----函数的各种参数
一、函数的定义、调用
1、def sayhi (name,age): # sayhi :参数名 , ()内可以传参,name、age是形参
print(f"hello,my name in {name},I am is {age} years old")
print("lalala")
sayhi("alex",22) # 函数的调用 ,"alex",22 是实参
2、默认参数
def stu_register(name,age,course,country="china"): #如果不输入国籍,默认国籍是China
print("--------学生注册信息-------")
print("姓名:",name)
print("年龄:",age)
print("课程:",course)
print("国籍:",country)
stu_register("alex",22,"python") 实参与形参是一一对应的:位置参数
stu_register("jack",21,"python",country="us")
stu_register("rain",22,"python","us")
3、关键参数(指定参数)
stu_register("rain",age=22,course="python",country="us")
注:关键参数要放在位置参数之后
4、非固定参数
若在函数定义时不确定输入多少个参数,就可以使用非固定参数
def stu_register(name,age,course,*args): #args:会把多传入的参数变成一个元组的形式
print(name,age,course,args)
stu_register("alex",22,"python","m","girl")
alex 22 python ('m', 'girl')
def stu_register(name,age,course,*args,**kwargs): #**kwargs:会把多传入的参数变成一个字典的形式
print(name,age,course,args,kwargs)
stu_register("alex",22,"python","m","girl",hobby="eat",hometown="河北保定")
alex 22 python ('m', 'girl') {'hobby': 'eat', 'hometown': '河北保定'}
练习:
def print_info(**kwargs):
print("---------info---------")
print("Name:",kwargs.get("name")) dict中取value值,若不存在不会报错,显示None.而kwargs["name"],若不存在会报错
print("Age:",kwargs.get("age"))
print("Sex:",kwargs.get("sex"))
print("hobbie:",kwargs.get("hobbie"))
print_info(name="alex",age=22,sex="M",hobbie="大保健")
print_info(name="jack",age=26,sex="M",hobbie="学习")
---------info---------
Name: alex
Age: 22
Sex: M
hobbie: 大保健
---------info---------
Name: jack
Age: 26
Sex: M
hobbie: 学习