0% found this document useful (0 votes)
7 views21 pages

Functions

Uploaded by

khushisjain88
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views21 pages

Functions

Uploaded by

khushisjain88
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

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

Functions are used because of following reasons –


1. To improve the readability of code.
2. Improves the reusability of the code, same function can be used in any program
rather than writing the same code from scratch.
3. Debugging of the code would be easier if you use functions, as errors are easy to be
traced.
4. Reduces the size of the code, duplicate set of statements are replaced by function
calls.
5. Usage of user-defined functions leads to modular and structured programming.

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

There are three types of functions in Python programming:

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:

Function Example Output


print(max(10,20,40,30)) 40
max() function – returns the
x=[10,40,30,15]
highest from the list of values .
print(max(x)) 40
Alphabetical comparison will be y=[“cat”,”bat”,”mat”]
made for strings. print(max(y)) mat
print(min(10,20,40,30)) 10
min() function – returns the lowest
x=[10,40,30,5]
from the list of values .
print(min(x)) 5
Alphabetical comparison will be y=[“cat”,”bat”,”mat”]
made for strings. print(max(y)) bat
x=len(“college”)
len() function – returns the
print(x) 7
number of items in the object. The
y=[10,2,3]
object can be list or sequence. print(len(y)) 3

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:

 The first line is known as function header.


 The function header begins with the keyword def, followed by the name of the
function, followed by set of parenthesis (), followed by a colon (:) .
 Parameters are placed inside () through which we pass values to a function. They are
optional.
 A colon : marks the end of function header.
 The function body contains one or more statement. The statements in the function
body must have the same indentation level.
 An optional return statement is used to return values from the function.

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.

 A function that returns value are called fruitfull function.


 A fruitfull function can return any type – string, integer, Boolean etc.
 Everything in python is an object hence return value can be any object such as
numeric (int, float) or collections (list, tuple, dictionary)
 A fruitfull function can also return multiple values using single return statement. a
function can return multiple values by separating them by commas.

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

num1 = int(input("Enter First Multiplication = 8


number :"))
num2 = int(input("Enter second Division = 2.0
number :"))
a,b,c,d = calculator(num1, num2)
print("Addition = ",a)
print("subtraction = ",b)
print("Multiplication = ",c)
print("Division = ",d)

The void functions

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

def add(num1,num2): None


print("sum is", num1+num2)

val=add(100,200)
print(val)

Passing Arguments to Function

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.

There are basically two types of arguments.


1. Actual arguments / parameters - The arguments appearing in the function call
are referred to as actual arguments.

2. Formal Arguments / parameters– The arguments that appear in the function


header (function definition) are referred to as formal parameters. Formal
arguments get their values from the actual arguments of the function call.
Example:
#Here num1 and num2 are formal
parameters
def add(num1,num2): #function
definition
print("sum is", num1+num2)

#Here 100 and 300 are actual parameters


add(100,300) #function call

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)

Positional Arguments in Python

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.

Example Output Explanation


#function definition
Name : Rama The first argument “Rama” from
def student(name,course,regno): Course : BCA function call is assigned to name,
print("Name :",name) Reg. No. : 11223 “BCA” to course and 11223 is
print("Course :",course) assigned to regno.
print("Reg. No. :",regno)

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.

Example: def add(a=10, b=20) :


def add(a=10, b=20, c=30, d=40) :
def add(a, b, c=30, d=40) :

 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.

Example: def add(a, b, c=10, d=20) is valid

def add(a, b=10, c , d=20) is invalid – we cannot have c as non-


default argument after default argument b.

Example Output Explanation


def add(a=10, b=20) :
sum=a+b
print("Sum: ", sum)

#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.

No value is passed during function call.


#function call with no arguments Sum: 30
Hence default value is used for both
add() parameters a and b
Arbitrary Arguments or Variable Length Arguments

If we don’t know the number of arguments needed for the function in advance, we can use
arbitrary arguments. There are two types:

1. Variable-Length Positional Arguments (*args)


Variable-length arguments are declared with (asterisk)* symbol before a parameter in
function definition. We can pass multiple arguments to the function. Internally all these
values are represented in the form of a tuple.
With the use of Arbitrary arguments, we can pass many arguments when calling a function
and can have only one argument in function definition with * symbol.

Example Output Explanation


def sum(*numbers): Sum of numbers : 30 Function sum() accepts
arbitrary argument named
res=0 Sum of numbers : 70 *numbers.
for i in numbers: Sum of numbers : We have called the function
200 sum() three times. First
res=res+i
time with two arguments 10
print(“sum of numbers =”, res) &20. Second time with
three arguments 23,34
&13. Third time with four
sum(10,20) #two arguments arguments(30,70,80,20).

sum(23,34,13) #three
arguments

sum(30,70,80,20) #four
arguments

2. Variable-Length Keyword Arguments (*kwargs)

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")

Scope and lifetime of variables


Local and Global variables
Scope : the scope is the region of a program where we can access a particular variable. A
variable can have one of the two scopes:
1. Global scope
 The variables are defined outside the function.
 A variable that has global scope are called global variables OR a variable that is
defined outside any function or block is called as a Global Variable.
 It can be accessed in any function defined onwards.
2. Local scope
 The variables defined inside a function have local scope.
 A variable that has a local scope are known as Local variables OR a variable that is
defined inside any function or block is called as a Local Variable.
 It can be accessed only in the function or block where it is defined. It exists only till
the function executes.
Lifetime : the lifetime of a variable is a period of time during which the variable is stored in the
memory of the computer.
1. Lifetime of local variable is as long as the function executes. These variables are destroyed as
soon as the function terminates.
2. Life time of global variables is as long as the program executes. These variables are destroyed as
soon as the program terminates.

Example: accessing local variable Output Explanation


inside and outside a function
def display(): Here the variable ‘s’ is local
to the function display(), so
s=”Hello” it can be accessed only
print(“Inside function :”,s) Inside function : Hello within that function.

That’s why we get the error


when we try to access it
display() ouside display()
print(“outside function”,s) NameError: name ‘s’
#trying to access local variable is not defined
outside its scope

Example: accessing global variable inside and Output Explanation


outside a function

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(“globalvar outside f1() :”, globalvar)


globalvar inside
f1() :100

Example: global variable and Output Explanation


global variable have the same
name
x=100 Both global and local variables are named
as x. when x is printed inside f1(), it prints
def f1(): the local variable x value as 200. The
x=200 local variable gets priority than global
variable if the names are same. outside
print(x) the function global variable x is accessible,
hence prints 100.
f1() 200

print(x) 100

The global keyword


In Python, the global keyword allows us to modify the variable outside of the current scope.
The global keyword is used to create global variables from a no-global scope, e.g. inside a function.

 A variable created inside a function is local by default unless explicitly declared global

 A variable declared outside of a function is global by default

 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.

 The use of the global keyword outside of a function is unnecessary.

Example: changing global variable from inside a Output


function using global keyword
c=10

def add():

global c

print("c value inside fn before increment:",c)

c=c+5 c value inside fn before increment: 10

print("c value inside fn after increment:",c)

c value inside fn after increment: 15

add()

print("c value outside function :",c) c value outside function : 15

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.

Example: lambda function to add three numbers Output


sum=lambda a,b,c : a+b+c 60

print(sum(10,20,30))

Example: lambda function to find square of a Output


number
sqr=lambda n : n*n Enter a number :6

36

n=int(input(“Enter a number :”))

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.

Types of modules – there are two types of modules in python

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.

Creating user-defined modules


Any Python file can be referenced as a module that can be imported inside another python
program. To create a module just save the code you want in a file with the file extension .py:

Example: write a function to add two numbers in a file calculation.py


def add(x,y):
print (x+y)

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)

Example: module calculation.py Output


x=999

def add(a,b):

print(" Sum = ",a+b)

def sub(a,b):

print(" Difference = ",a-b)

def mul(a,b):

print(" Product = ",a*b)

def div(a,b):

print(" Divisiion = ",a/b)

#importing the module calculation and use the x = 999


various functions
Sum = 30

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)

Various ways of importing modules


1. Import everything : imports Explanation
everything from a module
Example

This method imports everything from the


math module and the members of the
import math module are accessed using dot notation.
print(“the value of pi is : “, math.pi)

2. Import with renaming : imports Explanation


using an alias name for the module
Example Here, the ‘math’ module is imported with
the alias ‘m’ using the import statement.
# Import the 'math' module with the alias
'm'

import math as m The sqrt function from the ‘math’


module, accessed through the alias ‘m’,
is then used to calculate the square root
of 25.
# Use functions from the 'math' module
with the alias ‘m’

print("Square root of 25:", m.sqrt(25))

3. Import using ‘from’ : to import Explanation


specific names from a module
without importing the module as a
whole
Example Here, we imported only the ‘pi’ attribute from the
‘math’ module
# Import only pi from 'math' module

from math import pi

print(pi)

4. Import all names : imports Explanation


everything from the module , the
difference being that dot notation is
not needed to access the members
from math import * Here, we have imported all the definitions from the
math module with * symbol.
print(pi)
No need of dot notation to access the pi value and
print(factorial(6)) factorial() .

Commonly used modules


1. Module name: math  it contains different type of mathematical function. Most of the
functions returns float value. We need to import it using import math statement.
2. Module name: random it contains different functions used for generating random
numbers. We need to import it using import random statement.
3. Module name: statistics it contains different functions used for calculating statistics of
numeric data. We need to import it using import statistics statement.
Modules Vs Packages Vs Library
The module is a simple Python file that contains collections of functions and global
variables and with having a .py extension file.

Examples: Datetime, Random etc.

The package is a simple directory having collections of modules.

Examples: Numpy , Pandas

A package is a collection of modules, a library is a collection of packages.

Examples: Matplotlib, Pytorch

What is Package Manager?


Package manager is software to install any external libraries or packages. It handles installing,
uninstalling and managing any packages or libraries. Example – python pip
What is Python PIP?

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'

How to Install Python PIP?

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.

How to Install Package with Python PIP?

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

How to remove package using PIP?


To remove a package type and run the following command in command line
Syntax: pip uninstall numpy

Listing and Searching package using PIP


To list the packages use the command: pip list
To search for a particular package, use the command: pip search numpy

Command Line Arguments


Python Command Line Arguments provides a convenient way to accept some information at
the command line while running the program. The arguments that are given after the name
of the program in the command line shell of the operating system are known as Command
Line Arguments.
Syntax: c:\python filename.py arg1,arg2, ……argn

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.

Example : hello.py Output

import sys C:\Python311>python hello.py 10 20


print ('argument list', sys.argv) argument list ['hello.py', '10', '20']
first = int(sys.argv[1]) sum = 30
second = int(sys.argv[2])
print ("sum = {}".format(first+second))

2. Using getopt Module

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(=)

3. Using argparse Module

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.

You might also like