Module 5&6
Module 5&6
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters, list comprehension; Tuples: tuple assignment, tuple as return value, tuple
comprehension; Dictionaries: operations and methods, comprehension;
List:
>>> x=list()
>>> x
[]
>>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]
71
List operations:
These operations include indexing, slicing, adding, multiplying, and checking for
membership
Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string.
Because lists are sequences, indexing and slicing work the same way for lists as they do for
strings.
72
L[-2] department Negative: count from the right
List slices:
>>> list1=range(1,6)
>>> list1
range(1, 6)
>>> print(list1)
range(1, 6)
List methods:
The list data type has some more methods. Here are all of the methods of list objects:
Del()
Append()
Extend()
Insert()
Pop()
Remove()
Reverse()
Sort()
Delete: Delete a list or an item from a list
>>> x=[5,3,8,6]
>>> del(x[1]) #deletes the index position 1 in a list
>>> x
[5, 8, 6]
>>> del(x)
>>> x # complete list gets deleted
91
Append: Append an item to a list
>>> x=[1,5,8,4]
>>> x.append(10)
>>> x
[1, 5, 8, 4, 10]
Extend: Append a sequence to a list.
>>> x=[1,2,3,4]
>>> y=[3,6,9,1]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 3, 6, 9, 1]
Insert: To add an item at the specified index, use the insert () method:
>>> x=[1,2,4,6,7]
>>> x.insert(2,10) #insert(index no, item to be inserted)
>>> x
[1, 2, 10, 4, 6, 7]
>>> x.insert(4,['a',11])
>>> x
Pop: The pop() method removes the specified index, (or the last item if index is not
specified) or simply pops the last item of list and returns the item.
>>> x.pop()
>>> x
92
[1, 2, 10, 4, 6]
>>> x.pop(2)
10
>>> x
[1, 2, 4, 6]
Remove: The remove() method removes the specified item from a given list.
>>> x=[1,33,2,10,4,6]
>>> x.remove(33)
>>> x
[1, 2, 10, 4, 6]
>>> x.remove(4)
>>> x
[1, 2, 10, 6]
>>> x.sort()
>>> x
[1, 2, 3, 4, 5, 6, 7]
93
>>> x=[10,1,5,3,8,7]
>>> x.sort()
>>> x
[1, 3, 5, 7, 8, 10]
List loop:
Loops are control structures used to repeat a given section of code a certain number of times
or until a particular condition is met.
#list of items
list = ['V','T','U']
i=1
C:/Users/VTU/Programs/Python/Python38-32/pyyy/lis.py department 1 is
M
department 2 is
R
department 3 is
C
department 4 is
E
department5 is
T
Method #2: For loop and range()
In case we want to use the traditional for loop which iterates from number x to number
y. # Python3 code to iterate over a list
list = [1, 3, 5, 7, 9]
94
# getting length of list
length = len(list)
# Iterating the index
# same as 'for i in range(len(list))'
for i in range(length):
print(list[i])
Output:
C:/Users/VTU/ Programs/Python/Python38-32/pyyy/listlooop.py 1
3
5
7
9
Method #3: using while loop
Mutability:
A mutable object can be changed after it is created, and an immutable object can't.
>>> x=[1,2,4,6,7]
[1, 2, 10, 4, 6, 7]
>>> x.insert(4,['a',11])
>>> x
Pop: The pop() method removes the specified index, (or the last item if index is not
specified) or simply pops the last item of list and returns the item.
>>> x.pop()
>>> x
[1, 2, 10, 4, 6]
10
>>> x
[1, 2, 4, 6]
Remove: The remove() method removes the specified item from a given list.
>>> x=[1,33,2,10,4,6]
>>> x.remove(33)
>>> x
[1, 2, 10, 4, 6]
>>> x.remove(4)
>>> x
[1, 2, 10, 6]
>>> x.sort()
>>> x
[1, 2, 3, 4, 5, 6, 7]
>>> x=[10,1,5,3,8,7]
>>> x.sort()
97
>>> x
[1, 3, 5, 7, 8, 10]
Aliasing:
1. An alias is a second name for a piece of data, often easier (and more useful) than
making a copy.
2.
3. But if data can change, aliases can result in lot of hard to find bugs.
4.
For ex:
a = [81, 82, 83]
b = [81, 82, 83]
print(a == b)
print(a is b)
b=a
print(a == b)
print(a is b)
b[0] = 5
print(a)
Output:
C:/Users/VTU /Programs/Python/Python38-32/pyyy/alia.py True
False
True
True
[5, 82, 83]
Because the same list has two different names, a and b, we say that it is aliased. Changes
made with one alias affect the other. In the example above, you can see that a and b refer to
the same list after executing the assignment statement b = a.
Cloning Lists:
If we want to modify a list and also keep a copy of the original, we need to be able to make a
copy of the list itself, not just the reference. This process is sometimes called cloning, to
avoid the ambiguity of the word copy.
The easiest way to clone a list is to use the slice operator. Taking any slice of a creates a new
list. In this case the slice happens to consist of the whole list.
Example:
98
a = [81, 82, 83]
print(a == b)
print(a is b)
b[0] = 5
print(a)
print(b)
Output:
C:/Users/VTU/Programs/Python/Python38-32/pyyy/clo.py
True
False
[81, 82, 83]
[5, 82, 83]
Now we are free to make changes to b without worrying about a
List parameters:
Passing a list as an argument actually passes a reference to the list, not a copy of the list.
Since lists are mutable, changes made to the elements referenced by the parameter change
the same list that the argument is referencing.
# for example, the function below takes a list as an argument and multiplies each element
in the list by 2:
def doubleStuff(List):
""" Overwrite each element in aList with double its value. """
List[position] = 2 * List[position]
things = [2, 5, 9]
print(things)
99
doubleStuff(things)
print(things)
Output:
C:/Users/VTU/AppData/Local/Programs/Python/Python38-32/lipar.py ==
[2, 5, 9]
List comprehension:
List:
List comprehensions provide a concise way to create lists. Common applications are to make
new lists where each element is the result of some operations applied to each member of
another sequence or iterable, or to create a subsequence of those elements that satisfy a
certain condition.
>>> list1=[]
list1.append(x**2)
>>> list1
(or)
>>> list1
>>> list1
>>> a=5
>>> table = [[a, b, a * b] for b in range(1, 11)]
>>> for i in table:
print(i)
[5, 1, 5]
[5, 2, 10]
[5, 3, 15]
[5, 4, 20]
[5, 5, 25]
[5, 6, 30]
[5, 7, 35]
[5, 8, 40]
[5, 9, 45]
[5, 10, 50]
91
1
Tuples:
A tuple is a collection which is ordered and unchangeable. In Python tuples are written
with round brackets.
Supports all operations for sequences.
Immutable, but member objects may be mutable
91
2
accidently being added, changed, or deleted.
Example:
>>> x=(1,2,3)
>>> print(x)
(1, 2, 3)
>>> x
(1, 2, 3)
>>> x=()
>>> x
()
>>> x=[4,5,66,9]
>>> y=tuple(x)
>>> y
(4, 5, 66, 9)
>>> x=1,2,3,4
>>> x
(1, 2, 3, 4)
91
3
Access tuple items: Access tuple items by referring to the index number, inside square
brackets
>>> x=('a','b','c','g')
>>> print(x[2])
c
Change tuple items: Once a tuple is created, you cannot change its values. Tuples
are unchangeable.
>>> x=(2,5,7,'4',8)
>>> x[1]=10
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
x[1]=10
TypeError: 'tuple' object does not support item assignment
>>> x
(2, 5, 7, '4', 8) # the value is still the same
Loop through a tuple: We can loop the values of tuple using for loop
>>> x=4,5,6,7,2,'aa'
>>> for i in x:
print(i)
4
5
6
7
2
aa
Count (): Returns the number of times a specified value occurs in a tuple
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> x.count(2)
4
Index (): Searches the tuple for a specified value and returns the position of where it
was found
91
4
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> x.index(2)
1
(Or)
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=x.index(2)
>>> print(y)
1
Length (): To know the number of items or values present in a tuple, we use len().
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=len(x)
>>> print(y)
12
Tuple Assignment
Python has tuple assignment feature which enables you to assign more than one variable at a
time. In here, we have assigned tuple 1 with the department information like department
name, year, etc. and another tuple 2 with the values in it like number (1, 2, 7).
For Example,
>>> print(tup1[0])
vtu
>>> print(tup2[1:4])
(2, 3, 4)
91
5
We call the value for [0] in tuple and for tuple 2 we call the value between 1 and 4
Run the above code- It gives name vtu for first tuple while for second tuple it gives
number (2, 3, 4)
A Tuple is a comma separated sequence of items. It is created with or without (). Tuples are
immutable.
Output:
C:/Users/VTU /Programs/Python/Python38-32/tupretval.py vtu department
20
def circleInfo(r):
""" Return (circumference, area) of a circle of radius r """
c = 2 * 3.14159 * r
a = 3.14159 * r * r
return (c, a)
print(circleInfo(10))
Output:
C:/Users/VTU/Programs/Python/Python38-32/functupretval.py (62.8318, 314.159)
91
6
def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return (y0, y1, y2)
Tuple comprehension:
Tuple Comprehensions are special: The result of a tuple comprehension is special. You
might expect it to produce a tuple, but what it does is produce a special "generator"
object that we can iterate over.
For example:
>>> x = (i for i in 'abc') #tuple comprehension
>>> x
<generator object <genexpr> at 0x033EEC30>
>>> print(x)
<generator object <genexpr> at 0x033EEC30>
You might expect this to print as ('a', 'b', 'c') but it prints as <generator object <genexpr>
at 0x02AAD710> The result of a tuple comprehension is not a tuple: it is actually a
generator. The only thing that you need to know now about a generator now is that you
can iterate over it, but ONLY ONCE.
So, given the code
a
b
c
Create a list of 2-tuples like (number, square):
>>> z=[(x, x**2) for x in range(6)]
>>> z
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
91
7
Set:
Similarly to list comprehensions, set comprehensions are also supported:
Dictionaries:
Example:
>>> dict1 = {"brand":"vtu","model":"department","year":2004}
>>> dict1
{'brand': 'vtu', 'model': 'department', 'year': 2004}
Methods that are available with dictionary are tabulated below. Some of them have already
been used in the above examples.
Method Description
91
8
copy() Return a shallow copy of the dictionary.
91
9
To access specific value of a dictionary, we must pass its key,
>>> dict1 = {"brand":"vtu","model":"department","year":2004}
>>> x=dict1["brand"]
>>> x
'vtu'
vtu
depart
ment
2004
92
0
Remove
Length
Delete
Add/change values: You can change the value of a specific item by referring to its key
name
>>>{1: 1, 2: 4, 3: 9, 4: 16}
{1: 1, 2: 4, 3: 9, 4: 16}
>>> y=len(x)
>>> y
4
Iterating over (key, value) pairs:
>>> x = {1:1, 2:4, 3:9, 4:16, 5:25}
>>> for key in x:
print(key, x[key])
11
24
39
100
4 16
5 25
>>> for k,v in x.items():
print(k,v)
11
24
39
4 16
5 25
List of Dictionaries:
1 John
2 Smith
3 Andersson
## Modify an entry, This will change the name of customer 2 from Smith to Charlie
>>> customers[2]["name"]="charlie"
>>> print(customers)
[{'uid': 1, 'name': 'John'}, {'uid': 2, 'name': 'Smith'}, {'uid': 3, 'name': 'charlie'}]
>>> print(customers)
[{'uid': 1, 'name': 'John', 'password': '123456'}, {'uid': 2, 'name': 'Smith', 'password':
'123456'}, {'uid': 3, 'name': 'charlie', 'password': '123456'}]
## Delete a field
103
>>> del customers[1]
>>> print(customers)
[{'uid': 1, 'name': 'John', 'password': '123456'}, {'uid': 3, 'name': 'charlie', 'password':
'123456'}]
>>> x
{'name': 'John', 'password': '123456'}
Comprehension:
Dictionary comprehensions can be used to create dictionaries from arbitrary key and
value expressions:
103
Module 6
FILES, EXCEPTIONS, MODULES, PACKAGES
Files and exception: text files, reading and writing files, command line arguments, errors
and exceptions, handling exceptions, modules (datetime, time, OS , calendar, math module),
Explore packages.
A file is some information or data which stays in the computer storage devices. Python gives
you easy ways to manipulate these files. Generally files divide in two categories,
text file and binary file. Text files are simple text where as the binary files contain binary
data which is only readable by computer.
Text files: In this type of file, Each line of text is terminated with a special character
\
Binary files: In this type of file, there is no terminator for a line and the data is stored
after converting it into machine understandable binary language.
An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program's instructions. In general, when a Python script encounters a
situation that it cannot cope with, it raises an exception. An exception is a Python object
that represents an error.
Text files:
Variable name=open
We declared the variable f to open a file named hello.txt. Open takes 2 arguments, the
file that we want to open and a string that represents the kinds of permission or
operation we want to do on the file
Here we used "w" letter in our argument, which indicates write and the plus sign that
103
means it will create a file if it does not exist in library
103
The available option beside "w" are "r" for read and "a" for append and plus sign
means if it is not there then create it
Mode Description
'x' Creates a new file. If file already exists, the operation fails.
'+' This will open a file for reading and writing (updating)
The following image shows how to create and open a text file in notepad from command
prompt
104
(or)
print(a.read())
105
a.close()
Output:
C:/Users/VTU /Programs/Python/Python38-32/filess/f1.py welcome to python
programming
(or)
Note: All the program files and text files need to saved together in a particular file then
only the program performs the operations in the given file mode
f.close() ---- This will close the instance of the file somefile.txt stored
f=open("1.txt","a")
f.write("hello world")
f.close()
Output:
106
(or)
Note: In the above program the 1.txt file is created automatically and adds hello world
into txt file
If we keep on executing the same program for more than one time then it append the data
that many times
#
existing file.
f=open("1.txt",'w')
f.close()
Output:
In the above program the hello txt file consist of data like
107
But when we try to write some data on to the same file it overwrites and saves with the
current data (check output)
# Write a python program to open and write the content to file and read it.
fo=open("abc.txt","w+")
fo.write("Python Programming")
print(fo.read())
fo.close()
Output:
(or)
Note: It creates the abc.txt file automatically and writes the data into it
108
Command line arguments:
The command line arguments must be given whenever we want to give the input before the
start of the script, while on the other hand, raw_input() is used to get the input while the
python program / script is running.
Python sys module stores the command line arguments into a list, we can access it
using sys.argv. This is very useful and simple way to read command line arguments as
String.
sys.argv is the list of commandline arguments passed to the Python program. argv represents
all the items that come along via the command line input, it's basically an array holding the
command line arguments of our program
>>> sys.modules.keys() -- this prints so many dict elements in the form of list.
# Python code to demonstrate the use of 'sys' module for command line arguments
import sys
Output:
C:/Users/VTU /Programs/Python/Python38-32/cmndlinarg.py
109
Note:
import sys
print(type(sys.argv))
print('The command line arguments are:')
for i in sys.argv:
print(i)
Output:
C:/Users/VTU /Programs/Python/Python38-32/symod.py ==
<class 'list'>
The command line arguments are: C:/Users/VTU/
/Programs/Python/Python38-32/symod.py
Output:
C:/Users/VTU/AppData/Local/Programs/Python/Python38-32/pyyy/s1.py =
System version is:
3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)]
Version Information is:
sys.version_info(major=3, minor=8, micro=0, releaselevel='final', serial=0)
Python getopt module is very similar in working as the C getopt() function for parsing
command-line parameters. Python getopt module is useful in parsing command line
arguments where we want user to enter some options too.
110
#
111
import argparse
parser = argparse.ArgumentParser()
print(parser.parse_args())
Python argparse module is the preferred way to parse command line arguments. It provides a
lot of option such as positional arguments, default value for arguments, help message,
specifying data type of argument etc
It parses the command line options and parameter list. The signature of this function is
mentioned below:
import getopt
import sys
argv = sys.argv[0:]
try:
opts, args = getopt.getopt(argv, 'hm:d', ['help', 'my_file='])
#print(opts)
print(args)
except getopt.GetoptError:
# Print a message or do something useful
print('Something went wrong!')
sys.exit(2)
112
Output:
C:/Users/VTU/AppData/Local/Programs/Python/Python38-32/gtopt.py ==
['C:/Users/VTU/AppData/Local/Programs/Python/Python38-32/gtopt.py']
Python Errors and Built-in Exceptions: Python (interpreter) raises exceptions when it
encounters errors. When writing a program, we, more often than not, will
encounter errors. Error caused by not following the proper structure (syntax) of the language
is called syntax error or parsing error
ZeroDivisionError:
ZeroDivisionError in Python indicates that the second argument used in a division (or
modulo) operation was zero.
OverflowError:
OverflowError in Python indicates that an arithmetic operation has exceeded the limits of
the current Python runtime. This is typically due to excessively large float values, as integer
values that are too big will opt to raise memory errors instead.
ImportError:
It is raised when you try to import a module which does not exist. This may happen if you
made a typing mistake in the module name or the module doesn't exist in its standard path.
In the example below, a module named "non_existing_module" is being imported but it
doesn't exist, hence an import error exception is raised.
IndexError:
An IndexError exception is raised when you refer a sequence which is out of range. In the
example below, the list abc contains only 3 entries, but the 4th index is being accessed,
which will result an IndexError exception.
TypeError:
When two unrelated type of objects are combined, TypeErrorexception is raised.In example
below, an int and a string is added, which will result in TypeError exception.
113
IndentationError:
Syntax errors:
These are the most basic type of error. They arise when the Python parser is unable to
understand a line of code. Syntax errors are almost always fatal, i.e. there is almost never a
way to successfully execute a piece of code containing syntax errors.
Run-time error:
A run-time error happens when Python understands what you are saying, but runs into
trouble when following your instructions.
Key Error :
Value Error:
In Python, a value is the information that is stored within a certain object. To encounter a
ValueError in Python means that is a problem with the content of the object you tried to
assign the value to.
Python has many built-in exceptions which forces your program to output an error when
something in it goes wrong. In Python, users can define such exceptions by creating a new
class. This exception class has to be derived, either directly or indirectly,
from Exception class.
ArrayIndexOutOfBoundException.
ClassNotFoundException.
FileNotFoundException.
IOException.
InterruptedException.
NoSuchFieldException.
NoSuchMethodException
114
Handling Exceptions:
The cause of an exception is often external to the program itself. For example, an incorrect
input, a malfunctioning IO device etc. Because the program abruptly terminates on
encountering an exception, it may cause damage to system resources, such as files. Hence,
the exceptions should be properly handled so that an abrupt termination of the program is
prevented.
Python uses try and except keywords to handle exceptions. Both keywords are followed by
indented blocks.
Syntax:
try :
except :
Syntactical errors
At developer level and compile level it gives errors.
Logical errors
As a developer we test the application, during that time logical error may obtained.
1. You should be able to understand the mistakes; the error might be done by user, DB
connection or server.
2. Whenever there is an error execution should not
stop. Ex: Banking Transaction
3. The aim is execution should not stop even though an error occurs.
115
For ex:
a=5
b=2
print(a/b)
print("Bye")
Output:
C:/Users/VTU/AppData/Local/Programs/Python/Python38-32/pyyy/ex1.py 2.5
Bye
The above is normal execution with no error, but if we say when b=0, it is a
critical and gives error, see below
a=5
b=0
print(a/b)
Output:
print(a/b)
a=5
b=0
116
try:
print(a/b)
except Exception:
print("number can not be divided by zero")
print("bye")
Output:
C:/Users/VTU/AppData/Local/Programs/Python/Python38-32/pyyy/ex3.py
bye
The except block executes only when try block has an error, check it below
a=5
b=2
try:
print(a/b)
except Exception:
print("bye")
Output:
C:/Users/VTU/AppData/Local/Programs/Python/Python38-32/pyyy/ex4.py 2.5
For example if you want to print the message like what is an error in a program
a=5
b=0
try:
117
print(a/b)
except Exception as e:
print("bye")
Output:
C:/Users/VTU/AppData/Local/Programs/Python/Python38-32/pyyy/ex5.py
bye
(Type of error)
a=5
b=2
try:
print("resource opened")
print(a/b)
print("resource closed")
except Exception as e:
Output:
2.5
resource closed
118
Note: the file is opened and closed well, but see by changing the value of b to 0,
a=5
b=0
try:
print("resource opened")
print(a/b)
print("resource closed")
except Exception as e:
Output:
a=5
b=0
try:
print("resource opened")
print(a/b)
except Exception as e:
print("resource closed")
Output:
119
C:/Users/VTU /Programs/Python/Python38-32/pyyy/ex8.py resource opened
resource closed
The result is fine that the file is opened and closed, but again change the value of
b to back (i.e., value 2 or other than zero)
a=5
b=2
try:
print("resource opened")
print(a/b)
except Exception as e:
print("number can not be divided by zero",e)
print("resource closed")
Output:
C:/Users/VTU/AppData/Local/Programs/Python/Python38-32/pyyy/ex9.py
resource opened
2.5
Note: Except block executes, only when try block has an error, but finally block
executes, even though you get an exception.
a=5
b=0
try:
120
print("resource open")
print(a/b)
k=int(input("enter a number"))
print(k)
except ZeroDivisionError as e:
print("the value can not be divided by zero",e)
finally:
print("resource closed")
Output:
C:/Users/VTU /Programs/Python/Python38-32/pyyy/ex10.py resource open
the value can not be divided by zero division by zero
resource closed
change the value of b to 2 for above program, you see the output like
C:/Users/VTU/AppData/Local/Programs/Python/Python38-32/pyyy/ex10.py
resource open
2.5
enter a number 6
6
resource closed
Instead give input as some character or string for above program, check the
output
C:/Users/VTU /Programs/Python/Python38-32/pyyy/ex10.py resource open
2.5
enter a number p
resource closed
Traceback (most recent call last):
File "C:/Users/VTU/Programs/Python/Python38-32/pyyy/ex10.py", line 7, in <module>
k=int(input("enter a number"))
ValueError: invalid literal for int() with base 10: ' p'
121
#
a=5
b=0
try:
print("resource open")
print(a/b)
k=int(input("enter a number"))
print(k)
except ZeroDivisionError as e:
print("the value can not be divided by zero",e)
except ValueError as e:
print("invalid input")
except Exception as e:
print("something went wrong...",e)
finally:
print("resource closed")
Output:
C:/Users/VTU /Programs/Python/Python38-32/pyyy/ex11.py resource open
the value can not be divided by zero division by zero
resource closed
Change the value of b to 2 and give the input as some character or string (other
than int)
C:/Users/VTU /Programs/Python/Python38-32/pyyy/ex12.py resource open
2.5
enter a number p
invalid input
resource closed
122
We use modules to break down large programs into small manageable and organized
files. Furthermore, modules provide reusability of code.
We can define our most used functions in a module and import it, instead of copying
their definitions into different programs.
Advantages :
Simplicity: Rather than focusing on the entire problem at hand, a module typically
Functions, modules and packages are all constructs in Python that promote code
modularization.
A file containing Python code, for e.g.: example.py, is called a module and its module name
would be example.
result=a+b
return result
123
Here, we have defined a function add() inside a module named example. The function takes
in two numbers and returns their sum.
We can import the definitions inside a module to another module or the Interactive
interpreter in Python.
Using the module name we can access the function using dot (.) operation. For Eg:
>>> example.add(5,5)
10
Python has a ton of standard modules available. Standard modules can be imported
the same way as we import our user-defined modules.
Reloading a module:
def hi(a,b):
print(a+b)
hi(4,4)
Output:
C:/Users/VTU /Programs/Python/Python38-32/pyyy/add.py 8
124
>>> import add
>>>
Python provides a neat way of doing this. We can use the reload() function inside
the imp module to reload a module. This is how its done.
This code got executed >>> import my_module >>> imp.reload(my_module) This
code got executed <module 'my_module' from '.\\my_module.py'>how its done.
>>> imp.reload(add)
>>> dir(example)
['__builtins ', ' cached ', ' doc__', ' file__', ' loader ', ' name ', '__package ',
' spec ', 'add']
>>> dir()
['__annotations ', ' builtins ', ' doc ', ' file ', ' loader ', ' name ',
' package ', ' spec ', '__warningregistry__', 'add', 'example', 'hi', 'imp']
For ex:
125
>>> example. name
'example'
Datetime module:
>>> a=datetime.datetime(2019,5,27,6,35,40)
>>> a
import datetime
a=datetime.date(2000,9,18)
print(a)
Output:
import datetime
a=datetime.time(5,3)
print(a)
Output:
C:/Users/VTU/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
05:03:00
#write a python program to print date, time for today and now.
import datetime
126
a=datetime.datetime.today()
b=datetime.datetime.now()
print(a)
print(b)
Output:
C:/Users/VTU/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
2019-11-29 12:49:52.235581
2019-11-29 12:49:52.235581
#write a python program to add some days to your present date and print the date
added.
import datetime
a=datetime.date.today()
b=datetime.timedelta(days=7)
print(a+b)
Output:
C:/Users/VTU/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
2019-12-06
#write a python program to print the no. of days to write to reach your birthday
import datetime
a=datetime.date.today()
b=datetime.date(2020,5,27)
c=b-a
print(c)
Output:
127
C:/Users/VTU/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
#write an python program to print date, time using date and time functions
import datetime
t=datetime.datetime.today()
print(t.date())
print(t.time())
Output:
C:/Users/VTU/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
2019-11-29
12:53:39.226763
Time module:
import time
print(time.time())
Output:
C:/Users/VTU/AppData/Local/Programs/Python/Python38-32/pyyy/t1.py =
1575012547.1584706
import time
print(time.localtime(time.time()))
Output:
C:/Users/VTU/AppData/Local/Programs/Python/Python38-32/pyyy/t1.py =
128
time.struct_time(tm_year=2019, tm_mon=11, tm_mday=29, tm_hour=13, tm_min=1,
tm_sec=15, tm_wday=4, tm_yday=333, tm_isdst=0)
import time
a=(1999,5,27,7,20,15,1,27,0)
print(time.mktime(a))
Output:
import time
print("Python Lab")
Output:
os module:
>>> import os
>>> os.name
'nt'
>>> os.mkdir("temp1")
129
Note: temp1 dir is created
>>> open("t1.py","a")
>>> os.access("t1.py",os.F_OK)
True
>>> os.access("t1.py",os.W_OK)
True
>>> os.rename("t1.py","t3.py")
>>> os.access("t1.py",os.F_OK)
False
>>> os.access("t3.py",os.F_OK)
True
>>> os.rmdir('temp1')
(or)
os.rmdir('C:/Users/VTU/Programs/Python/Python38-32/pyyy/temp1')
130
Note: Temp1dir is removed
>>> os.remove("t3.py")
Note: We can check with the following cmd whether removed or not
>>> os.access("t3.py",os.F_OK)
False
>>> os.listdir()
['add.py', 'ali.py', 'alia.py', 'arr.py', 'arr2.py', 'arr3.py', 'arr4.py', 'arr5.py', 'arr6.py', 'br.py',
'br2.py', 'bubb.py', 'bubb2.py', 'bubb3.py', 'bubb4.py', 'bubbdesc.py', 'clo.py', 'cmndlinarg.py',
'comm.py', 'con1.py', 'cont.py', 'cont2.py', 'd1.py', 'dic.py', 'e1.py', 'example.py', 'f1.y.py',
'flowof.py', 'fr.py', 'fr2.py', 'fr3.py', 'fu.py', 'fu1.py', 'if1.py', 'if2.py', 'ifelif.py', 'ifelse.py',
'iff.py', 'insertdesc.py', 'inserti.py', 'k1.py', 'l1.py', 'l2.py', 'link1.py', 'linklisttt.py', 'lis.py',
'listlooop.py', 'm1.py', 'merg.py', 'nesforr.py', 'nestedif.py', 'opprec.py', 'paraarg.py',
'qucksort.py', 'qukdesc.py', 'quu.py', 'r.py', 'rec.py', 'ret.py', 'rn.py', 's1.py', 'scoglo.py',
'selecasce.py', 'selectdecs.py', 'stk.py', 'strmodl.py', 'strr.py', 'strr1.py', 'strr2.py', 'strr3.py',
'strr4.py', 'strrmodl.py', 'wh.py', 'wh1.py', 'wh2.py', 'wh3.py', 'wh4.py', 'wh5.py',
' pycache__']
Calendar module:
131
#write a python program to display a particular month of a year using calendar
module.
import calendar
print(calendar.month(2020,1))
Output:
# write a python program to check whether the given year is leap or not.
import calendar
print(calendar.isleap(2021))
Output:
import calendar
print(calendar.calendar(2020,1,1,1))
Output:
132
math module:
# write a python program which accepts the radius of a circle from user and computes
the area.
import math
r=int(input("Enter radius:"))
area=math.pi*r*r
Output:
133
C:/Users/VTU /Programs/Python/Python38-32/pyyy/m.py = Enter radius:4
For Eg:
We have renamed the math module as m. This can save us typing time in some cases.
Note that the name math is not recognized in our scope. Hence, math.pi is
invalid, m.pi is the correct implementation.
We can import specific names from a module without importing the module as a
whole. Here is an example.
In such case we don't use the dot operator. We could have imported multiple attributes
as follows.
134
>>> from math import pi, e
>>> pi
3.141592653589793
>>> e
2.718281828459045
We can import all names(definitions) from a module using the following construct.
We imported all the definitions from the math module. This makes all names except
those beginnig with an underscore, visible in our scope.
Explore packages:
We don't usually store all of our files in our computer in 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 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.
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.
135
If a file named __init .py is present in a package directory, it is invoked when the
package or a module in the package is imported. This can be used for execution of
package initialization code, such as initialization of package-level data.
We can import modules from packages using the dot (.) operator.
For example, if want to import the start module in the above example, it is done as
follows.
import Game.Level.start
Now if this module contains a function named select_difficulty(), we must use the
full name to reference it.
Game.Level.start.select_difficulty(2)
136
If this construct seems lengthy, we can import the module without the package prefix
as follows.
start.select_difficulty(2)
Yet another way of importing just the required function (or class or variable) form a
module within a package would be as follows.
select_difficulty(2)
Examples:
def read():
print("Department")
def write():
print("Student")
Output:
>>> student.read()
Department
>>> student.write()
Student
>>> read
137
<function read at 0x03BD1070>
>>> read()
Department
>>> write()
Student
c=a+b
return c
Output:
C:\Users\VTU\AppData\Local\Programs\Python\Python38-32\IIYEAR\modu1.py
>>> modu1.add()
10
def a():
print("hello world")
a()
Output:
hello world
138