Python 函数精讲:定义、参数、返回值与高级用法实例

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))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值