5200.8 Function
函数是一段可以用来执行特定任务的代码块,可以被复用。
使用 def 定义一个函数,使用函数名,调用一个函数。
def greet_user():
"""Display a simple greeting."""
print("Hello!")
greet_user()形参指的是定义的时候的参数,Parameters。
实参指的是调用的时候,传入的参数。Arguments
可以通过多种方式进行函数的传参:
- 位置
- 关键词
- 列表
- 字典
在定义函数的时候,可以使用默认值进行定义。
def describe_pet(pet_name, animal_type='dog'):
"""Display information about a pet."""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(pet_name='willie')定义参数的时候,可以用空值代表可选Parameters。