By: Archana Shukla and Rajesh Shukla
PYTHON PACKAGES
Here we will learn:
What are the packages?
Importing module from a package
What are the packages?
We don’t usually store all of our files in our computer at the same location. We use a well-organized hierarchy of directories for easier access.
Similar files are kept in the same directory, for example, we may keep all the python programs in a directory “python_prog” and we may keep all the songs in the “music” directory. Analogous to this, Python has packages for directories and modules for files.
As our application program grows larger in size with a lot of modules, we place similar modules in one package and different modules in different packages. This makes a project (program) easy to manage and conceptually clear.
Similar, as a directory can contain sub-directories and files, a Python package can have sub-packages and modules.
directory must contain a file named __init__.py in order for Python to consider it as a package. This file can be left empty but we generally place the initialization code for that package in this file.
Example: 1 Using Python packages
Process:
* We create a folder named “hello”.
* Within the folder “hello” we create a modules “example3.py” and “example4.py”
* the modules “example3.py” and example4.py” contain number of function to perform various tasks.
filename: example3.py
def abc(): print("in abc function") def xyz(): print("in xyz function") def fact(): n=int(input("Enter any no ")) i=1 f=1 while(i<=n): f=f*i i=i+1 print("fact = ",f) def table(n): i=1 while(i<=10): t=n*i print(n," * ",i," = ",t) i=i+1
Another file
filename: example4.py
def max(a,b,c): m=0 if(a>b and a>c): m=a else: if(b>c): m=b else: m=c print("max no = ",m) def min(a,b,c): m=0 if(a<b and a<c): m=a else: if(b<c): m=b else: m=c print("min no = ",m)
Now we will create a file named “menu.py” to access all the function within the modules “example3.py” and “example4.py”
filename:menu.py
import hello.example3 import hello.example4 hello.example3.abc() hello.example3.xyz() hello.example3.fact() hello.example3.table(7) a=int(input("Enter any no ")) hello.example3.table(a) #without input hello.example4.max(10,20,30) hello.example4.min(10,20,30) #with input a=int(input("Enter 1st no ")) b=int(input("Enter 2nd no ")) c=int(input("Enter 3rd no ")) hello.example4.max(a,b,c) a=int(input("Enter 1st no ")) b=int(input("Enter 2nd no ")) c=int(input("Enter 3rd no ")) hello.example4.min(a,b,c)