English

With the help of an example show, how can you return more than one value from a function? - Computer Science (Python)

Advertisements
Advertisements

Question

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

Answer in Brief

Solution

In a tuple, more than one value can be returned from a function by ‘packing’ the values. The tuple can be then ‘unpacked’ into the variables by using the same number of variables on the left-hand side as there are elements in a tuple. 

Example:

Program: 
#Function to compute area and perimeter of the square.
def square(r):
    area = r * r
    perimeter = 4 * r
    #Returns a tuple having two elements area and perimeter, i.e. two variables are packed in a tuple
    return (area, perimeter)
    ​#end of function

side = int(input("Enter the side of the square: "))
#The returned value from the function is unpacked into two variables area and perimeter
area, perimeter = square(side)
print("Area of the square is:",area)
print("The perimeter of the square is:",perimeter)

OUTPUT:
Enter the side of the square: 4
Area of the square is: 16
The perimeter of the square is: 16 
shaalaa.com
Tuple Handling
  Is there an error in this question or solution?
Chapter 10: Tuples and Dictionaries - Exercise [Page 224]

APPEARS IN

NCERT Computer Science [English] Class 11
Chapter 10 Tuples and Dictionaries
Exercise | Q 4. | Page 224
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×