View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
Functions in Python are first-class objects. First-class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures.
Properties of first-class functions:
- A function is an instance of the Object type.
- You can store the function in a variable.
- You can pass the function as a parameter to another function.
- You can return the function from a function.
- You can store them in data structures such as hash tables, lists, …
Example 1: Functions without arguments
In this example, the first method is A[] and the second method is B[]. A[] method returns the B[] method that is kept as an object with name returned_function and will be used for calling the second method.
Python3
def
B[]:
print
[
"Inside the method B."
]
def
A[]:
print
[
"Inside the method A."
]
return
B
returned_function
=
A[]
returned_function[]
Output :
Inside the method A. Inside the method B.
Example 2: Functions with arguments
In this example, the first method is A[] and the second method is B[]. Here A[] method is called which returns the B[] method i.e; executes both the functions.
Python3
def
B[st2]:
print
[
"Good "
+
st2
+
"."
]
def
A[st1, st2]:
print
[st1
+
" and "
, end
=
""]
return
B[st2]
A[
"Hello"
,
"Morning"
]
Output :
Hello and Good Morning.
Example 3: Functions with lambda
In this example, the first method is A[] and the second method is unnamed i.e; with lambda. A[] method returns the lambda statement method that is kept as an object with the name returned_function and will be used for calling the second method.
Python3
def
A[u, v]:
w
=
u
+
v
z
=
u
-
v
return
lambda
:
print
[w
*
z]
returned_function
=
A[
5
,
2
]
print
[returned_function]
returned_function[]
Output :
21
View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
A return statement is used to end the execution of the function call and “returns” the result [value of the expression following the return keyword] to the caller. The statements after the return statements are not executed. If the return statement is without any expression, then the special value None is returned. A return statement is overall used to invoke a function so that the passed statements can be executed.
Note: Return statement can not be used outside the function.
Syntax:
def fun[]: statements . . return [expression]
Example:
def cube[x]: r=x**3 return r
Example:
Python3
def
add[a, b]:
return
a
+
b
def
is_true[a]:
return
bool
[a]
res
=
add[
2
,
3
]
print
[
"Result of add function is {}"
.
format
[res]]
res
=
is_true[
2