Packages are namespaces which contain multiple packages and modules. They are simply directories.
Packages
•
Packages are namespaces which contain multiple
packages and modules. They are simply directories.
•
Along with packages and modules the package contains a file named __init_ _.py.
In fact to be a package, there must be a file called __init_ _.py in the
folder.
•
Packages can be nested to any depth, provided that the corresponding
directories contain their own _init__.py file.
•
The arrangement of packages is as shown
in Fig. 5.5.1.
Fig.
5.5.1
For
example :
We
can access the package and various subpackages and modules in it as follows:
import
My_Package #loads My_Package/ _init__.py
import
My_Package.module1 #loads My_Package/module1.py
from
My_Package import module2
import
My_Package.SubPackage1
When
we import Main package then there is no need to import subpackage. For example
import
My_Package My_Package.
SubPackage1.my_function1(
)
•
Thus we need not have to import SubPackage1.
•
The primary use of __init__.py is to initialize Python packages. Simply putting
the subdirectories and modules inside a directory does not make a directory a
package, what it needs is a __init_.py inside it. Then only Python treats that
directory as package.
How
to Create a Package ?
•
To understand how to create a package, let us take an example. We will perform
arithmetic operations addition, multiplication, division and subtraction
operations by creating a package. Just follow the given steps to create a
package.
Step
1:
Create a folder named MyMaths in your working drive. I have created it
on D:drive.
Step
2:
Inside MyMaths directory create _init_.py file. Just create an empty
file.
Step
3: Create
a folder named Add inside MyMaths. Inside Add folder
create file named addition.py. The addition.py will be as follows
addition.py
def
add_fun(a,b):
return
a + b
Step
4:
Similarly the folder Sub insider MyMaths is created. Inside which create
a file subtraction.py. The code for this file is
subtraction.py
def
sub_fun(a,b):
return(a-b)
Step
5:
Similarly the folder Mul insider MyMaths is created. Inside which create
a file multiplication.py. The code for this file is
multiplication.py
def
mul_fun(a,b):
return(a*b)
Step
6: Similarly
the folder Div insider MyMaths is created. Inside which create a file division.py.
The code for this file is
division.py
def
div_fun(a,b):
return
(a/b)
Step
7:
The overall directory Structure will be as given below. Note that _pycache_is
automatically generated directory.
Step
8:
Now on the D: drive create a driver program which will invoke all the above
functionalities present in the MyMaths package. I have named this driver
program as testing_arithmetic.py. It is as follows
print("The
addition of 10 and 20 is: ",MyMaths.Add.addition.add_fun(10,20))
print("The
multiplication of 10 and 20 is:
",MyMaths.Mul.multiplication.mul_fun(10,20))
print("The
division of 10 and 5 is: ",MyMaths.Div.division.div_fun(10,5))
print("The
subtraction of 20 and 10 is: ",MyMaths.Sub.subtraction.sub_fun(20,10))
Step
9:
Now just run this testing program and you will get following output
Output
The
addition of 10 and 20 is:30
The multiplication of 10 and 20 is:200
This
program counts the number of words present in the given file. If the specified
file is not present, then exception is raised.
Step
1:
Python
Program
try:
inFile
= open("D:\\test.txt",'rt')
except:
print("Error:
File not found")
else:
data
inFile.read()
words
= data.split()
print(words)
print('-'*80)
print("Total
number of words are ",len(words))
print('-'*80)
Step
2:
The
input file used for reading and for word counting is as follows
Step
3:
The
output for the Python program created in Step 1 is as follows –
In
this program, the contents of one file are copied line by line to another file.
For that purpose I have created a file named one.txt in which some contents are
stored. These contents are copied to another file named two.txt. The
python program for this is as given below -
Step
1:
The python program is as follows –
print("\t
Program for Copying the File")
with
open("d:\\one.txt") as inFile:
with
open("d:\\two.txt","w") as outFile:
for
line in inFile:
outFile.write(line)
inFile.close()
outFile.close()
print("The
contents of original File are... \n")
with
open("D:\\one.txt") as inFile:
print(inFile.read()).
inFile.close()
print("\nThe
contents of copied File are... \n")
with
open("D:\\two.txt") as in File:
print(inFile.read())
inFile.close()
Step
2:
The input file one.txt is as follows –
one.txt
Step
3:
The output of the python program created in step 1 is as follows -
3. Voter's Age Validation
Python
Program
try:
age
= int(input("Enter your age: "))
if
age > 18:
print("Eligible
to vote!!!")
else:
print("Not
eligible to vote!!!")
except
ValueError as err:
print(err)
finally:
#
code to be executed whether exception occurs or not
#typically
for closing files and other resources
print("Good
Bye!!!")
Output(Run 1)
Enter
your age: 20
Eligible
to vote!!!
Good
Bye!!!
>>>
Output(Run
2)
Enter
your age: twenty
invalid
literal for int() with base 10: 'twenty'
Good
Bye!!!
>>>
Python
Program
while
True :
try:
num
= int(input("Enter a number between 1 and 100: "))
if
num in range(1,100):
print("Valid
number!!!")
break
else
:
print("Invalid
number. Try again.")
except
:
print("That
is not a number. Try again.")
Output
Enter
a number between 1 and 100: -1
Invalid
number. Try again.
Enter
a number between 1 and 100-10000
Invalid
number. Try again.
Enter
a number between 1 and 100- five
This
not a number . Try again
Enter
a number between 1 and 100: 99
Valid
number
>>>
Review Question
1. Design a Python code to count the number of words in a Python
file.
AU : May-19,Dec.-19, Marks 8
Problem Solving and Python Programming: UNIT V: Files, Modules, Packages : Tag: Engineering Python : Example Program | Python Programming - Packages
Problem Solving and Python Programming
GE3151 1st Semester | 2021 Regulation | 1st Semester Common to all Dept 2021 Regulation