How Can I Use `Return` To Get Back Multiple Values From A loop?

In this post, we will learn how can I use ` Return ` to get back multiple values from a loop. If yes, we can put them on a list to display here we have given an example to implement.


Return A List Loop

We can return the Number of value of a loop using a list where we keep on storing all the value in the single list and Print at the end of it so in this way we can Print the Number of value of the loop at once or all the value are returned in just one by printing a list where we keep of a string the value in the list.

Here we have given an example to explain it better and implement it, in our  project

def calculate_statistics( numbers):
    total = 0
    count = 0
    for num in numbers:
        total += num
        count += 1
    average = total / count
    return [total, average, count]

Here we took an example of calculating a value where we used a loop and returned the Number of value in the form of a list where we keep on storing the value in the list and to know we can store the value in a list follow the code given below and understand it for Printing the value.

numbers = [1, 2, 3, 4, 5]
result = calculate_statistics( numbers)
print( result)

As here we used the list to store the value we can also use a tuple to strong the value and later Print it when we want to print those the Number of value for learning how we can use the tuple we have given an example to learn more.

def find_max_min( numbers):
    max_num = numbers[0]
    min_num = numbers[0]
    for num in numbers:
        if num > max_num:
            max_num = num
        elif num < min_num:
            min_num = num
    return max_num, min_num

And for the function, we have the code as followed to execute

numbers = [5, 3, 9, 2, 1]
max_num, min_num = find_max_min( numbers)
print( "Max:", max_num)
print( "Min:", min_num)

The result of this tule use will be as followed.

Max: 9
Min: 1


Here we have the ways are the same but in both the methods we used different entities to store the value of the result and Print as pr the requirement so we can say that we can implement the same thing in both the ways


To learn more about How Can I Use `Return` To Get Back Multiple Value From A Loop visit:  by stack overflow.

To learn more about Python solutions to different Python problems and tutorials for the concepts we need to know to work on Python programming along with different ways to solve any generally asked problems: How To Pass-Variables From A Java & Python Client To A Linux/Ubuntu Server Which Is Running C?.

Leave a Comment

%d bloggers like this: