Python案例如何自定义函数返回?

wen python案例 67

本文目录导读:

Python案例如何自定义函数返回?

  1. 基本返回语法
  2. 基础案例
  3. 返回不同类型的数据
  4. 返回None的特殊情况
  5. 条件返回
  6. 返回函数(高阶函数)
  7. 实用的综合案例
  8. 重要注意事项
  9. 最佳实践
  10. 调试技巧

在Python中,自定义函数通过return语句来返回值,以下是详细的用法和案例:

基本返回语法

def 函数名(参数):
    # 函数体
    return 返回值
# 调用函数并接收返回值
结果 = 函数名(参数)

基础案例

返回单个值

def add(x, y):
    return x + y
result = add(3, 5)
print(result)  # 输出: 8

返回多个值(实际返回元组)

def get_info():
    name = "张三"
    age = 25
    city = "北京"
    return name, age, city  # 返回元组
# 方法1:接收为元组
info = get_info()
print(info)  # 输出: ('张三', 25, '北京')
# 方法2:解包接收
name, age, city = get_info()
print(f"{name},{age}岁,来自{city}")  # 输出: 张三,25岁,来自北京

返回不同类型的数据

返回列表

def even_numbers(n):
    """返回1到n之间的所有偶数"""
    evens = []
    for i in range(1, n + 1):
        if i % 2 == 0:
            evens.append(i)
    return evens
result = even_numbers(10)
print(result)  # 输出: [2, 4, 6, 8, 10]

返回字典

def create_student(name, age, scores):
    """创建学生字典"""
    student = {
        "name": name,
        "age": age,
        "scores": scores,
        "average": sum(scores) / len(scores)
    }
    return student
stu = create_student("张三", 18, [85, 92, 78])
print(stu)
# 输出: {'name': '张三', 'age': 18, 'scores': [85, 92, 78], 'average': 85.0}

返回布尔值

def is_prime(n):
    """判断是否为素数"""
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True
print(is_prime(7))   # 输出: True
print(is_prime(10))  # 输出: False

返回None的特殊情况

def print_message(msg):
    """打印消息但不返回值"""
    print(msg)
    # 没有return语句,默认返回None
result = print_message("你好")
print(result)  # 输出: None
# 显式返回None
def do_nothing():
    return None
# 或者
def do_nothing():
    return

条件返回

def get_grade(score):
    """根据分数返回等级"""
    if score >= 90:
        return "优秀"
    elif score >= 80:
        return "良好"
    elif score >= 70:
        return "中等"
    elif score >= 60:
        return "及格"
    else:
        return "不及格"
print(get_grade(85))  # 输出: 良好
print(get_grade(45))  # 输出: 不及格

返回函数(高阶函数)

def multiplier(factor):
    """返回一个乘法函数"""
    def multiply(x):
        return x * factor
    return multiply
double = multiplier(2)      # 创建乘以2的函数
triple = multiplier(3)      # 创建乘以3的函数
print(double(5))   # 输出: 10
print(triple(5))   # 输出: 15
# 使用Lambda表达式
def make_power(exponent):
    return lambda x: x ** exponent
square = make_power(2)
print(square(4))   # 输出: 16

实用的综合案例

def analyze_text(text):
    """分析文本,返回统计信息"""
    # 去除首尾空白
    text = text.strip()
    if not text:
        return {
            "error": "文本不能为空",
            "valid": False
        }
    # 统计信息
    word_count = len(text.split())
    char_count = len(text)
    sentence_count = text.count('。') + text.count('!') + text.count('?')
    # 返回字典
    return {
        "valid": True,
        "word_count": word_count,
        "char_count": char_count,
        "sentence_count": sentence_count,
        "is_long_text": word_count > 100
    }
# 测试
result = analyze_text("今天天气真好,我们一起去公园玩吧!")
print(f"字数: {result['word_count']}")
print(f"字符数: {result['char_count']}")
print(f"句子数: {result['sentence_count']}")

重要注意事项

# 1. return后的代码不会执行
def test_return():
    print("这行会执行")
    return "返回值"
    print("这行不会执行")  # 这段代码被忽略
# 2. 可以使用多个return
def check_number(n):
    if n > 0:
        return "正数"
    if n < 0:
        return "负数"
    return "零"
# 3. 返回值可以是表达式
def calculate(x, y):
    return x ** 2 + y ** 2  # 返回计算结果
# 4. 返回复杂对象
def create_matrix(rows, cols):
    """创建并返回一个矩阵"""
    return [[0 for _ in range(cols)] for _ in range(rows)]
matrix = create_matrix(3, 4)
print(matrix)  # 输出: [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

最佳实践

# 1. 明确返回类型
def divide(a, b):
    """返回除法结果,如果除数为0返回None"""
    if b == 0:
        return None
    return a / b
# 2. 使用类型提示
def celsius_to_fahrenheit(celsius: float) -> float:
    """摄氏度转华氏度"""
    return celsius * 9 / 5 + 32
# 3. 返回类实例
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
def create_person(name, age):
    """创建并返回Person对象"""
    return Person(name, age)
person = create_person("李四", 30)
print(f"{person.name}, {person.age}岁")

调试技巧

# 使用调试打印
def calculate(x, y):
    print(f"输入: x={x}, y={y}")  # 调试信息
    result = x * y
    print(f"输出: {result}")      # 调试信息
    return result
# 或使用assert验证
def safe_divide(a, b):
    assert b != 0, "除数不能为零"
    return a / b
  • return用于返回值,可以返回任何Python对象
  • 可以返回多个值(自动打包为元组)
  • 没有return或return None时,函数返回None
  • return会立即结束函数执行
  • 返回的函数或类实例可以被调用和使用

抱歉,评论功能暂时关闭!