Python gets the specified return value in the function

In Python, if a function returns multiple values, you can use indexing or slicing to get one of the return values. Since the function returns a tuple object, its elements can be accessed like a tuple.

For example, in the following code, we define a function get_max_and_min()that takes the maximum and minimum values ​​in a list and returns these two values:

def get_max_and_min(numbers):
    max_num = max(numbers)
    min_num = min(numbers)
    return max_num, min_num

If you want to get one of the returned values, you can use indexing or slicing like this:

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
result = get_max_and_min(numbers)

# 获取第一个返回值(最大值)
max_num = result[0]
print("最大值:", max_num)

# 获取第二个返回值(最小值)
min_num = result[1]
print("最小值:", min_num)

# 获取前两个返回值(最大值和最小值)
max_num, min_num = result[0:2]
print("最大值:", max_num)
print("最小值:", min_num)

In this example, we first call get_max_and_min()the function to get the maximum and minimum values ​​in the list, and assign the returned value to resultthe variable. We can then access one of the return values ​​using indexing or slicing. For example, result[0]get the first return value, which is the maximum value; result[1]get the second return value, which is the minimum value; result[0:2]get the first two return values, which are the maximum and minimum values.

Guess you like

Origin blog.csdn.net/qq_44370158/article/details/131550211