Modules in Python

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 37

Function -

>Module -
>package
FUNCTION TYPES
Functions can be categorized as -
i. Modules
ii. Built in
iii. User Defined
MODULES
 As program gets longer, need to organize them for easier
access and easier maintenance.
 Reuse same functions across programs without copying its
definition into each program.
 Python allows putting definitions in a file
 use them in a script or in an interactive instance of the interpreter
 Such a file is called a module
 definitions
from a module can be imported into other modules or
into the main module

3
Programming 5/7/23
MODULE
 A module is a file containing Python definitions
(i.e. functions) and statements.
 Standard library of Python is extended as
module(s) to a programmer. Definitions from the
module can be used within the code of a
program. To use these modules in the program, a
programmer needs to import the module.
MORE ON MODULES
 Modules can contain executable statements along with
function definitions
 Each module has its own private symbol table used as the
global symbol table by all functions in the module
 Modules can import other modules
 Each module is imported once per interpreter session
 reload(name)
 Can
import names from a module into the importing
module’s symbol table
 from mod import m1, m2 (or *)
 m1()
EXECUTING MODULES
 python name.py <arguments>
 Runs code as if it was imported
 Setting _name_ == “_main_” the file can be used as a script and
an importable module
THE MODULE SEARCH PATH
 The interpreter searches for a file named name.py
 Current directory given by variable sys.path
 List of directories specified by PYTHONPATH
 Default path (in UNIX - .:/usr/local/lib/python)
 Script being run should not have the same name as a
standard module or an error will occur when the module is
imported
“COMPILED” PYTHON FILES
 If files mod.pyc and mod.py are in the same directory, there
is a byte-compiled version of the module mod
 The modification time of the version of mod.py used to
create mod.pyc is stored in mod.pyc
 Normally, the user does not need to do anything to create
the .pyc file
 A compiled .py file is written to the .pyc
 No error for failed attempt, .pyc is recognized as invalid
 Contents of the .pyc can be shared by different machines
SOME TIPS
 -O flag generates optimized code and stores it in .pyo files
 Only removes assert statements
 .pyc files are ignored and .py files are compiled to optimized bytecode
 Passing two –OO flags
 Can result in malfunctioning programs
 _doc_ strings are removed
 Same speed when read from .pyc, .pyo, or .py files, .pyo and .pyc files are
loaded faster
 Startup time of a script can be reduced by moving its code to a module and
importing the module
 Can have a .pyc or .pyo file without having a .py file for the same module
 Module compileall creates .pyc or .pyo files for all modules in a directory
HOW TO CREATE PYTHON MODULE ?
 Python modules are .py files that consist of Python code.
Any Python file can be referenced as a module.
 Some modules are available through the Python Standard
Library and are therefore installed with your Python
installation.
 Others can be installed with Python’s package manager
pip. Additionally, you can create your own Python
modules since modules are comprised of Python .py
files.
 Writing a module is just like writing any other Python file.
Modules can contain definitions of functions, classes, and
variables that can then be utilized in other Python programs.

To begin, we’ll create a function that prints Hello, World!:

hello.py
# Define a function
def world( ):
print("Hello, World!")

If we run the program on the command line with python hello.py


nothing will happen since we have not told the program to do
anything.
 Let’s create a second file in the same directory called
main_program.py so that we can import the module we just
created, and then call the function. This file needs to be in
the same directory so that Python knows where to find the
module since it’s not a built-in module.
main_program.py
# Import hello module
import hello

# Call function
hello.world()

# or from hello import world


 Create a python module to find the sum and product of digits (separately) and
imports in another program.
 Create a python function to find the a year is leap year of not a leap year
 What is local and global variable? Is global is keyword in python?
 Create a python module to find pow(x,n) and import in another program
 Write a function roll_D ( ), that takes 2 parameters- the no. of sides (with
default
value 6) of a dice, and the number of dice to roll-and generate random roll values
for each dice rolled. Print out each roll and then return one string “That’s all”.
Example roll_D (6, 3)
 4
 1
 6
MODULES EXAMPLE
fib.py - C:\

15
Programming 5/7/23
MODULES EXAMPLE

Within a module, the module’s


name is available as the value of
the global variable __name__.

16
Programming 5/7/23
HOW TO IMPORT MODULE?
 There are many ways to import a module in
your program, the one's which you should
know are:
 Import
 From
Import
 It is simplest and most common way to use modules in our code.

 Its syntax is:


 import modulename1 [,modulename2, ---------]
 Example
 >>> import math
 To use/ access/invoke a function, you will specify the module name and
name of the
 function- separated by dot (.). This format is also known as dot notation.
 Example
 >>> value= math.sqrt (25) # dot notation
From Statement
 It is used to get a specific function in the code instead of the
complete module file. If we know beforehand which function(s),
we will be needing, then we may use from. For modules having
large no. of functions, it is recommended to use from instead of
import.
Its syntax is:
>>> from modulename import functionname [, functionname…..]
>>>from modulename import * ( Import everything from the file)
Example
 >>> from math import sqrt
 value = sqrt (25)
IMPORTING SPECIFIC FUNCTIONS
 To import specific functions from a module

 This brings only the imported functions in the current symbol table
 No need of modulename. (absence of fib. in the example)

20
Programming 5/7/23
IMPORTING ALL FUNCTIONS
 To import all functions from a module, in the current
symbol table

 This imports all names except those beginning with an


underscore (_).
21
Programming 5/7/23
__MAIN__ IN MODULES
 When you run a module on the command line with
python fib.py <arguments>
the code in the module will be executed, just as if
you imported it, but with the __name__ set to
"__main__".
 By adding this code at the end of your module
if __name__ == "__main__":
... # Some code here
you can make the file usable as a script as well as an
importable module
22
Programming 5/7/23
ACCESSING MODULES FROM ANOTHER
DIRECTORY
MODULES MAY BE USEFUL FOR MORE THAN
ONE PROGRAMMING PROJECT, AND IN THAT
CASE IT MAKES LESS SENSE TO KEEP A
MODULE IN A PARTICULAR DIRECTORY
THAT’S TIED TO A SPECIFIC PROJECT.
APPENDING PATHS
 To append the path of a module to another programming file, you’ll start by importing
the sys module alongside any other modules you wish to use in your main program file.

 The sys module is part of the Python Standard Library and provides system-specific
parameters and functions that you can use in your program to set the path of the
module you wish to implement.

 For example, let’s say we moved the hello.py file and it is now on the path
/usr/sammy/ while the main_program.py file is in another directory.

 In our main_program.py file, we can still import the hello module by importing the sys
module and then appending /usr/sammy/ to the path that Python checks for files.
main_program.py
 import sys
 sys.path.append('/user/sammy/')
 import hello

...
 As long as you correctly set the path for the hello.py
file, you’ll be able to run the main_program.py file
without any errors and receive the same output as above
when hello.py was in the same directory.
Built in Function
 Built in functions are the function(s) that
are built into Python and can be accessed
by a programmer.
 These are always available and for using
them, we don’t have to import any
module (file).
SCOPE OF VARIABLES
The part of the program where a variable can be used is
known as Scope of variable

Two types of scopes :

●Global Scope

●Local Scope
GLOBAL SCOPE
● With global scope, variable can be used
anywhere in the program
eg:
x=50
def test ( ):
print(“inside test x is “, x)
print(“value of x is “, x)
Output:
inside test x is 50
value of x is 50
LOCAL SCOPE
● With local scope, variable can be used only within the
function / block that it is created .
Eg:
X=50
def test ( ):
y = 20
print(‘value of x is ’, X, ‘ y is ’ , y)
print(‘value of x is ’, X, ‘ y is ‘ , y)
On executing the code we will get
Value of x is 50 y is 20

The next print statement will produce an error, because the variable y is
not accessible outside the def()
MORE ON SCOPE OF
VARIABLES
To access global variable inside the function prefix
keyword global with the variable
Eg:

x=50
def test ( ):
global x =5
y =2
print(‘value of x & y inside the function are ‘ , x , y)
Print(‘value of x outside function is ‘ ‘, )

This code will produce following output:


Value of x & y inside the function are 5 2
Value of x outside the function is 5
QUESTION BASED ON FUNCTIONS
 What is the difference between methods, functions & user
defined functions.
 Open help for math module

i. How many functions are there in the module?


ii. Describe how square root of a value may be calculated
without using a math module
iii. What are the two data constants available in math module.
 Create a python module to find the sum and product of digits (separately) and
imports in another program.
 Create a python function to find the a year is leap year of not a leap year
 What is local and global variable? Is global is keyword in python?
 Create a python module to find pow(x,n) and import in another program
 Write a function roll_D ( ), that takes 2 parameters- the no. of sides (with
default
value 6) of a dice, and the number of dice to roll-and generate random roll values
for each dice rolled. Print out each roll and then return one string “That’s all”.
Example roll_D (6, 3)
 4
 1
 6

You might also like