1. Python Module (1)
1. Python Module (1)
Module
DCSN03C – Computer Programming 2
What is Module?
Python Module
● A python modules can be defined as a python program file.
● It contains -- functions, class or variables.
● Modules in Python provide us the flexibility to organize the code in a
logical way.
● Example:
def myModule(name):
print("Hi!", name)
1. Import Statement
2. From-Import Statement
Import Statement
● Import statement is used to import all
the functionality of one module into
another. (think of it like of taking a book
off the shelf).
● We can import multiple modules with a
single import statement, but a module is
loaded once regardless of the number of
times.
Syntax:
import module1, module2, ..., module n
Namespace
Inside a certain namespace, each name must
remain unique. This may mean that some names
may disappear when any other entity of an
already known name enters the namespace.
#test.py
import file
name = input("Enter your name:")
file.displayMsg(name)
From-Import Statement
● •It provides the flexibility to import only the specific
attributes of a module.
Syntax:
from <module-name> import <name1>, <name2> ...
From-Import Statement Example
#Calculation.py #Myprogram.py
def sum(a,b): from Calculation import sum
return a + b a = int(input("Enter the first number"))
def mul(a,b): b = int(input("Enter the second
return a * b number"))
def div(a,b): print("Sum = ", sum(a,b))
return a/b
Importing a module: *
Syntax
the name of an entity (or the list of entities' names) is replaced with a
single asterisk (*).
Such an instruction imports all entities from the indicated module.
The as keyword
import module variant and you don't like a particular module's name
(e.g., it's the same as one of your already defined entities, so
qualification becomes troublesome) you can give it any name you
like - this is called aliasing.
Aliasing causes the module to be identified under a different name than the
original. This may shorten the qualified names, too.
Syntax:
import module as alias
Aliasing Example
import math as m
print(m.sin(m.pi/2))
Note: after successful execution of an aliased import, the original module name
becomes inaccessible and must not be used.
In turn, when you use the from module import name variant and you need to change
the entity's name, you make an alias for the entity. This will cause the name to be
replaced by the alias you choose.