0% found this document useful (0 votes)
3 views

Unit-3_Python Functions

The document provides an overview of functions in Python, explaining their purpose, advantages, and structure. It covers function definitions, types of functions, parameters, arguments, and introduces concepts like lambda, filter, map, and reduce functions. Additionally, it discusses recursion and the effects of local and global variables in Python programming.

Uploaded by

shantanu270805
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit-3_Python Functions

The document provides an overview of functions in Python, explaining their purpose, advantages, and structure. It covers function definitions, types of functions, parameters, arguments, and introduces concepts like lambda, filter, map, and reduce functions. Additionally, it discusses recursion and the effects of local and global variables in Python programming.

Uploaded by

shantanu270805
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Functions

● In Python, a function is a group of statements that are used to perform a


specific task.

● Functions help to break our program into smaller modules and make our
program more organized, readable.
Function arguments and parameters
Some Advantages of Functions:
● Complex codes can be divided into smaller parts.

● Once function is written, it can be reused as and when required. This helps
programmer to avoid writing the same code again and again.

● Functions provide modularity in a code.

● Code maintenance becomes very easy. To add any new feature in the code, just
create new functions and if the user does not want any specific feature, that can be
removed from the code.
● When there is an error in the software, the corresponding function can be modified
without disturbing any other functions in the software. This makes code debugging
will become easy.
● The use of functions in a program will reduce the length of the program.
Use of Function:
Example: Suppose we have been asked to find the sum of numbers starting
from 1 to 10, 15 to 25 and 30 to 50. Without function we will write the code in
the following manner:
With use Of Function:
Definition of Function:

Syntax is:
def functionName(p1, p2, …):
statement1
statement2

return expression

Note—
● def is the keyword
● Use of parentheses i.e,( ) after function name.
● p1, p2, .. are the parameters
● Colon(:) sign at the end of the function name.
Example—
def user_function( ):
print("Hello...Welcome Back")
Types of Functions in Python

Below are the different types of functions in Python:

● Built-in library function: These are Standard functions in Python that are available to
use.
● Example: range(), id() , type(), input() ,print() etc.
Note:
id() Function: In Python, id() function is a built-in function that returns the unique identifier
of an object. The identifier is an integer, which represents the memory address of the object.
The id() function is commonly used to check if two variables or objects refer to the same
memory location.

Syntax: id(object)
Return: a unique integer for a given object
Example:1
Note:
● ID is a Memory Address: The id() function returns a unique identifier (memory address) for an object.

● Id() Function on different data types: Immutable data types (strings, tuples) can sometimes share IDs due to optimizations, while
mutable types (lists, sets, dictionaries) will not share IDs unless they reference the same object .
● User-defined function: We can create our own functions based on our requirements.

Example 2:
Working of Function
● To call a function in our code, use the function name followed by parenthesis()
Note:

● If we want to perform a task repetitively, then it is not necessary to re-write the


particular block of the program repeatedly.

● That particular block of statements can be shifted in a user-defined function.

● The function can be called any number of times to perform the task.

● Large programs can be reduced to smaller ones using functions. It is easy to


debug i.e. find out the errors in it and hence, it also increases readability.
Parameters:

A parameter is the variable defined within the parentheses during function definition. Simply they are written
when we declare a function.

Example Of Parameters:

Arguments:
An argument is a value that is passed to a function when it is called. It might be a variable, value or object
passed to a function or method as input. They are written when we are calling the function.

Example Of Arguments:
Types Of Argument:

A function may use the following types of formal arguments:

● Required arguments

● Keyword arguments

● Default arguments

● Variable-length arguments
Positional Arguments:
Positional Arguments are needed to be included in proper order i.e the first argument is always
listed first when the function is called, second argument needs to be called second and so on.
Example:
Keyword Arguments:

Keyword Arguments is an argument passed to a function or method which is preceded by a keyword and an
equal to sign. The order of keyword argument with respect to another keyword argument does not matter
because the values are being explicitly assigned.

Example:
Default Arguments

● In a function, arguments can have default values. We assign default values to the argument using
the ‘=’ (assignment) operator at the time of function definition. You can define a function with any
number of default arguments.
● The default value of an argument will be used inside a function if we do not pass a value to that
argument at the time of the function call. Due to this, the default arguments become optional during
the function call.
Important points to remember about function argument
Point 1: Default arguments should follow non-default arguments.

Point 2: keyword arguments should follow positional arguments only.


Point 3: The order of keyword arguments is not important, but All the keyword arguments passed must match one of
the arguments accepted by the function.

Point 4: No argument should receive a value more than once.


Point 5: Default Arguments Are Optional Arguments
(Giving only the mandatory arguments:)
4.Variable-length arguments
● Variable-length arguments refer to a feature that allows a function to accept a variable number
of arguments in Python. It is also known as the argument that can also accept an unlimited
amount of data as input inside the function. There are two types in Python:
● Non – Keyworded Arguments (*args)
● Keyworded Arguments (**kwargs)

*args
● When we are not sure about the number of arguments being passed to a function
then we can use *args as function parameter.
● *args allow us to pass the variable number of Non Keyword Arguments to function.
● We can simply use an asterisk * before the parameter name to pass variable length
arguments.
● These arguments are collected into a tuple within the function and allow us to
work with them.
Examples of *args :

Output:
Example 3: Example 4: Unpacking of Arguments
2. **kwargs
● **kwargs allows us to pass the variable number of Keyword Arguments to
the function.
● We can simply use an double asterisk ** before the parameter name to
pass variable length arguments.
● The arguments are passed as a dictionary.

Example of **kwargs
Example 2:
Combining *args and **kwargs
Lambda, Filter, Map and Reduce Functions
1. Lambda
● A lambda function is an anonymous function (function without a name).
● Lambda functions can have any number of arguments but only one
expression. The expression is evaluated and returned.
● We use lambda functions when we require a nameless function for a short
period of time.
Example
Filter
● It is used to filter the iterables/sequence as per the conditions.
● Filter function filters the original iterable and passes the items that returns
True for the function provided to filter.
● It is normally used with Lambda functions to filter list, tuple, or sets.
● filter() method takes two parameters:
● function - function tests if elements of an iterable returns true or false
● iterable - Sequence which needs to be filtered, could be sets, lists,
tuples, or any iterators
Map
● The map() function applies a given function to each item of an iterable (list,
tuple etc.) and returns a list of the results.
● map() function takes two Parameters :
● function : The function to execute for each item of given iterable.
● iterable : It is a iterable which is to be mapped.
● Returns : Returns a list of the results after applying the given function to
each item of a given iterable (list, tuple etc.)
Reduce

● The reduce() function is defined in the functools python module.The


reduce() function receives two arguments, a function and an iterable.
However, it doesn't return another iterable,instead it returns a single value.
Working:
1) Apply a function to the first two items in an iterable and generate a partial
result.
2) The function is then called again with the result obtained in step 1 and the
next value in the
sequence. This process keeps on repeating until there are items in the
sequence.
3) The final returned result is returned and printed on console.
Note:

The purpose of using lambda, filter, map, and reduce functions is to make data
processing easier, more efficient, and expressive in Python. Here’s how each
contributes:

1. Lambda Functions: Provide anonymous, one-line functions without the need to


formally define them, ideal for quick calculations or transformations.
2. Filter: Extracts elements from a collection based on a condition, simplifying data
filtering without loops.
3. Map: Applies a function to each element in a collection, allowing efficient
transformations on datasets.
4. Reduce: Aggregates all elements in a collection into a single result, like summing
or finding a product, useful for calculations requiring accumulation.
Examples:
Recursion In Python:

● it is a process in which a function calls itself directly or indirectly.

Advantages of using recursion


● A complicated function can be split down into smaller subproblems utilizing recursion.
● Sequence creation is simpler through recursion than utilizing any nested iteration.
● Recursive functions render the code look simple and effective.

Disadvantages of using recursion


● A lot of memory and time is taken through recursive calls which makes it expensive for use.
● Recursive functions are challenging to debug.
● The reasoning behind recursion can sometimes be tough to think through.
Effect of Local and Global Variables:
Python Local Variables
Local variables in Python are those which are initialized inside a function and belong only to that particular
function. It cannot be accessed anywhere outside the function.
Python Global Variables
These are those which are defined outside any function and which are accessible throughout the
program, i.e., inside and outside of every function.
Thank you

You might also like