Python返回值与多返回值
return 语句将函数结果返回给调用者,Python 支持返回多个值。
return 语句
基本用法
Python
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 8
无 return 或空 return
Python
def greet(name):
print(f"Hello, {name}")
result = greet("Alice")
print(result) # None
def process():
return # 等同于 return None
立即终止函数
Python
def check_positive(n):
if n < 0:
return "negative" # 立即终止
return "positive"
print(check_positive(-5)) # negative
print(check_positive(5)) # positive
多返回值
返回多个值(实际是元组)
Python
def get_info():
name = "Alice"
age = 25
city = "Beijing"
return name, age, city # 返回元组
# 元组解包接收
n, a, c = get_info()
print(n, a, c) # Alice 25 Beijing
# 整体接收
info = get_info()
print(info) # ('Alice', 25, 'Beijing')
print(type(info)) # tuple
实际应用
计算统计值
Python
def calculate_stats(numbers):
return min(numbers), max(numbers), sum(numbers)
minimum, maximum, total = calculate_stats([1, 2, 3, 4, 5])
print(f"min={minimum}, max={maximum}, sum={total}")
# min=1, max=5, sum=15
分割字符串
Python
def split_name(full_name):
parts = full_name.split()
return parts[0], parts[1] if len(parts) > 1 else ""
first, last = split_name("Alice Smith")
print(first, last) # Alice Smith
查找索引
Python
def find_item(items, target):
if target in items:
return items.index(target), True
return -1, False
index, found = find_item([1, 2, 3], 2)
print(f"index={index}, found={found}") # index=1, found=True
元组解包
基本解包
Python
def get_coordinates():
return 10, 20
x, y = get_coordinates()
扩展解包
Python
def get_values():
return 1, 2, 3, 4, 5
first, *middle, last = get_values()
print(first) # 1
print(middle) # [2, 3, 4]
print(last) # 5
忽略某些返回值
Python
def get_data():
return "Alice", 25, "Beijing"
name, _, city = get_data() # 用 _ 忽略 age
print(name, city) # Alice Beijing
返回字典
当返回值较多时
Python
def get_user_info():
return {
"name": "Alice",
"age": 25,
"city": "Beijing",
"email": "alice@example.com"
}
info = get_user_info()
print(info["name"]) # Alice
返回列表
返回多个结果集合
Python
def find_even_and_odd(numbers):
evens = [n for n in numbers if n % 2 == 0]
odds = [n for n in numbers if n % 2 != 0]
return evens, odds
even_list, odd_list = find_even_and_odd([1, 2, 3, 4, 5])
print(even_list) # [2, 4]
print(odd_list) # [1, 3, 5]
要点总结
return将结果返回给调用者,立即终止函数- 无 return 或空 return 返回 None
- 多返回值实际是元组,通过解包接收
- 使用
_忽略不需要的返回值 - 返回值较多时建议返回字典
📝 发现内容有误?点击此处直接编辑