Question 4 of 14intermediate🔧 ApplyShort Answer2 marks

With the help of an example show how can you return more than one value from a function.

Correct Answer

A function can return more than one value by returning them as a tuple. The caller can then use tuple assignment to unpack these values into separate variables.

Example: python def get_details(): name = "Pooja" rollNo = 40 subject = "CS" return (name, rollNo, subject)

Calling the function and unpacking values

(name, rollNo, subject) = get_details() print(name) # Output: Pooja print(rollNo) # Output: 40 print(subject) # Output: CS

In this example, the function returns a tuple containing three values. Using tuple assignment, we can assign these values to three separate variables at once. The number of variables on the left should be same as the number of elements in the tuple returned.

Exercise: EXERCISE | Q: 4 | (Page 18)
For More Understanding

Explanation

The textbook explains tuple assignment in Section 10.4, stating that 'Assignment of tuple is a useful feature in Python. It allows a tuple of variables on the left side of the assignment operator to be assigned respective values from a tuple on the right side.' Example 10.2 demonstrates this with (num1, num2) = (10, 20) and (name, rollNo, subject) = record. This same concept applies when returning multiple values from a function - the function returns a tuple, and the caller unpacks it using tuple assignment.