一、什么是 return?
返回值是函数执行完毕后传递给调用者的结果。使用return语句可以从函数中返回一个值,并终止函数的执行。概括说:return 语句用于结束函数的执行,并将一个值(或对象)返回给调用者。基本语法:
def 函数名 (参数): # 执行逻辑 return 返回值
def add(a, b): result = a + b return resultsum_value = add(3, 5)print(sum_value) # 8
💡 关键点:一旦执行到 return,函数立即停止,后面的代码不会再运行。二、返回多个值
Python 允许函数一次性返回多个值,本质上返回的是一个元组(Tuple)。示例:
def get_min_max(numbers): return min(numbers), max(numbers)# 返回的是元组result = get_min_max([3, 1, 4, 1, 5, 9])print(result) # (1, 9)print(type(result)) # <class 'tuple'># 可以解包接收minimum, maximum = get_min_max([3, 1, 4, 1, 5, 9])print(f"最小值: {minimum}, 最大值: {maximum}")
def get_info(): name = "Alice" age = 25 return name, age # 相当于 return (name, age)# 接收返回值info = get_info()print(info) # ('Alice', 25)print(type(info)) # <class 'tuple'># 元组解包(推荐写法)name, age = get_info()print(name, age) # Alice 25
返回状态和结果
def find_user(user_id): """查找用户,返回用户信息和是否成功""" users = {1: "张三", 2: "李四", 3: "王五"} if user_id in users: return users[user_id], True return None, Falsename, found = find_user(2)if found: print(f"找到用户: {name}")else: print("用户不存在")
返回不同类型的值
1.返回列表
def get_even_numbers(n): """返回n以内的偶数列表""" return [i for i in range(n) if i % 2 == 0]evens = get_even_numbers(10)print(evens) # [0, 2, 4, 6, 8]
2.返回字典
def create_user(name, age, city): """创建并返回用户字典""" return { "name": name, "age": age, "city": city, "created_at": "2025-01-01" }user = create_user("张三", 25, "北京")print(user)
3.条件返回
根据不同条件返回不同值:
def grade(score): """根据分数返回等级""" if score >= 90: return "优秀" elif score >= 80: return "良好" elif score >= 70: return "中等" elif score >= 60: return "及格" else: return "不及格"print(grade(85)) # 良好print(grade(55)) # 不及格
4.提前返回
# 嵌套写法(不推荐)def process_data_nested(data): if data is not None: if len(data) > 0: if isinstance(data[0], int): return sum(data) else: return "数据类型错误" else: return "数据为空" else: return "数据不存在"# 提前返回(推荐)def process_data(data): if data is None: return "数据不存在" if len(data) == 0: return "数据为空" if not isinstance(data[0], int): return "数据类型错误" return sum(data)
def square(n): return n ** 2result = square(5)print(result) # 25
return语句会立即终止函数执行,后面的代码不会运行:def check_positive(n): if n <= 0: return "不是正数" print("这行会执行吗?") # n <= 0 时不会执行 return "是正数"print(check_positive(-5)) # 不是正数print(check_positive(5)) # 这行会执行吗? 是正数
如果函数中没有 return 语句,或者只有 return 而没有值,函数默认返回 None。示例:
def say_hello(): print("Hello!")result = say_hello()print(result) # 输出:None
显式返回 None:
def do_nothing(): return None # 等价于直接 return 或不写 return
def greet(name): print(f"你好,{name}!") # 没有return语句result = greet("张三")print(result) # Nonedef empty_return(): return # 等同于 return Noneprint(empty_return()) # None
六、实际应用示例
def validate_email(email): """验证邮箱格式""" if not email: return False, "邮箱不能为空" if "@" not in email: return False, "邮箱必须包含@" if "." not in email.split("@")[1]: return False, "邮箱域名格式不正确" return True, "验证通过"valid, message = validate_email("test@example.com")print(f"有效: {valid}, 信息: {message}")
def calculate_stats(numbers): """计算统计信息""" if not numbers: return None return { "count": len(numbers), "sum": sum(numbers), "min": min(numbers), "max": max(numbers), "average": sum(numbers) / len(numbers) }stats = calculate_stats([10, 20, 30, 40, 50])print(f"统计: {stats}")
def parse_config(config_string): """解析配置字符串""" result = {} for line in config_string.strip().split("\n"): if "=" not in line: continue key, value = line.split("=", 1) result[key.strip()] = value.strip() return resultconfig = """host=localhostport=8080debug=true"""parsed = parse_config(config)print(parsed) # {'host': 'localhost', 'port': '8080', 'debug': 'true'}
from collections import namedtuple# 定义命名元组Coordinates = namedtuple("Coordinates", ["x", "y", "z"])def get_position(): """返回坐标""" return Coordinates(10, 20, 30)pos = get_position()print(f"x={pos.x}, y={pos.y}, z={pos.z}")# 比普通元组更易读
七、核心难点:return vs print
特性 | return
| print
|
|---|
作用 | 将值返回给调用者 | 将内容打印到控制台 |
后续使用 | 返回值可以被变量接收、参与运算 | 打印的内容无法被程序直接使用 |
函数结束 | 结束函数执行 | 不结束函数 |
场景 | 逻辑处理、数据计算 | 调试、用户展示 |
def with_return(n): return n * 2def with_print(n): print(n * 2)# return的结果可以继续使用result = with_return(5)print(result + 10) # 20# print的结果无法使用result = with_print(5) # 输出10print(result) # None
适用场景
计算结果:返回计算后的值
数据转换:返回处理后的数据
状态判断:返回True/False
查找操作:返回找到的元素或None
工厂函数:返回创建的对象
注意事项
return后的代码不执行:return会立即终止函数
不写return返回None:默认返回None
多个return选择一个执行:只有一个return会被执行
返回多值实际是元组:return a, b等同于return (a, b)
# 常见错误# 1. 忘记returndef add(a, b): result = a + b # 忘了 return resultprint(add(1, 2)) # None# 2. return后写代码def func(): return 42 print("这里不会执行") # 无法到达# 3. 混淆print和returndef double(n): print(n * 2) # 这只是打印,不是返回result = double(5) # 打印10print(result * 3) # TypeError: None * 3
常见问题
def analyze_text(text): """分析文本,返回多种信息""" word_count = len(text.split()) char_count = len(text) has_numbers = any(c.isdigit() for c in text) return word_count, char_count, has_numberswords, chars, has_num = analyze_text("Hello 123 World")print(f"单词数: {words}, 字符数: {chars}, 含数字: {has_num}")
2.函数可以有多个return吗?
def classify(n): """可以有多个return,但只执行一个""" if n > 0: return "正数" elif n < 0: return "负数" else: return "零"# 根据条件,只有一个return被执行print(classify(5)) # 正数print(classify(-3)) # 负数print(classify(0)) # 零
class Calculator: def __init__(self, value=0): self.value = value def add(self, n): self.value += n return self # 返回自身 def multiply(self, n): self.value *= n return self def result(self): return self.value# 链式调用calc = Calculator(10)result = calc.add(5).multiply(2).add(3).result()print(result) # (10 + 5) * 2 + 3 = 33