Assignment No: 10
Title: Modules and Packages
Objective: To understand modules and packages in Python
The assignment covers:
Course Outcome-CO5
Bloom’s Cognitive Domain-Creating
Basic Theory:
A module allows you to logically organize your Python code. Grouping related code into a
module makes the code easier to understand and use. A module is a Python object with
arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions,
classes and variables. A module can also include runnable code.
The import has the following syntax –
import module1[, module2[,... moduleN]
The from...import * Statement
It is also possible to import all names from a module into the current namespace by using
the following import statement –
from modname import *
Packages in Python
A package is a hierarchical file directory structure that defines a single Python application
environment that consists of modules and subpackages and sub-subpackages, and so
on.
Problem Statement:
1. Write a program which returns the year and name of weekday
import datetime
x = [Link]()
print([Link])
print([Link]("%A"))
Output:
2019
Tuesday
2. Write a module for calculator. Perform all the basic mathematical operations using the
created module.
[Link]
def add(x,y):
return x+y
def sub(x,y):
return x-y
def mul(x,y):
return x*y
def div(x,y):
return x/y,x%y
import mod
x=int(input("Enter a Number:"))
y=int(input("Enter a Number:"))
print([Link](x,y))
print([Link](x,y))
print([Link](x,y))
print([Link](x,y))
Output:
Enter a Number:5
Enter a Number:2
10
(2, 1)
3. Print all the modules, variables and functions that are defined under module random.
>>>dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST',
'SystemRandom', 'TWOPI', 'WichmannHill', '_BuiltinMethodType', '_MethodType', '__all__',
'__builtins__', '__doc__', '__file__', '__name__', '__package__', '_acos', '_ceil', '_cos', '_e',
'_exp', '_hashlib', '_hexlify', '_inst', '_log', '_pi', '_random', '_sin', '_sqrt', '_test',
'_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'division', 'expovariate',
'gammavariate', 'gauss', 'getrandbits', 'getstate', 'jumpahead', 'lognormvariate',
'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate',
'shu le', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
4. Import datetime module and print current date and time.
import datetime
x = [Link]()
print(x)
Output:
2019-08-20 17:03:35.329094
5. Import Calendar module and print the calendar of any year.
import calendar
print ("The calender of year 2012 is : ")
print ([Link](2012,2,1,6))
Output:
2012
January February March
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 1 2 3 4 5 1 2 3 4
2 3 4 5 6 7 8 6 7 8 9 10 11 12 5 6 7 8 9 10 11
9 10 11 12 13 14 15 13 14 15 16 17 18 19 12 13 14 15 16 17 18
16 17 18 19 20 21 22 20 21 22 23 24 25 26 19 20 21 22 23 24 25
23 24 25 26 27 28 29 27 28 29 26 27 28 29 30 31
30 31
April May June
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 12 3 4 5 6 1 2 3
2 3 4 5 6 7 8 7 8 9 10 11 12 13 4 5 6 7 8 9 10
9 10 11 12 13 14 15 14 15 16 17 18 19 20 11 12 13 14 15 16 17
16 17 18 19 20 21 22 21 22 23 24 25 26 27 18 19 20 21 22 23 24
23 24 25 26 27 28 29 28 29 30 31 25 26 27 28 29 30
30
July August September
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 1 2 3 4 5 1 2
2 3 4 5 6 7 8 6 7 8 9 10 11 12 3 4 5 6 78 9
9 10 11 12 13 14 15 13 14 15 16 17 18 19 10 11 12 13 14 15 16
16 17 18 19 20 21 22 20 21 22 23 24 25 26 17 18 19 20 21 22 23
23 24 25 26 27 28 29 27 28 29 30 31 24 25 26 27 28 29 30
30 31
October November December
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 7 1 2 3 4 1 2
8 9 10 11 12 13 14 5 6 7 8 9 10 11 3 4 5 67 8 9
15 16 17 18 19 20 21 12 13 14 15 16 17 18 10 11 12 13 14 15 16
22 23 24 25 26 27 28 19 20 21 22 23 24 25 17 18 19 20 21 22 23
29 30 31 26 27 28 29 30 24 25 26 27 28 29 30
31
6. Check whether a given year is leap year or not. Provide a range of years and display how
many leap years are there.
import calendar
y=int(input(“Enter a Year:”))
st= int(input(“Enter Start Year:”))
end= int(input(“Enter End Year:”))
if ([Link](y)):
print ("The year is leap")
else : print ("The year is not leap")
print ("The leap days between : %d and %d is"%(st,end),end="")
print ([Link](st,end))
Output:
Enter a Year: 2008
Enter Start Year: 1950
Enter End Year: 2000
The year is leap
The leap days between 1950 and 2000 are : 12
7. Print a month by importing calendar module.
import calendar
# using month() to display month of specific year
print ("The month 5th of 2016 is :")
print ([Link](2016,5,2,1))
Output:
The month 5th of 2016 is :
May 2016
Mo Tu We Th Fr Sa Su
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
8. Write a program to print a given datetime.
import datetime
x = [Link](2020, 5, 17)
print(x)
Output:
2020-05-17 00:00:00
9. Display the name of the month.
import datetime
x = [Link](2018, 6, 1)
print([Link]("%B"))
Output:
August
10. Print the month names of calendar.
import calendar
for name in calendar.month_name:
print(name)
Output:
January
February
March
April
May
June
July
August
September
October
November
December
11. Print the name of days in a week.
import calendar
for day in calendar.day_name:
print(day)
Output:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
12. Write a program which will print the month name and first Monday in a given year.
import calendar
yy=int(input(“Enter a Year: ”))
for month in range (1,13):
#it retrieves a list of weeks that represent the month
mycal=[Link](yy,month)
week1=mycal[0]
week2=mycal[1]
if week1[[Link]]!=0:
auditday=week1[[Link]]
else:
auditday=week2[[Link]]
print(“%10s %2d”%(calendar.month_name[month],auditday))
Output:
Enter a Year: 2025
January 6
February 3
March 3
April 7
May 5
June 2
July 7
August 4
September 1
October 6
November 3
December 1
13. Print the current date and time in the following format.
year: 2018
month: 12
day: 24
time: 04:59:31
date and time: 12/24/2018, 04:59:31
from datetime import datetime
now = [Link]() # current date and time
year = [Link]("%Y")
print("year:", year)
month = [Link]("%m")
print("month:", month)
day = [Link]("%d")
print("day:", day)
time = [Link]("%H:%M:%S")
print("time:", time)
date_time = [Link]("%m/%d/%Y, %H:%M:%S")
print("date and time:",date_time)
Output:
year: 2018
month: 12
day: 24
time: 04:59:31
date and time: 12/24/2018, 04:59:31
14. Write a Python program importing random which outputs the frequency of occurrence
of each faces for rolling a dice 6000 times.
import random
frequency1 = 0
frequency2 = 0
frequency3 = 0
frequency4 = 0
frequency5 = 0
frequency6 = 0
for roll in range( 1, 6001 ): # 6000 die rolls
face = [Link]( 1, 7 )
if face == 1: # frequency counted
frequency1 += 1
elif face == 2:
frequency2 += 1
elif face == 3:
frequency3 += 1
elif face == 4:
frequency4 += 1
elif face == 5:
frequency5 += 1
elif face == 6:
frequency6 += 1
else: # simple error handling
print "should never get here!"
print "Face %13s" % "Frequency"
print " 1 %13d" % frequency1
print " 2 %13d" % frequency2
print " 3 %13d" % frequency3
print " 4 %13d" % frequency4
print " 5 %13d" % frequency5
print " 6 %13d" % frequency6
Output
Face Frequency
1 946
2 1003
3 1035
4 1012
5 987
6 1017
15. Create a module which contains the functions as stated below.
a) F(x,y)=F(x-y,y)+1, if y ≤ x
b) F(n,r)=F(n-1,r)+F(n-1,r-1)
c) F(n)=F(n/2)+1 if n>1
d) F(M,N)=1 if M=0, or M ≥N ≥1, and F(M,N)=F(M-1,N)+F(M-1,N-1), otherwise.
e) B(m,x)=m!/(x!(m-x)!) where m>x,
B(0,0)=B(m,0)=1 and B(m,x)=B(m,x-1)*[(m-x+1)/x]
module_fun.py
def f1(x,y):
if y<=x:
return f1(x-y,y)+1
return 1
def f2(n,r):
if n>0 and r>0:
return (f2(n-1,r)+f2(n-1,r-1))
else:
return n+r
def f3(n):
if n>1:
return f3(n/2)+1
return 0
def f4(m,n):
if m==0 or (m>=n and n>=1):
return 1
else:
return f4(m-1,n)+f4(m-1,n-1)
def fact(n):
p=1
for i in range(1,n+1):
p*=i
return p
def f5(m,x):
if x==0:
return 1
if m>x:
return (fact(m)/(fact(x)*fact(m-x)))
else:
return (f5(m,x-1)*((m-x+1)/x))
[Link]
import module_fun as mf
while(1):
print("Press i to access function number i(eg:-1 for fun1)\nPress 6 to exit")
c=int(input())
if c==1:
print("Enter x and y:")
x,y=input().split()
x=int(x)
y=int(y)
print("Result=",mf.f1(x,y))
elif c==2:
print("Enter n and r:")
n,r=input().split()
n=int(n)
r=int(r)
print("Result=",mf.f2(n,r))
elif c==3:
n=int(input("Enter n:"))
print("Result=",mf.f3(n))
elif c==4:
print("Enter m and n")
m,n=input().split()
m=int(m)
n=int(n)
print("Result=",mf.f4(m,n))
elif c==5:
print("Enter m and x")
m,x=input().split()
m=int(m)
x=int(n)
print("Result=",mf.f5(m,x))
elif c==6:
print("Thanks")
break
else:
print("Wrong input")
Output
Press i to access function number i(eg:-1 for fun1)
Press 6 to exit
Enter x and y:
('Result=', 1)
Press i to access function number i(eg:-1 for fun1)
Press 6 to exit
Enter n and r:
('Result=', 78)
Press i to access function number i(eg:-1 for fun1)
Press 6 to exit
Enter n:7
('Result=', 2)
Press i to access function number i(eg:-1 for fun1)
Press 6 to exit
Enter m and n
('Result=', 16)
Press i to access function number i(eg:-1 for fun1)
Press 6 to exit
Enter m and x
('Result=', 0)
Press i to access function number i(eg:-1 for fun1)
Press 6 to exit
Thanks
16. Create a module which contains the functions printing several patterns. Each function
will take input the number of rows and/or columns as required.
* ** 456
** *** 7 8 9 10
*** **** 11 12 13 14
15
**** *****
*****
* 12
** 123
*** 1234
**** 12345
*****
* 23
[Link]
def pypart(n):
# outer loop to handle number of rows
# n in this case
for i in range(0, n):
# inner loop to handle number of columns
# values changing acc. to outer loop
for j in range(0, i+1):
# printing stars
print("* ",end="")
# ending line after each row
print("\r")
def pypart2(n):
# number of spaces
k = 2*n - 2
# outer loop to handle number of rows
for i in range(0, n):
# inner loop to handle number spaces
# values changing acc. to requirement
for j in range(0, k):
print(end=" ")
# decrementing k after each loop
k=k-2
# inner loop to handle number of columns
# values changing acc. to outer loop
for j in range(0, i+1):
# printing stars
print("* ", end="")
# ending line after each row
print("\r")
def triangle(n):
# number of spaces
k = 2*n - 2
# outer loop to handle number of rows
for i in range(0, n):
# inner loop to handle number spaces
# values changing acc. to requirement
for j in range(0, k):
print(end=" ")
# decrementing k after each loop
k=k-1
# inner loop to handle number of columns
# values changing acc. to outer loop
for j in range(0, i+1):
# printing stars
print("* ", end="")
# ending line after each row
print("\r")
def numpat(n):
# initialising starting number
num = 1
# outer loop to handle number of rows
for i in range(0, n):
# re assigning num
num = 1
# inner loop to handle number of columns
# values changing acc. to outer loop
for j in range(0, i+1):
# printing number
print(num, end=" ")
# incrementing number at each column
num = num + 1
# ending line after each row
print("\r")
def contnum(n):
# initializing starting number
num = 1
# outer loop to handle number of rows
for i in range(0, n):
# not re assigning num
# num = 1
# inner loop to handle number of columns
# values changing acc. to outer loop
for j in range(0, i+1):
# printing number
print(num, end=" ")
# incrementing number at each column
num = num + 1
# ending line after each row
print("\r")
[Link]
[Link](5)
pattern.pypart2(5)
[Link](5)
[Link](5)
[Link](5)
Output:
**
***
****
*****
**
***
****
*****
**
***
****
*****
12
123
1234
12345
23
456
7 8 9 10
11 12 13 14 15
17. Create a package which contains five modules fish, birds, amphibians, mammals,
and reptiles. Each module contains two functions example and characteristics.
[Link]
def examples():
print("Here are some examples of amphibians:")
egs=['Frog',"Salamander","Toads","Newts","caecilians"]
for f in egs:
print(f)
def chars():
ch=["Cold blooded","Lays eggs","Moist scaleless skin"]
print("Characteristics of amphibians:")
for c in ch:
print(c)
[Link]
def examples():
print("Here are some examples of birds:")
egs=['Parrot',"Pigeon","Crow","Owl","Sparrow"]
for f in egs:
print(f)
def chars():
ch=["Have wings","Lays eggs","Warm blooded","Have beaks and no teeth"]
print("Characteristics of birds:")
for c in ch:
print(c)
fi[Link]
def examples():
print("Here are some examples of fish:")
egs=['Goldfish',"Tuna","Guppy","Piranha","Swordfish"]
for f in egs:
print(f)
def chars():
ch=["Lives Under Water","Breathes through gills","Swims using fins and Tail"]
print("Characteristics of fish:")
for c in ch:
print(c)
[Link]
def examples():
print("Here are some examples of mammals:")
egs=["Human","Cat","Tiger","Dog","Elephant"]
for f in egs:
print(f)
def chars():
ch=["Warm blooded","Gives birth to babies","Have hair and fur","Four chambered
heart"]
print("Characteristics of mammals:")
for c in ch:
print(c)
[Link]
def examples():
print("Here are some examples of reptiles:")
egs=['Turtle',"Lizard","Crocodiles","Chameleon","Snakes"]
for f in egs:
print(f)
def chars():
ch=["Have scales","Vertebrates","Breathe through lungs","Cold blooded"]
print("Characteristics of reptiles:")
for c in ch:
print(c)
[Link]
import fish,birds,amphibians,mammals,reptiles
def __init__(self):
print("Find your information about creatures:examples and characteristics")
[Link]
#Creatures package includes various modules
import Creatures
print("Find your information about creatures:examples and characteristics")
while(1):
print("Press\n1 for fish\n2 for birds\n3 for amphibians\n4 for mammals\n5 for
reptiles\n6 to exit:")
c=int(input())
if c==1:
Creatures. fi[Link]()
Creatures. fi[Link]()
elif c==2:
Creatures. [Link]()
Creatures. [Link]()
elif c==3:
Creatures. [Link]()
Creatures. [Link]()
elif c==4:
Creatures. [Link]()
Creatures. [Link]()
elif c==5:
Creatures. [Link]()
Creatures. [Link]()
elif c==6:
print("Thank You!!!")
break
else:
print("Wrong input")
#for each module class concept has been introduced purposefully.
#to be noted same process can be implemented without introducing separate class
Output
Find your information about creatures:examples and characteristics
Press
1 for fish
2 for birds
3 for amphibians
4 for mammals
5 for reptiles
6 to exit:
Here are some examples of fish:
Goldfish
Tuna
Guppy
Piranha
Swordfish
Characteristics of fish:
Lives Under Water
Breathes through gills
Swims using fins and Tail
Press
1 for fish
2 for birds
3 for amphibians
4 for mammals
5 for reptiles
6 to exit:
Here are some examples of birds:
Parrot
Pigeon
Crow
Owl
Sparrow
Characteristics of birds:
Have wings
Lays eggs
Warm blooded
Have beaks and no teeth
Press
1 for fish
2 for birds
3 for amphibians
4 for mammals
5 for reptiles
6 to exit:
Here are some examples of amphibians:
Frog
Salamander
Toads
Newts
caecilians
Characteristics of amphibians:
Cold blooded
Lays eggs
Moist scaleless skin
Press
1 for fish
2 for birds
3 for amphibians
4 for mammals
5 for reptiles
6 to exit:
Here are some examples of mammals:
Human
Cat
Tiger
Dog
Elephant
Characteristics of mammals:
Warm blooded
Gives birth to babies
Have hair and fur
Four chambered heart
Press
1 for fish
2 for birds
3 for amphibians
4 for mammals
5 for reptiles
6 to exit:
Here are some examples of reptiles:
Turtle
Lizard
Crocodiles
Chameleon
Snakes
Characteristics of reptiles:
Have scales
Vertebrates
Breathe through lungs
Cold blooded
Press
1 for fish
2 for birds
3 for amphibians
4 for mammals
5 for reptiles
6 to exit:
Thank You!!!
Discussions:
This assignment covers the basics of files, modules, and packages in Python which
covers PO1, PO2, PO3, PO12, and PSO1, PSO2, PSO3.
Questionnaires:
1. What is pip?
PIP is a package manager for Python packages, or modules if you like. If you have Python
version 3.4 or later, PIP is included by default.
2. How do you check whether it is installed or not?
Typing pip in the command prompt.
3. How do you check which packages of Python are installed?
pip list