Python 函数详解
什么是函数?
函数是一段组织起来的、可重复使用的、用来实现单一或相关联功能的代码段。函数能提高应用的模块性和代码的重复利用率。
定义函数
在 Python 中,使用 def
关键字来定义函数。
def greet(name):
"""这是一个简单的问候函数"""
print(f"Hello, {name}!")
# 调用函数
greet("Cline") # 输出: Hello, Cline!
函数参数
函数可以接受参数,参数是传递给函数的值。
- 位置参数: 按照参数定义的顺序传递。
- 关键字参数: 通过参数名指定,顺序无关紧要。
- 默认参数: 如果调用函数时没有提供参数值,则使用默认值。
- 可变参数:
*args
: 接收任意数量的位置参数,打包成一个元组。**kwargs
: 接收任意数量的关键字参数,打包成一个字典。
def describe_pet(animal_type, pet_name="Doggy"): # 默认参数
print(f"I have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet("hamster", "Harry") # 位置参数
describe_pet(pet_name="Willy", animal_type="whale") # 关键字参数
describe_pet("cat") # 使用默认参数
def make_pizza(*toppings): # *args
print("\nMaking a pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
def build_profile(first, last, **user_info): # **kwargs
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key, value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('albert', 'einstein',
location='princeton',
field='physics')
print(user_profile)
# 输出: {'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}
返回值
函数可以使用 return
语句返回一个值。如果函数没有 return
语句,它默认返回 None
。
def add(x, y):
return x + y
result = add(5, 3)
print(result) # 输出: 8