Tuesday, 3 December 2019

A function can return more than one value


Returning multiple values from a function:
A function can return more than one value in Python.
def cal(a,b):
    c=a+b
    d=a-b
    return c,d
x,y=cal(10,6)
print("Addition=",x)
print("Subtraction=",y)
"""output:
Addition= 16
Subtraction= 4
>>> """

Ex2:
def cal(a,b):
    c=a+b
    d=a-b
    e=a*b
    f=a/b
    return c,d,e,f
#a,s,m,d=cal(10,6)
r=cal(10,6)
for i in r:
    print(i)
"""output:
16 ,4,60,1.6666666666666667
>>>

Functions are First class objects:

In python, functions are considered as first class objects. It means we can use functions as objects. When we create the function, the python interpreter internally creates an object. Since functions are objects, we can pass function to another function just like we pass an object (or variable) to a function. Also it is possible to return a function from another function.

#assign a function to a variable
def display(s):
    return 'good'+s
#assign function to variable a
a=display("Morning")
print(a)
"""output:
Good Morning
>>>
"""
Nested function:
#A python program to know how to define a function inside another function
def display(s):
    def inner():
        return "Hello "
    a=inner()+s
    return a
print(display("How are you"))
"""output:
Hello How are you
>>>
"""
#function ca be passed as parameters to other functions
def display(a):
    return 'Sri'+a
def f1():
    return 'Ram'
#call display() and pass f1() function as a parameter
print(display(f1()))
"""
output:SriRam
>>>
"""

Previous Return statement

No comments:

Post a Comment

Files with Exception handling

#Ask the user to take two input integer values var a,b try:     a=int(input("enter any integer value:"))     b=int(input(&qu...