Functions
• Functions are used when you have a block of statements that
needs to be executed multiple times within the program.
• Functions also reduce the size of the program by eliminating
rudimentary code.
• Two main advantages of function
– Divide our program into multiple task
– Provide a code reuse mechanism
– and they allow us to hide the details once we have completed part
of our program.
• A function can be called any number of times or in multiple
locations
• Functions can be either Built-in Functions or User-defined
functions.
• The Python interpreter has a number of functions that are built
into it and are always available. some of the built-in functions
like input(), print(), range() etc.
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
Types of Functions
• Making programs modular and reusable is one of the
fundamental goals of any programming language and
functions help to achieve this goal.
• there are two types of functions in Python; built-in
functions and user-defined functions.
• Built-in functions are those provided by the language.
Ex- len(),min(),max()…
• Python comes with many built-in modules as part of
the standard library.
• User-defined functions are reusable code blocks
created by users to perform some specific task in the
program. user-defined functions are those written by
developers .
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
How Functions Work
• When a function is called (or invoked)
the flow of control a program jumps
from where the function was called to
the point where the function was
defined.
• The body of the function is then
executed before control returns back to
where it was called from i.e. Once the
function finishes it returns to the point
at which the function was called.
• You can create your own functions and
use them as and where it is needed.
• Defining a function does not execute it.
Defining a function simply names the
function and specifies what to do when
the function is called.
• Calling the function actually performs
the specified actions with the indicated
parameters.
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
• In Python, a function definition consists of the def keyword.
• A function can (optionally) have a list of parameters which allow data to be passed into
the function.
• The syntax for function call or calling function is,
• function_name(argument_1, argument_2,…,argument_n)
• Arguments are the actual value that is passed into the calling function. There must be a
one to one correspondence between the formal parameters in the function definition
and the actual arguments of the calling function
• A function should be defined before it is called and the block of statements in the
function definition are executed only after calling the function.
• Put all the relevant necessary calling functions inside the main() function definition.
Since the above program is a stand-alone main source program, Python interpreter
assigns the string value "__main__" to the built-in special variable __name__ which is
Manoj Chauhan , Assist. Professor ,
6/10/2021
checked for equality using if condition RBSMTC ,Agra
Returning Values from Functions
• It is very common to want to return a value from a function. In
Python this can be done using the return statement
• The return statement terminates the execution of the function
definition in which it appears and
• returns control to the calling function.
• It can also return an optional value to its calling function.
• In Python, it is possible to define functions without a return
statement.
• Functions like this are called void functions, and they return None.
• A function can return only a single value, but that value can be a list
or tuple.
• def square(n):
return n * n
result = square( 4)
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
Median of Three Values
• def median(a, b, c):
• if a < b and b < c or a > b and b > c:
• return b
• if b < a and a < c or b > a and a > c:
• return a
• if c < a and b < c or c > a and b > c:
• return c
• #The median of three values is the sum of the values, less the smallest, less the largest.
• def alternateMedian(a, b, c):
• return a + b + c - min(a, b, c) - max(a, b, c)
• def main():
• x = float(input("Enter the first value: "))
• y = float(input("Enter the second value: "))
• z = float(input("Enter the third value: "))
• print("The median value is:", median(x, y, z))
• print("Using the alternative method, it is:",alternateMedian(x, y, z))
• # Call the main function
• main() Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
Function Parameters
• Communication with functions is done using parameters/arguments
passed to it and the value returned from it
• A parameter is a variable defined as part of the function header and is
used to make data available within the function itself.
• An argument is the actual value or data passed into the function when it
is called. The data will be held within the parameters.
• There must be a one to one correspondence between the formal
parameters in the function definition and the actual arguments of the
calling function.
• def area_trapezium(a, b, h):
area = 0.5 * (a + b) * h
print(f"Area of a Trapezium is {area}")
• def main():
area_trapezium(10, 15, 20)
• if __name__ == "__main__":
Manoj Chauhan , Assist. Professor ,
6/10/2021
main() RBSMTC ,Agra
Types of Arguments
• Arguments in a python can be of four types
• Positional arguments-arguments must be passed
in correct order.
• Keyword arguments –can be passed out of order.
It uses variable names to match arguments in
function definition.
• Variable length positional arguments- when no
of positional arguments to be passed is not
certain.
• Variable length keyword arguments- when no of
keywords arguments to be passed is not certain.
• In a call we can use positional as well as keyword
arguments. Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
def print_info(i,a ,str):
print(i , a ,str )
print_info(10,12.5,”Agra”)
print_info(str=”Agra” , i=10,a=12.5)
print_info(10, str=”Agra” , a=12.5)
print_info(str=”Agra” , j=10,a=12.5)
print_info(”Agra”,10,12.5)
print_info(10,12.5)
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
sometimes no of positional arguments to be passed is not certain.
• In such cases variable-length positional arguments can be received
using *args.
• * indicate that it will hold all the arguments passed to calling
function.
def print_info(*args):
print()
for itm in args:
print(itm, end=‘’)
print_info(10)
print_info(10,12.5)
print_info(10,12.5,”Agra”)
print_info(10,12.5,”Agra”,”India”)
The tuple can be iterated through using for loop.
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
sometimes no of keyword arguments to be passed is not certain.
• In such cases variable-length keyword arguments can be received
using **kwargs.
• ** indicate that it will hold all the arguments passed to calling
function.
def print_info(**kwargs):
print()
for itmkey, itmvalue in [Link]():
print(itmkey, itmvalue, end=‘’)
print_info(i=10)
print_info(i=10,a=12.5)
print_info(i=10,a=12.5,str=”Agra”)
print_info(i=10,a=12.5,city=”Agra”, country=”India”)
dct={0:’Sun’ , 1:’Mon’ , 2:’Tue’ , 3:’Wed’ 4:’Thu’ , 5:’Fri’ , 6:’Sat’}
print_info(**dct)
kwargs used in definition is a dictionary
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
Scope and Lifetime of Variables
• Python programs have two scopes: global and local.
• A variable that is defined inside a function definition is a local
variable.
– The lifetime of a variable refers to the duration of its existence.
– The local variable is created and destroyed every time the function
is executed, and
– it cannot be accessed by any code outside the function definition.
– Local variables inside a function definition have local scope and
exist as long as the function is executing.
• A variable is a global variable if its value is accessible and
modifiable throughout your program.
– Global variables have a global scope.
– It is possible to access global variables from inside a function, as
long as you have not defined a local variable with the same name.
• A local variable can have the same name as a global variable,
but they are totally different so changing the value of the local
variable has no effect on the global variable.
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
• test_variable = 5
• def outer_function():
test_variable = 60
def inner_function():
• test_variable = 100
• print(f"Local variable value of {test_variable} having local scope to inner function is displayed")
inner_function()
print(f"Local variable value of {test_variable} having local scope to outer
function is displayed ")
• outer_function()
• print(f"Global variable value of {test_variable} is displayed ")
• Python use the keyword global with the name of the variable for updating result of
variable everywhere!
• max = 100
• def print_max():
• global max
• max = max + 1
• print(max) Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
scope and lifetime of variables
1. The scope of a variable is the part of a program where
the variable is known.
• Parameters and variables defined inside a function are
not visible from outside.
• Hence, they have a local scope.
2. The lifetime of a variable is the period throughout
which the variable exits in the memory of your Python
program.
The lifetime of variables inside a function is as long as the
function executes.
These local variables are destroyed as soon as the
function returns or terminates. This means that the
function does not store the values in a variable from
one invocation to another.
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
Default Parameters
• In some situations, it might be useful to set a default
value to the parameters of the function definition.
• Each default parameter has a default value as part of its
function definition.
• Any calling function must provide arguments
• for all required parameters in the function definition but
can omit arguments for default parameters.
• If no argument is sent for that parameter, the default
value is used.
• Usually, the default parameters are defined at the end of
the parameter list
• The default value is evaluated only once.
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
• def work_area(prompt, domain="Data Analytics"):
• print(f"{prompt} {domain}")
def main():
• work_area("Sam works in")
• work_area("Alice has interest in", "Internet of Things")
• if __name__ == "__main__":
main()
• Output
• Sam works in Data Analytics
• Alice has interest in Internet of Things
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
• Command Line Arguments-
• Command line arguments is a methodology in
which user will give inputs to the program through
the console using commands.
• A Python program can accept any number of
arguments from the command line.
• You need to import sys module to access command
line arguments.
• To execute a command line argument program, you
need to navigate to the directory where your
program is saved.
• Then issue a command in the format
• python file_name argument_1 argument_2
argument_3 …… argument_n.
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
• >>> python [Link] arg1 arg2 arg3
• The Python sys module provides access to any command-line arguments via the [Link].
• This serves two purposes-
• [Link] is the list of command-line arguments.
• len([Link]) is the number of command-line arguments.
• Here [Link][0] is the program i.e. the script name
• Consider the following script [Link]-
– import sys
– print ('Number of arguments:', len([Link]), 'arguments.')
– print ('Argument List:', str([Link]))
• Program to Demonstrate Command Line Arguments in Python
• import sys
• def main():
print(f"[Link] prints all the arguments at the command line including file name {[Link]}")
print(f"len([Link]) prints the total number of command line arguments including file
name {len([Link])}")
print("You can use for loop to traverse through [Link]")
for arg in [Link]:
print(arg)
• if __name__ == "__main__":
• main()
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
Recursion
• Set of statements in a function can be repeat in two ways
• By using while or for loop –i.e. iteration
• By calling the function from within itself –i.e. recursion
• A recursive solution in a programming language such as Python is one in which
a function calls itself one or more times in order to solve a particular
problem.
• Functions that solve problems by calling themselves are referred to as
recursive functions.
• def recfun():
– print(‘continue..’)
– recfun() # recursive call
• However, if such a function does not have a termination point then the
function will go on calling itself to infinity (at least in theory). In most
languages such a situation will (eventually) result in an error being generated.
• For a recursive function to the useful it must therefore have a termination
condition.
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
The termination condition may be because:
• • A solution has been found (some data of interest in a tree
structure).
• • The problem has become so small that it can be solved
without further recursion.
• A base case is a problem that can be solved without further
recursion.
• Some maximum level of recursion has been reached, possibly
without a result being found/generated.
• A recursive function is a function that calls itself. Such
functions normally include one or more base cases and one
or more recursive cases
• Recursive calls terminate when the base case condition is
satisfied .
• Alternatively a function to generate a factorial number might
call itself passing in a smaller number to process etc.
• factorial(n)=1 if n=0 # base case
= n* factorial(n-1) if n>0 # recursive case
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
# Compute the sum of the integers from 0 up to and including
n using recursion
• # @param n the maximum value to include in the sum
• # @return the sum of the integers from 0 up to and
including n
• def sum_to(n):
if n <= 0:
return 0 # Base case
else:
return n + sum_to(n - 1) # Recursive case
• # Compute the sum of the integers from 0 up to and
including a value entered by the user
• num = int(input("Enter a non-negative integer: "))
• total = sum_to(num)
• print("The total of the integers from 0 up to and including",
num, "is", total) Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
When to use recursion
• Recursion is useful when a problems requires an
unknown number of loops
Ex- traversing a binary tree data structure
,Traversing a graph data structure
• Recursion is also useful when a problems can be
solved by breaking it down into similar sub
programs
Ex- finding factorial value of a number ,Finding sum
of digit of n integer number
• Everything you can do with recursion can also be
done by loops, but sometimes a recursive function
is more readable.
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
• Disadvantages of Recursion-
• Recurive functions are slow since passing value and control
to a function and returning value and control will slow down
the execution of the function
• it is not as efficient as iteration. This is because a function
call is more expensive for Python to process that a for loop.
Because during execution several set of variables get
created.
• Too many recursive calls may result into an error. Default
recursion limit in python is aprox. 10^[Link] we provide a large
input to the recursive function a RecursionError will be
raised.
• to improve the performance of a recursive solution , A tail
recursive solution is one in which the calculation is
performed before the recursive call.
• However, it should be noted that Python currently does not
perform tail recursion optimization; so this is a purely a
theoretical exercise.
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
Types of Recursion
• Two types of recursions can exist
• Head recursion –First recursive call is made before other processing i.e. In head
recursive we don’t get the result until we have returned from every recursive
call.
• def headrecfun(n):
if n==0:
return
else :
headrecfun(n-1)
print(n)
Number get printed in ther order 1 to 10
• Tail recursion- Recursive call is made after other processing.
• def tailrecfun(n):
if n==11:
return
else :
print(n)
tailrecfun(n+1)
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
Nested functions
• Nested function- When a function is defined inside another
function then this is called nesting of functions, where, the
function inside which another function is defined is called
the outer function and the function which is defined inside
another function is called the inner function.
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
Anonymous Functions
• All the functions have a name that they can be referenced by, such as my_function etc.
• This means that we can reference and reuse these functions as many times as we like.
• In Python an anonymous function is one that does not have a name and can only be
used at the point that it is defined.
• Anonymous functions are defined using the keyword lambda and for this reason they
are also known as lambda functions.
• The syntax used to define an anonymous function is:
• lambda arguments: expression
• Anonymous functions can have any number of arguments but only one expression
(that is a statement that returns a value) as their body
• As an example, let us define an anonymous function that will square a number:
• double = lambda i : i * i
• The whole anonymous function is then stored into a variable called double.
• To invoke the function, we can access the reference to the function held in the variable
double and then use the round brackets to cause the function to be executed, passing
in any values to be used for the parameters:
• print(double(10))
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
Docstring
• However, as functions become more complex and may have multiple parameters the
documentation provided can become more important.
• The docstring allows the function to provide some guidance on what is expectedin terms
of the data passed into the parameters, potentially what will happen if the data is
incorrect,as well as what the purpose of the function is in the first place
• Docstring is optional
• The docstring can be read directly from the code via a very special property of the function
called __doc__ that is accessible via the name of the function using the dot notation:
• print(functionname.__doc__)
• def get_integer_input(message):
""“ This function will display the message to the user and request that they input an
integer.
If the user enters something that is not a number then the input will be rejected and an
error message will be displayed.
The user will then be asked to try again."""
value_as_string = input(message)
while not value_as_string.isnumeric():
print('The input must be an integer')
value_as_string = input(message)
Manoj Chauhan , Assist. Professor ,
return int(value_as_string)
6/10/2021
RBSMTC ,Agra
• In Python there is no concept of the main() function
like in languages of C family (C, C++, Java, C# etc.)
needs the main() function to indicate the starting point
of execution., on the other hand, as it is an interpreter
based language and can be equally used in an
interactive shell.
• The Python program file with .py extension contains
multiple statements. The execution of the Python
program file starts from the first statement.
• Python includes the special variable called __name__
that contains the scope of the code being executed as a
string. __main__ is the name of the top-level scope in
which top-level code executes.
• All the functions and modules will be executed in the
top-level scope __main___ in the interpreter shell.
• A Python file can contain multiple functions and
statements that can be executed independently.
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
Modules and Packages
• Modular programming is the process of breaking a large programming task into
separate, smaller, more manageable subtasks or modules.
• Modules and packages are two constructs used in Python to organize larger
programs
• Module-A module allows you to group together related functions, classes and
code in general.
• It is useful to organise your code into modules when the code either becomes
large or when you want to reuse some elements of the code base in multiple
projects .
• In Python a module equates to a file containing Python code. A module can
contain
– • Functions
– • Classes
– • Variables
– • Executable code
– • Attributes associated with the module such as its name.
• Functions, modules and packages are all constructs in Python that promote code
Manoj Chauhan , Assist. Professor ,
modularization.
6/10/2021
RBSMTC ,Agra
Breaking up a large body of code from a single file helps with
simplifying code maintenance and comprehensibility of code,
testing, reuse and scoping code. These are explored below:
• • Simplicity—This means that individual modules can be
simpler than the overall solution.
• • Maintenance—It helps to distinguish one body of code
from another so makes it easier to work out where changes
should go.
• Testing—As one module can be made independent of
another module there are less dependencies and cross overs.
This means that a module can be tested in isolation.
• Reusability—Defining a function or class on one module
means that it is easier to reuse that function or class in
another module.
• Scoping—Modules typically also define a namespace, that is a
scope within which each function or class is unique.
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
• Modules Are Used to Define Things –
• That means that any classes or functions you define, and any variables you
assign a value to, become attributes of the module.
• Modules in Python are reusable libraries of code having .py extension, which
implements a group of methods and statements.
• Python comes with many built-in modules as part of the standard library.
• To use a module in your program, import the module using import statement.
• All the import statements are placed at the beginning of the program.
• The syntax for import statement is,
• import module_name
• >>>import math
• The syntax for using a function defined in a module is,
• module_name.function_name()
• >>> print([Link](4))
• >>> dir(math)
• Various functions associated with math module is displayed
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
• What’s in a Module -To find out what a module contains, you can use the
dir function, which lists all the attributes of an object (and therefore all
functions, classes, variables, and so on of a module).
• Any Python program can be imported as a module
• When you import a module, you may notice that a new file appears—like
c:\python\ [Link]. The file with the .pyc extension is a (platform-
independent) processed (“compiled”) Python file
• Defining a Function in a Module-A Simple Module Containing a Function
• # [Link]
• def hello():
print "Hello, world!“
• You can then import it like this:
• >>> import hello2
• The module is then executed, which means that the function hello is
defined in the scope of the module, so you can access the function like this:
• >>> [Link]()
• Hello, world!
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
• Making Your Modules Available-There are two ways of doing this: put your
module in the right place or tell the interpreter where to look
• When the interpreter executes the above import statement, it searches
for .py file in a list of directories assembled from the following sources:
• The directory from which the input script was run or the current directory if
the interpreter is being run interactively
• The list of directories contained in the PYTHONPATH environment variable, if it
is set.
• An installation-dependent list of directories configured at the time Python is
installed
• The resulting search path is accessible in the Python variable [Link], which is
obtained from a module named sys:
• The exact contents of [Link] are installation-dependent.
• >>> import sys
• >>> [Link] ['', 'C:\\Users\\john\\Documents\\Python\\doc',
'C:\\Python36\\Lib\\idlelib', 'C:\\Python36\\[Link]',
'C:\\Python36\\DLLs', 'C:\\Python36\\lib', 'C:\\Python36',
'C:\\Python36\\lib\\site-packages']
• 6/10/2021
Look through your [Link] Manoj and Chauhan
find your
, [Link]-packages
Professor , directory, and save the
RBSMTC ,Agra
module in it.
• Putting Your Module in the Right Place-It’s just a matter of
finding out where the Python interpreter looks for modules
and then putting your file there.
• Thus, to ensure your module is found, you need to do one of
the following:
• Put <Scriptname>.py file in the directory where the input
script is located or the current directory, if interactive
• Modify the PYTHONPATH environment variable to contain
the directory where <Scriptname>.py is located before
starting the interpreter
– Or: Put [Link] in one of the directories already contained in
the PYTHONPATH variable
• Put <Scriptname>.py in one of the installation-dependent
directories, which you may or may not have write-access to,
depending on the OS
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
• Telling the Interpreter Where to Look-Putting your module in the correct
place might not be the right solution for you for a number of reasons:
– • You don’t have permission to save files in the Python interpreter’s
directories.
– • You would like to keep your modules somewhere else.
• Include your module directory (or directories) in the environment
variable PYTHONPATH
• Environment variables are not part of the Python interpreter
• In Windows, you may be able to edit environment variables from your
Control Panel
• In the Control Panel, double-click the System icon.
• In the dialog box that opens, select the Advanced tab and click the
Environment Variables button.
• If you see PYTHONPATH there already, select it, click Edit, and edit it.
• If you want to add the directory
• C:\python, type the following:
• set PYTHONPATH=%PYTHONPATH%;C:\python
• Naming Your Module-As you may have noticed, the file that contains the
code of a module must be given the same name as the module, with an
additional .py file name extension.
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
#[Link]
• def median(a, b, c):
• if a < b and b < c or a > b and b > c:
• return b
• if b < a and a < c or b > a and a > c:
• return a
• if c < a and b < c or c > a and b > c:
• return c
• def alternatemedian(a, b, c):
• return a + b + c - min(a, b, c) - max(a, b, c)
• #[Link]
• import medianfunct
• #import sys
• #[Link]('c:/Python')
• def main():
• x = float(input("Enter the first value: "))
• y = float(input("Enter the second value: "))
• z = float(input("Enter the third value: "))
• print("The median value is:", [Link](x, y, z))
• print("Using the alternative method, it is:",[Link](x, y, z))
• # Call the main function Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
• main()
Module Properties
• Every module has a set of properties that can be used to find what features it
provides, what its name is, what (if any) its documentation string is etc.
• These properties are considered special as they all start, and end, with a
double underbar ('__'). These are:
• • __name__ the name of the module
• • __doc__ the doctoring for the module
• • __file__ the file in which the module was defined.
• For example:
• import module_name
• print(module_name.__name__)
• print(module_name.__doc__)
• print(module_name.__file__)
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
• Modules as Scripts- Any Python file is not only a
module but also a Python script or program. This means
that it can be executed directly if required.
• In Python we can distinguish between when a file is
loaded as a module and when it is being run as a
standalone script/program.
• This is because Python sets the module property
__name__ to the name of the module when it is being
loaded as a module; but if a file is being run as a
standalone script (or the entry point of an application)
then the __name__ is set to the string __main__.
• If __name__==‘__main__’:
– #work as a script
• Else :
– #work as a module
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
•
Importing Python Modules
Importing a module makes the functions, classes and variables defined in the
module visible to the file they are imported into.
• For example, to import all the contents of the utils module into a file called
• import utils #importing an entire module
• A variant of the import statement allows us to import everything from a
particular module and remove the need to prefix the modules functions or
classes with the module name, for example:
• from <module name> import *
• The problem with this form of import is that it can result in name clashes as it
brings into scope all the elements defined in the utils module
• from utils import Shape #importing specific module entities
• Now only the Shape class has been imported into the file and made directly
available.
• You can even give an alias for an element being imported from a module using
the import statement
• import utils as utilities
• Hiding Some Elements of a Module-By default, any element in a module whose
name starts with an underbar ('_')
Manoj is hidden
Chauhan when
, Assist. Professor , a wildcard import of the
6/10/2021
RBSMTC ,Agra
contents of a module is performed.
Reloading modules
• You can reload a module that has previously been loaded by calling the
built in function reload()
• It takes a single argument (the module you want to reload) and returns
the reloaded module.
• This may be useful if you have made changes to your module and want
those changes reflected in your program while it is running
• >>> hello = reload(hello)
• Hello, world!
• Here, I assume that hello has already been imported (once). By
assigning the result of reload to hello, I have replaced the previous
version with the reloaded one.
• Note that the reload function has disappeared in Python 3.0. While you
can achieve similar functionality using exec, the best thing in most cases
is simply to stay away from module reloading.
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
• Python comes with many built-in modules as well as many more
available from third parties.
• Sys=The sys module gives you access to variables and functions
that are closely linked to the Python interpreter.
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
• os-The os module gives you access to several
operating system services. The os module is extensive;
only a few of the most useful functions and variables
are described in Table
• Python os module provides a portable way of using
operating system dependent functionality
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
Packages
• We organize a large number of files in different folders and subfolders
based on some criteria, so that we can find and manage them easily.
• To structure your modules, we can group them into packages.
• A package can contain one or more relevant modules.
• A package is actually a folder containing one or more module files.
• While a module is stored in a file (with the file name extension .py), a
package is a directory.
• To put modules inside a package, simply put the module files inside the
package directory.
• A package is defined as
• • a directory containing one or more Python source files and
• • an optional source file named __init__.py. This file may also contain
code that is executed when a module is imported from the package ,an
empty __init__.py file makes all functions from the above modules
available when this package is imported.
• Note- Packages can contain sub packages to any depth you require.
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
• A package is defined by creating a directory with the same name as the
package and then creating the file _init_.py within that [Link] file
contains the necessary instruction to the Python interpreter to allow the
importing of modules within the package.
• For example, the following picture illustrates a package utils containing two
modules classes and functions.
• In this case the __init__.py file contains package level initialisation code:
• The contents of the __init__.py file will be run once, the first time either
module within the package is referenced.
• The functions module then contains several function definitions; while the
classes module contains several class definitions.
• Here we can import both the functions module and the classes module from
the utils package.
• Importing a Module from a Package
• from <mypackage> import <functions>
• [Link](3,5,2)
Manoj Chauhan , Assist. Professor ,
6/10/2021
RBSMTC ,Agra
Namespaces
Namespace map names – variables , functions , and modules – to
objects .
Namespaces themselves are just dictionary –like objects where the
keys of the dictionary refer to the name of and the value is a
reference to the actual object. A typical script is made up of
multiple namespaces .
LGB Rule- The L in LGB refer to the local namespace and is the
namespace where names are defined and searched relative to the
current execution frame. The G in LGB refer to the global
namespace and contains the variables declared in global
statement . The B in LGB refer to the built in functions and objects.
The NameError exception is raised if a given name cannot be
resolved through the LGB rule.
Remember that the global namespace do not nest.
Dictionary of identifiers in globale and local namespaces can be
obtained using built-in function
6/10/2021
Manoj Chauhan ,globals()
Assist. Professor , and locals()
RBSMTC ,Agra