案例:计算圆的面积
def calculate_circle_area(radius):
return 3.14159 * radius ** 2
# 接收单个返回值
area = calculate_circle_area(5)
print(f"半径为5的圆面积:{area:.2f}") # 输出:半径为5的圆面积:78.54
易错点警示:
# 错误写法:误以为返回多个值
result = calculate_circle_area(3)
width, height = result # 引发TypeError: cannot unpack non-iterable float object
案例:同时获取商和余数
def divide(dividend, divisor):
quotient = dividend // divisor
remainder = dividend % divisor
return quotient, remainder # 实际返回元组
# 正确接收方式(解包)
q, r = divide(17, 5)
print(f"17除以5的商:{q},余数:{r}") # 输出:商:3,余数:2
# 直接接收元组
result = divide(20, 3)
print(type(result)) #
print(f"完整结果:{result}") # 输出:(6, 2)
多返回值高级用法:
# 星号解包剩余返回值
def get_coordinates():
return 120.5, 31.3, 15 # 经度、纬度、海拔
x, y, *rest = get_coordinates()
print(f"平面坐标:({x}, {y}),其他数据:{rest}") # 输出:[15]
None
返回值处理案例1:显式返回None
def find_negative(numbers):
for num in numbers:
if num < 0:
return num
return None # 明确表示未找到
nums = [1, 3, 5]
result = find_negative(nums)
print(f"负数查找结果:{result}") # 输出:None
案例2:隐式返回None
def print_greeting(name):
print(f"Hello, {name}!")
# 没有return语句,默认返回None
ret_value = print_greeting("Alice")
print(ret_value is None) # 输出:True
None判断陷阱:
def get_user_age(user_id):
# 假设数据库查询返回None表示记录不存在
return None if user_id > 100 else 25
age = get_user_age(200)
if not age: # 当age=0时也会进入判断!
print("用户不存在或年龄为0")
# 正确判断方式
if age is None:
print("用户不存在")
elif age == 0:
print("年龄为0")
def clean_data(raw_str):
if not isinstance(raw_str, str):
return None, "Invalid input type"
cleaned = raw_str.strip().lower()
if len(cleaned) < 3:
return None, "String too short"
return cleaned, None # 成功返回清洗结果,错误信息为None
data, error = clean_data(" Python ")
if error:
print(f"清洗失败:{error}")
else:
print(f"清洗结果:'{data}'") # 输出:清洗结果:'python'
def fetch_user_data(user_id):
# 模拟API调用
if user_id % 2 == 0:
return {"status": 200, "data": {"name": "Alice", "age": 30}}
else:
return {"status": 404, "error": "User not found"}
response = fetch_user_data(123)
if response["status"] == 200:
print(f"用户数据:{response['data']}")
else:
print(f"错误:{response['error']}") # 输出:错误:User not found
from typing import Tuple, Optional
def process_data(data: list) -> Tuple[bool, Optional[dict]]:
if not data:
return False, None
# 处理逻辑...
return True, {"result": "processed_data"}
# 不推荐写法
def get_config(key):
if key not in config:
return False # 返回布尔表示失败
return {"value": config[key]} # 返回字典表示成功
# 推荐统一返回结构
def get_config_safe(key):
if key not in config:
return {"success": False, "error": "Key not found"}
return {"success": True, "value": config[key]}
is None
/is not None
进行判断def parse_number(s: str) -> Union[float, None]:
"""
尝试将字符串转换为浮点数
:param s: 输入字符串
:return: 转换后的数值,转换失败返回None
"""
try:
return float(s)
except ValueError:
return None
错误现象 | 原因分析 | 解决方案 |
---|---|---|
TypeError: 'NoneType' object is not iterable |
试图解包返回None的函数 | 检查函数是否在所有路径都有正确返回值 |
ValueError: too many values to unpack |
接收变量数量与返回值数量不匹配 | 使用* 捕获剩余值或调整接收变量数量 |
意外进入if not return_value 判断 |
将0、空列表等有效值与None混淆 | 使用is None 进行精确判断 |
函数返回意外类型 | 多分支返回不同类型数据 | 统一返回类型或使用包装字典 |
总结:合理处理函数返回值是编写健壮Python代码的关键。掌握单值返回的常规处理、多值返回的解包技巧、None值的正确判断方法,结合类型提示和明确的接口设计,可以显著提升代码的可读性和可靠性。