Python return 语句
return 用于结束当前函数的执行,并把一个表达式的结果传回调用方。函数里可以写多个 return,最先执行到的那一个会使函数立即返回,其后的语句不会运行。
没有 return、或只有 return 而没有表达式时,函数相当于返回 None。与函数基础见 函数;异常与 finally 的配合见 异常处理。
语法
python
return # 等价于 return None
return 表达式若有表达式,会先求值,再将该值作为函数结果返回。
简单示例
python
def add(x, y):
total = x + y
return total
def add_short(x, y):
return x + y
print(add(5, 3))输出:
text
8无 return 与「空 return」
python
def foo():
pass
def return_none():
return
print(foo())
print(return_none())输出:
text
None
None多个 return 分支
python
def parity(n):
if n % 2 == 0:
return "even"
return "odd"
print(parity(7))输出:
text
odd任意类型作为返回值
Python 不在函数签名里声明返回类型,运行时可以返回不同类型(是否好风格由项目约定决定)。
python
def get_demo(kind):
if kind == "str":
return "test"
if kind == "tuple":
return (1, 2, 3)
if kind == "list":
return [1, 2, 3]
if kind == "dict":
return {"1": 1, "2": 2}
return None
print(get_demo("str"))
print(get_demo("tuple"))
print(get_demo("list"))
print(get_demo("dict"))
print(get_demo("set"))输出:
text
test
(1, 2, 3)
[1, 2, 3]
{'1': 1, '2': 2}
None一次返回多个值(元组打包)
逗号分隔的多个表达式会打包成一个元组返回:
python
def coords():
return 1, 2, 3
t = coords()
print(t)
print(type(t))输出:
text
(1, 2, 3)
<class 'tuple'>调用方可用 a, b, c = coords() 解包。
与 try / finally 的关系
离开 try 时若要走 return,解释器仍会先执行 finally 块,再真正带着返回值退出函数。
python
def hello():
try:
return "hello try"
finally:
print("finally block")
def hello_except():
try:
raise TypeError
except TypeError:
return "hello except"
finally:
print("finally block")
print(hello())
print(hello_except())输出:
text
finally block
hello try
finally block
hello except若 finally 里也有 return,会覆盖 try / except 里准备返回的值(易读性差,尽量避免):
python
def hello():
try:
return "hello try"
finally:
print("finally block")
return "hello from finally"
print(hello())输出:
text
finally block
hello from finally小结
| 要点 | 说明 |
|---|---|
| 结束函数 | 执行到 return 后,当前函数立即结束 |
| 默认返回值 | 无 return 或 return 无表达式 → None |
| 多个值 | return a, b → 返回元组 (a, b) |
finally | 一般先于 return 生效;finally 里的 return 会覆盖前面的返回 |
return 把数据交回调用方;print 只在输出设备上显示,多数业务逻辑应优先用 return 传递结果。