Python-FUNCTIONS by Vivek Singh Khetwal.
Python-FUNCTIONS by Vivek Singh Khetwal.
Functions:
In computer programming the programs are broken up into functions for better
modularity and ease of maintenance. A function can be defined as a block of code
that takes in some data either for performing some operations using that data and
returns the operated data or performs some task on that data.
Similar kind of data can be stored inside a function and we can provide a name to
that function that can describe its functionality. Functions in Python are similar to
the functions in C++ and Java. The functionality is same only the syntax differs
from other programming languages.
A function is a piece of code written to carry out a specified task. To carry out that
specific task, the function might or might not need multiple inputs. When task is
carried out a function might or might not return one or more values.
Functions in Python are defined using the def keyword.
Example1:
def hello():
print('Hello! I am Vivek.’)
Fig: The example above is showing the use of def keyword while defining a function.
Method Description
def greet():
print(“Hello! How are you?”)
return 1
If __name__== ‘__main__’:
print(“ going to call greet ”)
x=greet
print(“ called greet ”)
print(“ foo returned ” + str(x))
Output:
18
12
Function Arguments
In Python, user-defined functions can take four different types of arguments.
The argument types and their meanings, however, are pre-defined and
cannot be changed. But a user can use these pre-defined rules to make their
own custom functions.
One can call a function by using the following types of formal arguments:
a) Required Arguments.
b) Keyword arguments.
c) Default arguments.
d) Variable-length arguments.
Function definition:
Function Call:
Keyword Arguments
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the
parameter name.
This allows you to skip arguments or place them out of order because the
Python interpreter is able to use the keywords provided to match the values
with parameters.
Function definition:
Function Call:
or
Function Definition:
Function Call:
defaultArg( Vivek )
Variable-Length Arguments
This type of argument is very useful when we do not know the exact number
of arguments that will be passed to a function. Or we can have a design
where any number of arguments can be passed based on the requirement.
Function Definition:
Function Call:
lambda arguments:expression
Program:
Output:
20
int = lambda x : x * 2
def int( x ):
return( x * 2 )
my_list = range(20)
map(lambda x : x * 2, my_list)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38]
my_list = range(20)
filter(lambda x: x > 10 my_list)
[11, 12, 13, 14, 15, 16, 17, 18, 19]