Functions
Functions
Introduction
As the program grow larger in size and complexity, it becomes very difficult to keep track of
the logic. Therefore, at this stage the programs are divided into smaller modules called
functions, where each module can be coded separately and tested. These modules can be
combined into a simple program.
Need for functions
Advantages of Functions
1. Easy to read and understand – the code seems to be easier to understand when
broken down into functions.
2. Code Reuse – function reduces the duplication of code in a program. Once defined,
Python functions can be called multiple times and from any location in a program.
3. Facilitates testing and debugging- Functions enable you to test and debug individual
components of your code independently. This makes it easier to identify and fix
errors without affecting the rest of the program.
4. Faster Development – the entire program is divided into tasks which are assigned to
individual team so that it’s easy to accomplish the program in a faster manner.
5. Reducing complexity of the program-complex program can be broken down into
small sub-problems thereby reducing the complexity of the program.
What is a function?
A function is a named, independent section of code that performs a specific task.
A function is a set of statements that when called perform some specific task.
It is the basic building block of a program that provides modularity and code
reusability.
Types of Functions
1. Built-in Functions
2. User Defined Functions
3. Anonymous Functions
1. Built-in Functions: are the predefined functions which are defined in python. These
functions are a part of python libraries and packages. These are called as pre-defined
functions. Few of the built-in functions are:
a = 100
abs() function – returns the
b = -23
absolute value and removes the
print(abs(a)) 100
negative sign of the number print(abs(b)) 23
print(round(3.4)) 3
round() function – returns the
print(round(7.8)) 8
roundoff value of a number
print(round(-6.7)) -7
print(pow(2,3)) 8
pow() function – returns the result
of the first parameter raised to the print(pow(3,0)) 1
power of second parameter
num= [ 20,13,-3]
sum() function – returns the sum
of members of the iterable object print(sum(num)) 30
like list, tuple , dictionary and
sequence of numbers.
divmod() function – takes two print("divmod(5,4)=" , divmod(5,4)) divmod(5,4)=(1,1)
numbers and returns a pair of
numbers : quotient and remainder. print("divmod(7.5,2.5)=”, divmod(7.5,2.5)) divmod(7.5,2.5)=
This method calculates both x//y (3.0, 0.0)
and x%y
eval() function – this method expr=input("Enter the Expression :") Enter the
parses the expression passed to it Expression : 5-4*2/2
and runs the expression within the x=eval(expr)
program x= 1.0
print("x=",x)
2. User Defined Functions: are functions that are defined by the user to perform a
specific task.
Function Definition
A function definition consists of function’s name, parameters and body. General format is as
shown below:
Example Explanation
In this function definition “max” is
def max (a , b) : the name of the function, ‘a’ and ‘b’
if a > b : are the arguments.
large = a The body contains code to find the
else : largest of two numbers
large = b The function returns the one value
return large ‘large’
Calling a Function
Once the function has been defined, to use that function, you will have to call that function
to perform the defined task. when a program calls a function, program control is transferred
to the called function. A called function returns control to the caller when its return
statement is executed or the function is finished.
There are two ways to call a function depending on whether or not it returns a value
1. If the function returns a value, a call to the function is usually treated as a value.
Example Explanation
i. lar = max(4 ,5) This calls the function max(4,5) and
assigns the result of the function to
the variable lar
ii. print (max(4,5))
This prints the return value of the
function call max(4,5)
2. If the function does not return a value, the call to the function must be a statement.
Example Explanation
we have created function named msg()
# Function definition
this function does not return value,
def msg() :
print (“ python”) hence the function call is a
statement.
#function call
msg()
Output : python
The Return Statement (Fruitful functions)
The Python return statement is used to return a value from a function to the caller. The
keyword return is used for the same. It cannot be used outside of the Python function.
Syntax: return(expression)
The return statement is used for two things: first, it returns a value to the caller. Second, to
end and exit the function and go back to the caller.
Example : return a, b, c
return “bca”, “bba”
Example Output
Enter First number :4
def calculator(num1, num2):
sum = num1 + num2 Enter second number :2
sub = num1 - num2
mul = num1 * num2 Addition = 6
div = num1 / num2
return sum, sub, mul, div subtraction = 2
The void functions are those functions that do not return any value or don’t have any return
statement. The void function can accept any number of arguments and perform operation
inside the function. In void function, python will send a value None referring to the type
called None Type, which denotes the absence of a value.
NOTE: Technically every function in python returns a value whether we use return or not.
if a function does not return a value, by default, it returns a special value None.
Example Output
#void function sum is 300
val=add(100,200)
print(val)
An argument is a piece of data that is passed into a function when the function is called. This
argument is copied to the argument in the function definition.
Types of Arguments
There are various ways to use arguments in a function and it depends on the way we send
the arguments to the function. In python, we have 4 types of function arguments.
1. Positional Arguments
2. Keyword Arguments
3. Default Arguments
4. Arbitrary or Variable Length Arguments
i. Variable-Length Positional Arguments (*args)
ii. Variable-Length Keyword Arguments (**kwargs)
During a function call, values passed through arguments should be in the order of
parameters in the function definition. This is called positional arguments. The first argument
in the call corresponds to the first parameter in the function's definition, the second to the
second parameter, and so on.
Name : kavitha
#function call Course : Bcom
Reg. No. : 11224
student("Rama","BCA",11223)
student("kavitha","Bcom",11224)
Keyword Arguments
Keyword arguments are arguments that are passed to a function using the name of the
argument followed by equal sign and the value of the argument. These arguments need
not be passed in a specific order. The idea is to allow the caller to specify the argument
name with values so that the caller does not need to remember the order of parameters.
Example Output Explanation
#function definition The keyword
Name : Rama arguments
def student(name,course,regno): Course : BCA specify exactly
print("Name :",name) Reg. No. : 11223 which parameter
print("Course :",course) refers to which
print("Reg. No. :",regno) value. We assign
11223 to regno,
Name : kavitha Rama to name
#funcion call Course : Bcom and BCA to
Reg. No. : 11224 course .
student(regno=11223,name="Rama",course="BCA")
student(course="Bcom",regno=11224,name="kavitha")
Default Arguments in Python
Default arguments are values that are given a default value while defining functions.
The assignment operator = is used to assign a default value to the argument.
Default arguments become optional during the function calls. The function will use
default values if no value is provided for the argument when the function is called.
If we provide a value to the default arguments during function calls, it overrides the
default value.
The function can have any number of default arguments.
Default arguments should follow non-default arguments.
#function call with two arguments Both the arguments are passed during the
add(5,10) Sum: 15 function call hence default arguments are
not taken.
#function call with one positional Sum: 50 Only one value is passed as positional
argument during the function call so 30 is
arguments assigned to a and b takes the default value
add(30) 30.
#function call with one keyword Sum: 60 One value is passed as keyword argument,
arguments 50 is assigned to b and default value 10 is
add(b=50) given for a.
If we don’t know the number of arguments needed for the function in advance, we can use
arbitrary arguments. There are two types:
sum(23,34,13) #three
arguments
sum(30,70,80,20) #four
arguments
If a variable in the argument list has two asterisks prefixed to it, the function can accept
arbitrary number of keyword arguments. The variable becomes a dictionary of keyword :
value pairs where the argument name are the keys and arguments are the corresponding
dictionary value.
Example Output Explanation
def addr(**kw): pass two keyword args The function addr() is
defined with **kw as a
for key,value in kw.items(): Name:John variable-length keyword
print (f"{key}:{value}") City:Mumbai argument.
print ("pass two keyword args") pass three keyword args This function is called
twice : first with two
addr(Name="John", Name:Ram keyword arguments and
City="Mumbai") second time with three
City:Mumbai
arguments.
PIN:400001
print ("pass three keyword args")
addr(Name="Ram",
City="Mumbai", PIN="400001")
globalvar=100 globalvar is
declared outside
any function and
def f1() : hence is
accessible both
localvar=50 inside a function
and outside the
print(“globalvar inside f1() :”, globalvar) globalvar inside
function.
f1() :100
print(“localvar inside f1() :”, localvar)
localvar inside f1() :50
f1()
print(x) 100
A variable created inside a function is local by default unless explicitly declared global
To access the global variable inside a function, there is no need to use a global
keyword.
We use the global keyword to a global variable inside a function when we want to do
assignments or when we want to change global variable value.
def add():
global c
add()
Anonymous Functions
Anonymous function is a no-name function declared in a single line. These functions are
called so because they are not declared in the standard manner. lambda keyword is used to
create small anonymous functions. Hence anonymous functions are also called as lambda
functions.
Syntax: lambda arguments : expression
Here, arguments are values passed to the lambda function
expression is executed and result is returned
Lambda function can have any number of arguments but only one expression which
is evaluated and returned.
Lambda functions cannot access variables other than in their parameter list.
Lambda functions cannot even access global variables.
The function can be assigned to a variable to give it a name.
print(sum(10,20,30))
36
print(sqr(n))
Modules
A module is a file consisting of Python code. It can define functions, classes, and variables
and can also include runnable code. Every file with .py extension is called a python file or a
module.
1. Built-in modules are modules that are pre-defined in python and are available in the python
standard library.
2. User-defined modules are the modules created by the users which are custom made to
cater the needs of a certain project.
Importing Module
We can use the module created, by using the import statement:
Syntax: import modulename1 [ , modulename2 ,…..]
Example : import calculation
This gives access to all the functions and variables in the module. When using a function from a
module, use the syntax: module_name.function_name.
Example : calculation.add(10,20)
def add(a,b):
def sub(a,b):
def mul(a,b):
def div(a,b):
Difference = -10
import calculator
Product = 200
Divisiion = 0.5
print(" x = ",calculator.x)
calculator.add(10,20)
calculator.sub(10,20)
calculator.mul(10,20)
calculator.div(10,20)
print(pi)
Python PIP is the package manager for Python packages. We can use PIP to install packages that
do not come with Python. PIP stands for “preferred installer program”. The basic syntax of PIP
commands in the command prompt is:
pip 'arguments'
Python PIP comes pre-installed on 3.4 or older versions of Python. To Check if PIP is installed or
not type the command in the terminal: pip --version
This command will tell the version of the Pip if it is already installed in the system.
We can install additional packages by using the Python pip install command. Let’s suppose we
want to install the Numpy using PIP. We can do it using the below command.
Syntax: pip install numpy
Python provides various ways of dealing with these types of arguments. The three most common
are:
1. Using sys.argv
2. Using getopt module
3. Using argparse module
1. Using sys.argv
It is a basic module that comes with Python distribution from the early versions. The sys
module implements command-line arguments in a simple list structure named sys.argv.
Each list element represents a single argument. The first one -- sys.argv[0] -- is the name of
Python script. The other list elements are sys.argv[1] to sys.argv[n]- are the command line
arguments 2 to n. As a delimiter between arguments, space is used.
Python provides a getopt module that helps you parse command-line options and
arguments. This module provides two functions and an exception to enable command line
argument parsing. getopt.getopt() methodThis method parses the command line options
and parameter list. Following is a simple syntax for this method –
getopt.getopt(args,options,long_options=[])
args − This is the argument list to be parsed.
options − This is the string of short options as list. Options in the argument should be
followed by a colon (:).
long_options – string of long options as list. Options in the argument should be
followed by a equal sign(=)
Using argparse module is a better option than the above two options as it provides
a lot of options such as positional arguments, default value for arguments, help
message, specifying data type of argument etc.