函数返回值
return 语句终止当前函数的执行,并把后面的表达式结果传回给调用者。Python 的 return 比许多语言更灵活:可以返回单个值、多个值,也可以什么都不返回。
return 的基本语法
return 后面可以跟一个表达式,也可以什么都不跟:
def add(a, b):
return a + b
print(add(3, 5)) # 8
当 return 不带表达式时,函数返回 None:
def early_exit(flag):
if not flag:
return # 提前结束,返回 None
print("继续执行")
return "完成"
print(early_exit(False)) # None
print(early_exit(True)) # 先打印"继续执行",再返回"完成"
函数执行到末尾没有遇到 return 时,同样返回 None。这与显式写 return 不带表达式效果相同。
多返回值:元组解包
Python 函数可以"返回多个值",语法上实际是返回一个元组,调用处可以用多个变量并行接收:
def divide(a, b):
quotient = a // b
remainder = a % b
return quotient, remainder # 等价于 return (quotient, remainder)
q, r = divide(17, 5)
print(q, r) # 3 2
返回的元组也可以整体赋值给一个变量:
result = divide(17, 5)
print(result) # (3, 2)
print(type(result)) # <class 'tuple'>
这种机制在需要同时返回计算结果和状态信息时非常有用:
def parse_number(s):
try:
n = int(s)
return True, n
except ValueError:
return False, None
ok, value = parse_number("42")
print(ok, value) # True 42
ok, value = parse_number("abc")
print(ok, value) # False None
提前返回与守卫语句
return 可以出现在函数体的任何位置,常用于守卫语句(guard clause)——在函数开头检查非法输入,立即返回,避免深层嵌套:
def calculate_discount(price, rate):
if price < 0:
return 0 # 守卫:非法价格
if rate < 0 or rate > 1:
return price # 守卫:非法折扣率
return price * (1 - rate)
print(calculate_discount(100, 0.2)) # 80.0
print(calculate_discount(-10, 0.2)) # 0
print(calculate_discount(100, 1.5)) # 100
对比不使用提前返回的写法,守卫语句让主逻辑保持扁平,可读性更强。
返回 None 的语义
None 在 Python 中常表示"无结果"或"操作失败"。设计函数时,返回 None 应有意为之,且调用者需要正确处理:
def find_index(items, target):
for i, item in enumerate(items):
if item == target:
return i
return None # 未找到,显式返回 None
idx = find_index(["a", "b", "c"], "d")
if idx is None:
print("未找到")
else:
print(f"索引为 {idx}")
注意:不要用 == 判断 None,应使用 is。None 是单例对象,is 判断更精确且语义清晰。
# 错误示范
if idx == None: # 能工作,但不推荐
pass
# 正确做法
if idx is None: # 推荐
pass
返回函数对象
return 可以返回任何对象,包括另一个函数。这是闭包和装饰器的基础:
def make_multiplier(factor):
def multiply(x):
return x * factor
return multiply
triple = make_multiplier(3)
print(triple(5)) # 15
常见错误
在 return 后写不可达代码:
def broken(x):
return x * 2
print("永远不会执行") # 逻辑错误,但语法合法
试图在 return 后写多个表达式而不打包:
def wrong():
return 1, 2, 3 # 这其实是合法的,返回元组 (1, 2, 3)
# 真正的错误:试图用分号分隔(Python 不支持)
# def broken():
# return 1; return 2 # SyntaxError
在交互式解释器中,直接调用无返回值的函数会显示 None,容易让人困惑:
>>> def greet(name):
... print(f"Hello, {name}")
...
>>> greet("Alice")
Hello, Alice
>>> result = greet("Alice")
Hello, Alice
>>> print(result)
None
第一个调用显示 Hello, Alice 是因为 print 的输出;第二个调用把 None 赋给 result,再打印 result 时才看到 None。
小结
return 终止函数并传回值;无 return 或空 return 返回 None;多返回值本质是返回元组;提前返回能简化嵌套逻辑。正确区分"打印"与"返回",是避免函数相关 bug 的关键。