Site icon Student Projects Live

Python Program to Return Multiple Values From a Function

Python Program to Return Multiple Values From a Function

The provided Python code demonstrates how to return multiple values from a function in Python using tuples. It defines a function named multiple_values() that encapsulates three different values: an integer (value1), a string (value2), and a list (value3). These values are then returned from the function using the return statement. Since multiple values are being returned, Python implicitly packs them into a tuple. Upon calling the function, the returned tuple is unpacked into individual variables (result1, result2, and result3). Finally, the script prints out these returned values, illustrating how multiple values can be efficiently handled and utilized from a single function call in Python. This approach is commonly used when a function needs to provide diverse information to the caller without resorting to more complex data structures or objects.


Source code

def multiple_values():
    # Define multiple values
    value1 = 10
    value2 = 'Hello'
    value3 = [1, 2, 3]
    
    # Return multiple values as a tuple
    return value1, value2, value3

# Call the function and unpack the returned tuple
result1, result2, result3 = multiple_values()

# Print the returned values
print("Result 1:", result1)
print("Result 2:", result2)
print("Result 3:", result3)

Description

Sure, here’s a step-by-step breakdown of the provided code:

  1. Function Definition (multiple_values()):
  1. Variable Assignment within the Function:
  1. Returning Multiple Values:
  1. Function Call and Unpacking:
  1. Printing the Returned Values:

In summary, the code defines a function that returns multiple values (an integer, a string, and a list) using the implicit packing of values into a tuple. It then demonstrates how to call the function, unpack the returned tuple, and use the individual values. This approach provides a convenient way to organize and retrieve multiple pieces of data from a single function call.


Screenshot


Download

Exit mobile version