Functions Returning Multiple Values
In python, we can return multiple values from a function. (In C and C++ a function can return a maximum of one value)
Examples:
Question:1. Python program to calculate square and cube of a number. (returning multiple values)
#function definition def cal(a): sq=a*a cu=a*a*a return(sq,cu) #function calling n=int(input('enter any number: ')) s,c=cal(n) print('square of ',n,' =',s) print('cube of ',n,' =',c)
Output:
enter any number: 5
square of 5 = 25
cube of 5 = 125
>>>
Question:2. Python program to find the maximum and minimum of three numbers. (returning multiple values)
code#function definition def find(a,b,c): m=0 n=0 if(a>b and a>c): m=a else: if(b>c): m=b else: m=c if(a<b and a<c): n=a else: if(b<c): n=b else: n=c return(m,n) #function calling a=int(input('enter 1st number: ')) b=int(input('enter 2nd number: ')) c=int(input('enter 3rd number: ')) ma,mi=find(a,b,c) print('largest of three numbers = ',ma) print('smallest of three numbers = ',mi)
Output:
enter 1st number: 23
enter 2nd number: 45
enter 3rd number: 76
largest of three numbers = 76
smallest of three numbers = 23
>>>
Question:3. Python program to calculate sum, product, and the average of three numbers. (returning multiple values)
#function definition def cal(a,b,c): s=a+b+c p=a*b*c av=(a+b+c)/3 return(s,p,av) #function calling a=int(input('enter 1st number: ')) b=int(input('enter 2nd number: ')) c=int(input('enter 3rd number: ')) su,pr,avr=cal(a,b,c) print('Sum of three numbers = ',su) print('Product of three numbers = ',pr) print('Average of three numbers = ',avr)
Output:
enter 1st number: 3
enter 2nd number: 4
enter 3rd number: 5
Sum of three numbers = 12
Product of three numbers = 60
Average of three numbers = 4.0
Question:4. Python program to calculate the area and perimeter of a circle.(returning multiple values)
#function definition def cal(r): area=3.14*r*r peri=2*3.14*r return(area,peri) #function calling r=int(input('enter the radius of a circle: ')) ar,pm=cal(r) print('area of a circle = ',ar) print('Perimeter of a circle = ',pm)
Output:
enter the radius of a circle: 6
area of a circle = 113.03999999999999
Perimeter of a circle = 37.68
>>>
Question:5. Python program to calculate area of a square and a rectangle.(returning multiple values)
#function definition def area(s,l,b): sqr=s*s rect=l*b return(sqr,rect) #function calling s=int(input('enter the side of a square: ')) l=int(input('enter the length of a rectangle: ')) b=int(input('enter the breadth of a rectangle: ')) sq,rec=area(s,l,b) print('area of a square = ',sq) print('area of a rectangle = ',rec)
Output:
enter the side of a square: 4
enter the length of a rectangle: 20
enter the breadth of a rectangle: 10
area of a square = 16
area of a rectangle = 200
>>>