Python
Python
Presented By
Harsh Kumar Singh
Rohit
Kartik
ansh
Python Modules
●
When you “import” a function, for instance,
you are essentially using a module
●
A module is essentially a Python file with a .py
extension
Using Modules
●
You can import a module using
import <module-name>
and access the contents using
<module-name>.<entity-name>
● You can also access entities
directly
from <module-name> import <entity-name>
OR
import <module-name>
<alias>=<module-name>.<entity-name>
Creating Modules
●
Example: Create the following and save it as
example.py
def add(x,y):
return x+y
●
Now, in another Python file, call the add()
function using the following:
import example
print(example.add(1,2))
Creating Modules (Contd)
●
Modules have the name variable set to the module
name
● When a Python file is called as a script, the
name is set to “ main ”. This lets you create
modules that can also be executed as scripts
using the following:
def add(x,y):
return x+y
if name
== “
main
”:
print(add(1,2)
Packages
●
PYTHONPATH is an environment variable set with
the locations where the Python interpreter searches
for modules
● Typically, the module search path is defined as:
PYTHONPATH=./usr/local/lib/pythonX.X
which is the current directory and
/usr/local/lib/pythonX.X