Python 函数是编程中非常重要的组成部分,它们帮助我们组织代码、提高代码的复用性和模块化。
1. 简单函数定义与调用
def greet(name):
"""打印问候信息"""
print(f"Hello, {name}!")
# 调用函数
greet("Alice")
2. 函数参数
- 位置参数
def add_numbers(x, y):
"""返回两个数的和"""
return x + y
# 调用函数
result = add_numbers(5, 10)
print(result)
- 关键字参数
def describe_pet(animal_type, pet_name):
"""描述宠物的信息"""
print(f"I have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name}.")
# 调用函数
describe_pet(animal_type="hamster", pet_name="Harry")
- 默认参数值
def make_pizza(size=12, *toppings):
"""打印披萨的尺寸和配料"""
print(f"Making a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
# 调用函数
make_pizza(16, "pepperoni", "mushrooms", "extra cheese")
3. 可变参数
- 不定数量的位置参数 (
*args
)
def sum_all(*numbers):
"""计算所有传入数字的总和"""
total = 0
for number in numbers:
total += number
return total
# 调用函数
total_sum = sum_all(1, 2, 3, 4, 5)
print(total_sum)
- 不定数量的关键字参数 (
**kwargs
)
def build_profile(first, last, **user_info):
"""创建用户信息字典"""
user_info['first_name'] = first
user_info['last_name'] = last
return user_info
# 调用函数
user_profile = build_profile('albert', 'einstein', location='princeton', field='physics')
print(user_profile)
4. 返回值
def get_formatted_name(first_name, last_name):
"""返回整洁的名字"""
full_name = f"{first_name} {last_name}"
return full_name.title()
# 调用函数
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
5. 文档字符串 (Docstrings)
def square(number):
"""返回给定数字的平方"""
return number ** 2
# 打印函数的文档字符串
print(square.__doc__)
6. 内置函数和递归
def factorial(n):
"""返回 n 的阶乘"""
if n == 1:
return 1
else:
return n * factorial(n-1)
# 调用函数
print(factorial(5))