2. What is Function?
• A function is a block of reusable code that is used to perform a
specific action
• In Python, function is a group of related statements that perform a
specific task.
• Functions help break our program into smaller and modular chunks.
As our program grows larger and larger, functions make it more
organized and manageable.
3. Why we use Function?
• Reducing duplication of code
• Decomposing complex problems into simpler pieces
• Improving clarity of the code
• Reuse of code
• Information hiding
4. • There are three types of functions in Python:
1. Built-in function ,which are already pre defined.
2. Anonymous functions, which are also called lambda function
3. User-Defined Functions (UDFs), which are functions that users create
to help them out; And
Types of function
5. Syntax
Function with arguments:-
def function_name (argument1, argument2, ...) :
statement_1
statement_2 ....
Function without arguments:-
def function_name() :
statement_1
statement_2 ....
6. Lambda/Anonymous Forms/Function
• In Python, small anonymous (unnamed) functions can be created
with lambda keyword.
• A lambda function can take any number of arguments, but can only
have one expression.
• Syntax: -
lambda arguments: expression
7. • A function like this:
def mul(x, y):
return (x *y)
print(mul4, 3))
• may also be defined using lambda:
print((lambda x, y: (x + y)/2)(4, 3))
8. Use of Lambda Function in python
• We use lambda functions when we require a nameless function for a
short period of time.
• Lambda functions are used along with built-in functions like filter(),
map() ,reduce(),etc.
• The filter() :- function in Python takes in a function and a list as
arguments.
• Syntax: -
list(filter(lambda arguments: expression, any_list))
9. • The map() function in Python takes in a function and a list.
• Syntax: -
list(map(lambda arguments: expression, any_list))
• The reduce() function in Python takes in a function and a list.
• Syntax: -
(reduce(lambda arguments: expression, any_list))
10. Built-In Function
The function and
specify the required
arguments, then it will
return the results. The
type of the argument
(e.g. string, list, integer,
Boolean, etc…) can be
restricted (e.g. in some
cases it has to be an
integer), but in most
cases it can be multiple
value types.