Unit 4
Unit 4
os module.
random module.
math module.
time module
Calendar Module, etc.
import statement
from statement
from * statement
Manish Jain
Assistant Professor
Allenhouse Business School Kanpur
using import statement one can view all the functions and other attributes of a particular module
import math
dir(math)
importing module can be done using from statement specific attributes can be included in other programs.
syntax :
from <filename> import function name
example:
from* statement can be used to import all names from the module in to the current calling name
space.
syntax :
from <filename> import *
eg.
Manish Jain
Assistant Professor
Allenhouse Business School Kanpur
os module: This module has functions to perform many tasks of operating system.
mkdir():
>>> import os
>>> os.mkdir("d:\\tempdir")
A new directory corresponding to path will be created. If we open D drive in Windows explorer we should
notice tempdir folder created.
chdir():
>>> import os
>>> os.chdir("d:\\temp")
rmdir():
The rmdir() function in os module removes a specified directory. However, it should not be the current
working directory and it should be empty.
>>> os.rmdir("d:\\tempdir")
listdir():
The os module has listdir() function which returns list of all files in specified directory.
>>> os.listdir("c:\\Users")
['acer', 'All Users', 'Default', 'Default User', 'desktop.ini', 'Public']
random module: Python’s standard library contains random module which defines various functions for
handling randomization. Functions in this module depend on pseudo-random number generator function
random() which generates a random float number between 0.0 and 1.0.
random.random(): Returns a random float number between 0.0 to 1.0. The function doesn’t need any
arguments
Manish Jain
Assistant Professor
Allenhouse Business School Kanpur
Other functions in random module are described here:
random.randint(): Returns a random integer between the specified integers
random.randrange(): Returns a random element from the range created by start, stop and step
arguments. The start , stop and step parameters behave similar to range() function.
>>> random.randrange(1,10)
2
>>> random.randrange(1,10,2)
3
>>> random.randrange(0,101,10)
40
random.choice(): Returns a randomly selected element from a sequence object such as string, list or tuple.
>>> numbers=[12,23,45,67,65,43]
>>> random.shuffle(numbers)
>>> numbers
[23, 12, 43, 65, 67, 45]
>>> random.shuffle(numbers)
>>> numbers
[23, 43, 65, 45, 12, 67]
Pie π which is defined as ratio of circumference to diameter of a circle and its value is 3.141592653589793,
is available in math module.
Manish Jain
Assistant Professor
Allenhouse Business School Kanpur
>>> import math
>>> math.pi
3.141592653589793
>>> math.log10(10)
1.0
math.pow(): This function receives two float arguments, raises first to second and returns the result.
pow(4,4) is equivalent to 4**4
>>> math.pow(4,4)
256.0
>>> math.sqrt(100)
10.0
The ceil() function approximates given number to smallest integer greater than or equal to given floating
point number. The floor() function returns a largest integer less than or equal to given number
>>> math.ceil(4.5867)
5
>>> math.floor(4.5687)
4
time ():
This function returns current system time in ticks. The ticks are number of seconds elapsed after epoch
time i.e. 12.00 am, January 1, 1970.
>>> time.time()
1544348359.1183174
localtime():
>>> tk=time.time()
>>> time.localtime(tk)
time.struct_time(tm_year=2018, tm_mon=12, tm_mday=9, tm_hour=15, tm_min=11, tm_sec=25, tm_wda
y=6, tm_yday=343, tm_isdst=0)
Manish Jain
Assistant Professor
Allenhouse Business School Kanpur
asctime():
>>> tk=time.time()
>>> tp=time.localtime(tk)
>>> time.asctime(tp)
'Sun Dec 9 15:11:25 2018'
ctime():
>>> time.ctime()
'Sun Dec 9 15:17:40 2018'
sleep():
This function halts current program execution for a specified duration in seconds.
>>> time.ctime()
'Sun Dec 9 15:19:14 2018'
>>> time.sleep(20)
Calendar Module: Python defines an inbuilt module calendar that handles operations related to the
calendar.
month():
import calendar
cal = calendar.month(2020,3)
#printing the calendar of December 2018
print(cal)
prcal() :
import calendar
#printing the calendar of the year 2019
s = calendar.prcal(2020)
print(s)
isleap():
import calendar
# checking whether given year is leap or not
print(calendar.isleap(2016))
print(calendar.isleap(2001))
Manish Jain
Assistant Professor
Allenhouse Business School Kanpur
class calendar.Calendar :
The calendar class creates a Calendar object. A Calendar object provides several methods that can be
used for preparing the calendar data for formatting. Calendar class allows the calculations for various
tasks based on date, month, and year. Calendar class provides the many methods.
import calendar
# providing firstweekday = 0
obj = calendar.Calendar(firstweekday = 0)
output:
0123456
class calendar.TextCalendar :
TextCalendar class can be used to generate plain text calendars. TextCalendar class in Python allows you
to edit the calendar and use it as per your requirement.
import calendar
text_cal = calendar.TextCalendar(firstweekday = 0)
year = 2018
month = 9
# default value of width is 0
# printing formatmonth
print(text_cal.formatmonth(year, month))
output:
September 2018
Mo Tu We Th Fr Sa Su
1 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
class calendar.HTMLCalendar :
HTMLCalendar class can be used to generate HTML calendars. HTMLCalendar class in Python allows you
to edit the calendar and use as per your requirement.
import calendar
text_cal = calendar.HTMLCalendar(firstweekday = 0)
year = 2018
month = 9
# default value of width is 0
# printing formatmonth
print(text_cal.formatmonth(year, month))
Manish Jain
Assistant Professor
Allenhouse Business School Kanpur
output:
<table border="0" cellpadding="0" cellspacing="0" class="month">
<tr><th colspan="7" class="month">September 2018</th></tr>
<tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th
class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr>
<tr><td class="noday"> </td><td class="noday"> </td><td class="noday"> </td><td
class="noday"> </td><td class="noday"> </td><td class="sat">1</td><td
class="sun">2</td></tr>
<tr><td class="mon">3</td><td class="tue">4</td><td class="wed">5</td><td class="thu">6</td><td
class="fri">7</td><td class="sat">8</td><td class="sun">9</td></tr>
<tr><td class="mon">10</td><td class="tue">11</td><td class="wed">12</td><td
class="thu">13</td><td class="fri">14</td><td class="sat">15</td><td class="sun">16</td></tr>
<tr><td class="mon">17</td><td class="tue">18</td><td class="wed">19</td><td
class="thu">20</td><td class="fri">21</td><td class="sat">22</td><td class="sun">23</td></tr>
<tr><td class="mon">24</td><td class="tue">25</td><td class="wed">26</td><td
class="thu">27</td><td class="fri">28</td><td class="sat">29</td><td class="sun">30</td></tr>
</table>
Packages:
The package is a simple directory having collections of related modules. This makes a project (program)
easy to manage and conceptually clear.
Similarly, as a directory can contain subdirectories and files, a Python package can have sub-packages
and modules.
A 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.
The package also contains sub-packages inside it.
Examples of Packages: Numpy, Pandas etc.
Library:
The library is having a collection of related functionality of codes that allows you to perform many tasks
without writing your code. It is a reusable chunk of code that we can use by importing it into our
program, we can just use it by importing that library and calling the method of that library with a period.
However, it is often assumed that while a package is a collection of modules, a library is a collection of
packages.
Manish Jain
Assistant Professor
Allenhouse Business School Kanpur
Creating user defined package/Module:
Following are the steps for creating user defined modules:
1) create file.py with following code
def time_fun1():
sec = int(input("Enter a number of seconds: "))
hours = sec//3600
sec = sec%3600
minutes=sec//60
sec=sec%60
print(hours, "Hours", minutes, "minutes",sec,"seconds")
def time_fun2():
days = int(input("Enter a number of days: "))
months = days//30
days = days%30
print(months, "Months", days, "Days")
2) create test_module.py with following code and run
from file import *
time_fun1()
time_fun2()
output:
Enter a number of seconds: 100
0 Hours 1 minutes 40 seconds
Enter a number of days: 80
2 Months 20 Days
Following are the steps for creating user defined packages and modules:
1) create directory or folder names bca2
2) save two files/modules in this folder named file.py and file1.py
file.py
def time_fun1():
sec = int(input("Enter a number of seconds: "))
hours = sec//3600
Manish Jain
Assistant Professor
Allenhouse Business School Kanpur
sec = sec%3600
minutes=sec//60
sec=sec%60
print(hours, "Hours", minutes, "minutes",sec,"seconds")
file1.py
def time_fun2():
days = int(input("Enter a number of days: "))
months = days//30
days = days%30
print(months, "Months", days, "Days")
3) create _init_.py named file with following code:
_init_.py
import time_fun1,time_fun2
4) now create test_bca2_package.py file anywhere with following code and run:
test_bca2_package.py
from bca2 import file,file1
file.time_fun1()
file1.time_fun2()
output:
Enter a number of seconds: 100
0 Hours 1 minutes 40 seconds
Enter a number of days: 80
2 Months 20 Days
Manish Jain
Assistant Professor
Allenhouse Business School Kanpur