Python函数:如何返回值和多个返回值?
发布时间:2023-07-06 01:02:48
Python函数可以通过使用return关键字来返回值。return语句可以返回任何类型的值,包括数字、字符串、列表和字典等。当函数执行到return语句时,它会停止执行,并将返回值提供给调用函数的地方。
要返回多个值,可以使用元组、列表或字典等数据类型。以下是一些示例:
1. 返回单个值:
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 输出:8
2. 返回元组:
def calculate(a, b):
add = a + b
subtract = a - b
multiply = a * b
divide = a / b
return add, subtract, multiply, divide
result = calculate(10, 5)
print(result) # 输出:(15, 5, 50, 2.0)
在这个例子中,函数返回一个元组,其中包含四个计算结果。
3. 返回列表:
def get_even_numbers(numbers):
even_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
return even_numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = get_even_numbers(numbers)
print(result) # 输出:[2, 4, 6, 8, 10]
在这个例子中,函数返回一个包含给定列表中的偶数的新列表。
4. 返回字典:
def get_student_info(name, age, grade):
info = {
"name": name,
"age": age,
"grade": grade
}
return info
student_info = get_student_info("Tom", 17, "11th")
print(student_info) # 输出:{'name': 'Tom', 'age': 17, 'grade': '11th'}
在这个例子中,函数返回一个包含学生信息的字典。
无论是返回单个值还是多个值,我们都可以将返回值存储在变量中,并在需要的地方使用。
