Python 函数基础
函数是组织代码的基本单元,能够将逻辑封装起来重复使用。在 Python 中,定义函数使用 def 关键字,通过缩进界定函数体。
定义与调用
定义函数时,括号内列出参数(即使不需要参数,括号也必不可少),函数签名以冒号结束。文档字符串(docstring)用于描述函数作用,方便后续生成文档。
def greet_user():
"""显示简单的问候语"""
print("Hello!")
# 调用函数,无需额外信息,直接写空括号即可
greet_user()
向函数传递信息
位置实参
调用函数时,Python 将每个实参关联到对应的形参。最简单的关联方式是基于顺序的位置实参。
def describe_pet(animal_type, pet_name):
"""显示宠物的信息"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
# 实参顺序必须与形参一致
describe_pet("dog", "goushengzi")
关键字实参
关键字实参是名称 - 值对,无需考虑顺序,能清晰指出值的用途。
def describe_pet(animal_type, pet_name):
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
# 指定名称,顺序可打乱
describe_pet(animal_type="dog", pet_name="goushengzi")
describe_pet(pet_name="goushengzi", animal_type="dog")
默认值
为形参指定默认值可以简化调用。注意:,否则 Python 无法正确解读位置实参。

