默认值参数
- 形参设定默认值 称为 默认参数。调用函数时,可以使用比定义时更少的参数。
- 调用函数时,如果没有传入默认参数对应的实参,则实参使用默认值
- 默认参数在调用的时候可以不传递,也可以传递 ```python def say_hello(name=’林青霞’):# 形参 “”” 给女神打招呼 :param name: :return: “”” print(‘hello ‘, name)
调用时不传递参数,使用默认值
say_hello()
调用时传递参数
say_hello(‘高圆圆’)
注意::::warning默认参数一定要在参数的最后:::```pythondef say_hello(score, name='林青霞'):# 默认参数放在参数最后面"""给女神打招呼:param name::return:"""print('hello %s'%(name))say_hello(60, '高圆圆')
关键字参数
- 调用函数时,实参可以指定对应的形参,称为 关键字参数 ```python def say_hello(name, age, score): print(‘姓名:%s,年纪:%d,分数:%f’%(name,age,score))
say_hello(name=’林青霞’,age=60,score=70.5)
- 使用关键字参数调用可以**改变传递参数的顺序**```python# 改变参数传递的顺序say_hello(score=70,age=30,name='高圆圆')
练习-根据需要创建用户
根据需要创建对象是很常见的需求,在一个函数中,我们可以保留一些默认配置,然后根据需要进行修改。
例如,我们有一个创建用户的函数create_user,参数如下
username(用户名)必填password(密码) 必填is_admin(是否是管理员)可选,默认为Falseis_active(是否已激活)可选,默认为Trueis_verified(是否已验证)可选,默认为False需求
声明一个函数,实现根据需求create_user创建用户,打印用户的创建用户用到的参数。使其支持如下方式的代码调用:create_user("john", "password")create_user("jane", "password123", is_admin=True)create_user("alice", "pass123", is_active=False, is_verified=True)
代码
```python def create_user(username, password, is_admin=False, is_active=True, is_verified=False):创建用户的逻辑
print(“Creating user…”) print(“Username:”, username) print(“Password:”, password) print(“Is Admin:”, is_admin) print(“Is Active:”, is_active) print(“Is Verified:”, is_verified) print(“User created successfully.”)
示例用法
create_user(“john”, “password”) create_user(“jane”, “password123”, is_admin=True) create_user(“alice”, “pass123”, is_active=False, is_verified=True) ```
