Python Functions | Python functions returning multiple values

Python 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)

Example:

Question:1
Python script to calculate and print square and cube of a number
Sol:

#function definition
def calculate(n):
    s=n*n
    c=n*n*n
    return(s,c)


#function calling
a=int(input("Enter any no "))
s,c=calculate(a)
print("Square = ",s)
print("Cube = ",c)

Output:

Enter any no 5
Square = 25
Cube = 125
>>>

Question:2
Python script to calculate and print sum , product and difference of two number
Sol:

#function definition
def calculate(n1,n2):
    s=n1+n2
    p=n1*n2
    if(n1>n2):
        d=n1-n2
    else:
        d=n2-n1
    return(s,p,d)


#function calling
a=int(input("Enter 1st no "))
b=int(input("Enter 2nd no "))
s,p,d=calculate(a,b)
print("Sum = ",s)
print("Product = ",p)
print("Difference = ",d)

Output:

Enter 1st no 10
Enter 2nd no 20
Sum = 30
Product = 200
Difference = 10
>>>

Question:3
Python script to print largest and lowest of three numbers
Sol:

#function definition
def calculate(p,q,r):
    #max no
    if(p>q and p>r):
        ma=p
    elif(q>r):
        ma=q
    else:
        ma=r
    #min no
    if(p<q and p<r):
        mi=p
    elif(q<r):
        mi=q
    else:
        mi=r
    return(ma,mi)


#function calling
a=int(input("Enter 1st no "))
b=int(input("Enter 2nd no "))
c=int(input("Enter 3rd no "))
ma,mi=calculate(a,b,c)
print("Max no  = ",ma)
print("Min no  = ",mi)


Output:

Enter 1st no 25
Enter 2nd no 96
Enter 3rd no 3
Max no = 96
Min no = 3
>>>

Visitor Counter

0051008