Skip to content

Python 函数的默认参数

在创建函数时,可以给形式参数设置默认值,这样在调用时可以省略实际参数,拥有默认值的形式参数必须在参数列表的末尾:

python
# 防御力默认为 0
def attack(attack_power:float, defense_power:float=0) -> None:
    # damage 是 attack 函数内的局部变量
    damage:float = attack_power * ( 1 - defense_power / (defense_power + 100))

    # 返回伤害
    return damage

print("伤害为", attack(100))        # 防御力不传递实际参数,使用默认值
print("伤害为", attack(100, 10))    # 防御力传递实际参数 10