Python精选200Tips:51-60


一文读懂、会写Python中的函数
运行系统:macOS Sonoma 14.6.1
Python编译器:PyCharm 2024.1.4 (Community Edition)
Python版本:3.12

往期链接:

1-5 6-10 11-20 21-30 31-40
41-50

在 Python 中,函数是组织、重用代码的重要工具。函数使得代码更加模块化、易于维护和理解。以下是关于 Python 函数的详细解释,包括其基本结构、参数类型、返回值、作用域及其他高级特性。

051 基本结构

def function_name(parameters):
    """函数文档字符串(可选)"""
    # 函数体
    return value  # 可选返回值
  • 定义:使用 def 关键字定义函数。
  • 函数名:遵循命名规则,通常使用小写字母和下划线。
  • 参数:函数可以接受零个或多个参数。
  • 文档字符串:可选的描述,使用三重引号括起来,方便用户理解函数的用途。
  • 返回值:使用 return 语句返回结果,若没有返回值,则默认返回 None。
# 完整函数写法示例
def multiply(a: float, b: float) -> float:
    """
    返回 a 和 b 的乘积。
    参数:
    a (float): 第一个乘数。
    b (float): 第二个乘数。
    返回:
    float: a 和 b 的乘积。
    异常:
    TypeError: 如果 a 或 b 不是数字,将抛出异常。
    """
    if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
        raise TypeError("a 和 b 必须是数字。")
    return a * b

# 示例调用
result = multiply(3, 4)
print(result)  # 输出: 12

052 参数类型

  1. 位置参数:按位置传递的参数
def describe_person(name: str, age: int, city: str) -> str:
    """
    描述一个人的信息。
    参数:
    name (str): 姓名。
    age (int): 年龄。
    city (str): 所在城市。
    返回:
    str: 描述信息。
    """
    return f"{
     name} is {
     age} years old and lives in {
     city}."

# 示例调用
description1 = describe_person("Alice", 30, "New York")
print(description1)  # 输出: Alice is 30 years old and lives in New York.

# 参数顺序改变
description2 = describe_person(30, "Alice", "New York")
print(description2)  # 输出: 30 is Alice years old and lives in New York.

# 带上参数名可以改变参数顺序
description3 = describe_person(age=30, name="Alice", city="New York")
print(description3)  # 输出: Alice is 30 years old and lives in New York.
  1. 默认参数:可以为参数指定默认值
def create_user(username: str, email: str, is_active: bool = True) -> dict:
    """
    创建用户信息的字典。
    参数:
    username (str): 用户名。
    email (str): 用户邮箱。
    is_active (bool): 用户是否活跃,默认为 True。
    返回:
    dict: 包含用户信息的字典。
    """
    return {
   
        "username": username,
        "email": email,
        "is_active": is_active
    }

# 示例调用:is_active不用给定,直接用默认值
user1 = create_user("john_doe", "john@example.com")
print(user1)
# 输出: {'username': 'john_doe', 'email': 'john@example.com', 'is_active': True}

# 示例调用:is_active用给定值
user2 = create_user("jane_doe", "jane@example.com", False)
print(user2)
# 输出: {'username': 'jane_doe', 'email': 'jane@example.com', 'is_active': False}
  1. 可变参数:使用 *args 接收任意数量的位置参数
def calculate_total_price(discount: float = 0, *prices: float) -> float:
    """
    计算产品的总价格,考虑可选的折扣。

    参数:
    discount (float): 可选折扣,默认为 0。
    *prices (float): 任意数量的产品价格。

    返回:
    float: 应付的总价格。
    """
    total = sum(prices)  # 计算所有产品的总价
    total_discounted = total * (1 - discount)  # 应用折扣
    return total_discounted

# 示例调用
total1 = calculate_total_price(0.1, 100.0, 200.0, 50.0)  # 10% 折扣
print(f"{
     total1:.2f}")  # 输出: 315.00

total2 = calculate_total_price(0.2, 50.0, 75.0, 25.0, 100.0)  # 20% 折扣
print(f"{
     total2:.2f}")  # 输出: 120.00

total3 = calculate_total_price(0, 30.0, 20.0)  # 无折扣
print(f"{
     total3:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AnFany

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值