Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

PYTHON PROGRAMMING

(Subject Code: CS311PC)

NOTES MATERIAL
UNIT2

For
B. TECH (AI&DS)
2nd YEAR – 1st SEM (R18)

Faculty:
B. RAVIKRISHNA

DEPARTMENT OF AI&DS
VIGNAN INSTITUTE OF TECHNOLOGY & SCIENCE
DESHMUKHI
PYTHON PROGRAMMING UNIT–I

UNIT – II Syllabus:
Files, Exceptions and Modules
(Chapters 9, 10,12; Text Book: Chun, Core PP, 2nd Edition (2006))
Files: File Objects, File Built-in Function [ open ()], File Built-in Methods, File Built-in Attributes, Standard
Files, Command-line Arguments, File System, File Execution, Persistent Storage Modules, Related Modules
Exceptions: Exceptions in Python, Detecting and Handling Exceptions, Context Management, *Exceptions
as Strings, Raising Exceptions, Assertions, Standard Exceptions, *Creating Exceptions, Why Exceptions
(Now)? Why Exceptions at All? Exceptions and the sys Module, Related Modules.
Modules: Modules and Files, Namespaces, Importing Modules, Importing Module Attributes, Module Built-
in Functions, Packages, Other Features of Modules

Index:
Files:
• File Objects
• File Built-in Function [open ()]
• File Built-in Methods
• File Built-in Attributes
• Standard Files
• Command-line Arguments
• File System, File Execution
• Persistent Storage Modules
• Related Modules

Exceptions:
• Exceptions: Exceptions in Python
• Detecting and Handling Exceptions
• Context Management
• *Exceptions as Strings
• Raising Exceptions
• Assertions
• Standard Exceptions
• *Creating Exceptions
• Why Exceptions (Now)? Why Exceptions at All? Exceptions and the sys Module
• Related Modules.

Modules:
• Modules and Files
• Namespaces
• Importing Modules
• Importing Module Attributes
• Module Built-in Functions
• Packages
• Other Features of Modules

RK VIGNAN VITS – AI&DS 2|Page


PYTHON PROGRAMMING UNIT–I

Python Files & File Objects


Sometimes, it is not enough to only display the data on the console. The data to be
displayed may be very large, and only a limited amount of data can be displayed on the
console since the memory is volatile, it is impossible to recover the programmatically
generated data again and again.
Def: A file is a container in computer storage devices used for storing data.
• When we want to read from or write to a file, we need to open it first. When we are
done, it needs to be closed so that the resources that are tied with the file are freed.
• File handling is an important part of any web application.
• Python has several functions for creating, reading, updating, and deleting files.
• The file-handling implementation is slightly lengthy or complicated in the other
programming language, but it is easier and shorter in Python.
• In Python, files are treated in two modes as text or binary.

File Access Modes for File Objects:


File operation can be done in the following order.
o Open a file
o Read or write - Performing operation
o Close the file
open ():
• The key function for working with files in Python is the open() function.
• The open() function takes two parameters; filename, and mode.
• There are four different methods (modes) for opening a file:
o "r" - Read - Default value. Opens a file for reading, error if the file does
not exist
o "a" - Append - Opens a file for appending, creates the file if it does not
exist
o "w" - Write - Opens a file for writing, creates the file if it does not exist
o "x" - Create - Creates the specified file, returns an error if the file exists
• In addition, you can specify if the file should be handled as binary or text
mode
o "t" - Text - Default value. Text mode
o "b" - Binary - Binary mode (e.g. images)

File Access Modes for file Objects:

SN Access Description
mode

1 r It opens the file to read-only mode. The file pointer exists at the
beginning. The file is by default open in this mode if no access mode
is passed.
2 rb It opens the file to read-only in binary format. The file pointer exists
at the beginning of the file.
3 r+ It opens the file to read and write both. The file pointer exists at the
beginning of the file.

RK VIGNAN VITS – AI&DS 3|Page


PYTHON PROGRAMMING UNIT–I

4 rb+ It opens the file to read and write both in binary format. The file
pointer exists at the beginning of the file.
5 w It opens the file to write only. It overwrites the file if previously
exists or creates a new one if no file exists with the same name. The
file pointer exists at the beginning of the file.
6 wb It opens the file to write only in binary format. It overwrites the file
if it exists previously or creates a new one if no file exists. The file
pointer exists at the beginning of the file.
7 w+ It opens the file to write and read both. It is different from r+ in the
sense that it overwrites the previous file if one exists whereas r+
doesn't overwrite the previously written file. It creates a new file if
no file exists. The file pointer exists at the beginning of the file.
8 wb+ It opens the file to write and read both in binary format. The file
pointer exists at the beginning of the file.
9 a It opens the file in the append mode. The file pointer exists at the
end of the previously written file if exists any. It creates a new file
if no file exists with the same name.
10 ab It opens the file in the append mode in binary format. The pointer
exists at the end of the previously written file. It creates a new file
in binary format if no file exists with the same name.
11 a+ It opens a file to append and read both. The file pointer remains at
the end of the file if a file exists. It creates a new file if no file exists
with the same name.
12 ab+ It opens a file to append and read both in binary format. The file
pointer remains at the end of the file.

File Object Built-in Attributes:


Once a file is opened and you have one file object, you can get various information related to
that file. A file object attribute helps us to get the information about the file. Here is a list of all
attributes related to file object –
File Description
Attribute
file.closed Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was opened.
file.name Returns name of the file.
file.softspace Returns false if space explicitly required with
print, true otherwise.

Example:
#Program Program to check the file attributes of a file object.
# Open a file
f = open("file1.txt", "r")
print ("Name of the file: ", f.name)
print ("File is Closed! : ", f.closed)
print ("Opening mode : ", f.mode)

RK VIGNAN VITS – AI&DS 4|Page


PYTHON PROGRAMMING UNIT–I

Output:
Name of the file: file1.txt
File is Closed! : False
Opening mode : r

File Operations: (File Built-in Function [open ()]


read():
To open a file for reading it is enough to specify the name of the file:
f = open("file1.txt")
The code above is the same as:
f = open("file1.txt", "r")
(or)
f = open("file1.txt", "rt")
Because "r" for read, and "t" for text are the default values, you do not need to specify
them.
Note: Make sure the file exists, or else you will get an error.
Output:
Content from <file1.txt>
This is a text document
to test file read write operations in python
AI&DS – Python Programming – By RK

Open a file on a different location:


Example:
f = open(""f = open("G:/RKCODES/pycodes/u2/marks.txt","r")
print(f.read())
Output:
Dept. of AI&DS | "II-I AI&DS_OnlineMarksReport" |
Test-1 Marks
S.No. Roll No. Name of the Student PP
1 21891A7201 A SUDHESHNA REDDY 88
2 21891A7202 PASULA ADITYA RAM 100
3 21891A7203 Y. RAJKUMAR 99
4 21891A7204 BANDA GAYATHRI 88
5 21891A7205 BADDAM SANJAY 99
6 21891A7206 BANDA PRANAVI 90
7 21891A7207 BEERAM ADITYA 89

Reading a file in parts:


By default the read() method returns the whole text, but you can also specify how many
characters you want to return:

Example:
f = open("file1.txt",'r')
print(f.read(0))
Output:
<nothing outputs>
Example:
print(f.read(2))

RK VIGNAN VITS – AI&DS 5|Page


PYTHON PROGRAMMING UNIT–I

Output:
Co
Example:
print(f.read(4))
Output:
nten
Example:
print(f.readline())
Output:
t from <file1.txt>
Example:
s= f.readlines() #till end of file
print(s)
Output:
['to test file read write operations in python\n', 'AI&DS\n', '\n']

Note: readlines() Output in raw format useful for developers to understand


complete formats of data.

Getting Input from Keyboard:


Input from Keyboard & Converting to different/relevant types:
Example:
#Getting Input from Keyboard
s=input("Enter Text: ")
print(s, type(s))
Output:
Enter Text: Entering input from keyboard
Entering input from keyboard <class 'str'>
Example:
#Converting str to int
i=input("Enter a int number: ")
print(i,type(i))
i1=int(i)
print(i1,type(i1))
Output:
Enter a int number: 25
25 <class 'str'>
25 <class 'int'>
Example:
#Converting str to float
f=input("Enter float No.: ")
print(f,type(f))
f1=float(f)
print(f1, type(f1))
Output:
Enter float No.: 12.34
12.34 <class 'str'>

RK VIGNAN VITS – AI&DS 6|Page


PYTHON PROGRAMMING UNIT–I

12.34 <class 'float'>


Example:
#Converting String to Complex:
c=input("Enter a complex number: ")
print(c,type(c))
c1=complex(c)
print(c1,type(c1))
Output:
Enter a complex number: 3+4J
3+4J <class 'str'>
(3+4j) <class 'complex'>

Write to a File and reading using “w” and “w+”


write():
"w" - Write - will overwrite any existing content – used only to write
“w+” – used to write first read next operations.

Program:
f = open("newfile.txt","w+")
s1 = "File contents for newfile.txt"
f.write(s1)
s2="\nMore content for newfile.txt"
f.write(s2)
s3=input("Enter content from keyboard to file:")
f.write("\n Input from keyboard \n")
f.write(s3)
f.tell()
f.seek(0)
print("newfile.txt contents: \n",f.read())
f.close()
Output:
Enter content from keyboard to file: Entering Input from Keyboard to
file\n AI&DS-Python
newfile.txt contents:
File contents for newfile.txt
More content for newfile.txt
input from keyboard
Entering Input from Keyboard to file
AI&DS-Python

Read and write content into a file using “r+”:


Program:
f = open("newfile.txt","r+")
print(f.read())
f.seek(0,2)
f.tell()

RK VIGNAN VITS – AI&DS 7|Page


PYTHON PROGRAMMING UNIT–I

s = "More File contents from newfile.txt \n"


f.write(s)
f.write(input("Enter still more:"))
f.seek(0)
print(f.read())
f.close()
Output:
File contents for newfile.txt
More content for newfile.txt
input from keyboard
Entering Input from Keyboard to file
120
120
Enter still more: Entering Data from Keyboard. Python Files
.
.
File contents for newfile.txt
More content for newfile.txt
input from keyboard
Entering Input from Keyboard to fileMore File contents from
newfile.txt
Entering Data From Keyboard..Python Files

write(), writable(), writelines():


writable(): Returns whether the file can be written to or not
write() : Writes the specified string to the file
writelines(): Writes a list of strings to the file
Program:
f=open("file3.txt","w+")
f.writable()
f.write("multile\nstrings\ncan be added")
f.tell()
f.seek(0)
print(f.read())

f.writelines(["\nstill more", "lines can be\n ", "added in


writelines\n"])
f.tell()
f.seek(0)
print(f.read())
f.close()
Output:
multile
strings
can be added
multile
strings

RK VIGNAN VITS – AI&DS 8|Page


PYTHON PROGRAMMING UNIT–I

can be added
still morelines can be
added in writelines

Appending content to a file: (Write to an Existing File)


"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
Example:
Open the file "demofile2.txt" and append content to the file:
f = open(“frdwt.txt", "a")
f.write("Now the file has more content!")
f.close()
#open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())

Python program to check weather a files exists in the current


directory/folder or not using os.path.isfile() method:
isfile():
• Python contains 'OS' module that contains a submodule called 'path
module'. This contains a method 'isfile()'
• It iss used to check whether the file exists in the current
directory or not.
• If exists it opens otherwise it returns false.

#A python program to know whether a file exists or not


Program:
import os
fname=input("Enter file name :")
if(os.path.isfile(fname)):
f=open(fname,"r")
print("The file Contents are : ")
str=f.read()
print(str)
f.close()
else:
print(fname," does not exist")
Output:
Enter file name :nofile.txt
nofile.txt does not exist

Another method “exists()”:


Program:
import os.path as ope
ope.exists("marks2.txt") #used to check weather or not a file
exist

RK VIGNAN VITS – AI&DS 9|Page


PYTHON PROGRAMMING UNIT–I

ope.exists("nofile.txt")
Output:
True
False

Copy a file to another:


Program:
import shutil
shutil.copy("file1.txt", "copyfile.txt")
Output:
<a new file “copyfile.txt” will be created, “file1.txt” will be
copied to it>

Resize and check a file is readable or not:


truncate() : Resizes the file to a specified size
readable() : tells whether or not a file is readable(T/F)

Program:
#Truncate a file using ‘truncate()’
f = open("copyfile.txt","r+")
print(f.read())
f.readable() #tell weather or not a file is readable

f.tell()

f.truncate(100)
f.seek(0)
print(f.read())
f.close()

Output:
Content from <file1.txt>
This is a text document
to test file read write operations in python
AI&
Note: <copyfile.txt truncated to 100 chars>

#Program to check whether a file connected to a terminal or not!


# isatty(): Check if the file is connected to a terminal device:
Program:
f=open("file1.txt","r")
f.seek(0)
print(f.isatty()) #returns T or F
Output:
False

#Program to get the number of File Descriptor:


fileno():
• This method is an inbuilt method in Python, used to get the file
number i.e., the file descriptor as an integer of the stream.
• It may return an error if an operating system does not use
• a file descriptor of the file is closed.

RK VIGNAN VITS – AI&DS 10 | P a g e


PYTHON PROGRAMMING UNIT–I

Program:
f1=open("file1.txt","r")
f2=open("file2.txt","r")
f3=open("file2.txt","r")

# f1,f2,f3 are called file descriptors


f1.fileno() #prints a number(integer)
f2.fileno() #prints a different number(integer)
f3.fileno() #prints another different number(integer)
Output:
5
6
7
#Program to read and write Binary files
Program:
f=open("crc1.jpeg","rb")
f.read()
f.seek(0)

f = open("binfile.bin","wb+")
a = [3,4,5]
# Convert the integer elements to a bytearray
bytary = bytearray(a)

# The byte representation ius now written to the file


f.write(bytary)
f.tell()
f.seek(0)
f.read()
f.close()
Output:
b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x
00\xff\xdb\x00\x84\x00\x06\x06\x06\x06\x07\x06\x07\x08\x08\x07\n\x0b
\n\x0b\n\x0f\x0e\x0c\x0c\x0e\x0f\x16\x10\x11\x10\x11\x10\x16"\x15\x1
9\x15\x15\x19\x15"\x1e$\x1e\x1c\x1e$\x1e6*&&*6>424>LDDL_Z_||\xa7\x01
\x06\x06\x06\x06\x07\x06\x07\x08\x08\x07\n\x0b\n\x0b\n\x0f\x0e\x0c\x
0c\x0e\x0f\x16\x10\x11\x10\x11\x10\x16"\x15\x19\x15\x15\x19\x15"\x1e
$\x1e\x1c\x1e$\x1e6*&&*6>424>LDDL_Z_||\xa7\xff\xc2\x00\x11\x08\x

# Program to display image file using module Image from PIL module
Program:
from PIL import Image
# open method used to open different extension image file
im = Image.open("img.jpg")
# This method will show image in any image viewer
im.show()
Output:
<you can see the image file displayed>

RK VIGNAN VITS – AI&DS 11 | P a g e


PYTHON PROGRAMMING UNIT–I

Command-line Arguments
• Python Command Line Arguments provides a convenient way to accept some
information at the command line while running the program.
• The arguments that are given after the name of the Python script are known as
Command Line Arguments and they are used to pass some information to the
program.
For example:
>>> python script.py arg1 arg2 arg3
sys module - System-specific parameters:
The Python sys module provides access to any command-line arguments via the
sys.argv.
This serves two purposes −
sys.argv is the list of command-line arguments.
len(sys.argv) is the number of command-line arguments.
Here sys.argv[0] is the program ie. script name.
Program:
#Python program to perform addition of two numbers and find factorial of
result, pass two values as command line arguments
import sys
from math import factorial
n=len(sys.argv)
print("No. of Args passed", n)
print("Args are: ", sys.argv)
s=int(sys.argv[1])+int(sys.argv[2])
print("Sum of", sys.argv[1], " and", sys.argv[2]," is: ",s)
# print("Sum : %d"%s)
print("Factorial of sum : ",s,"! =", factorial(s))
Output:
Now open command prompt and follow below specified:

RK VIGNAN VITS – AI&DS 12 | P a g e


PYTHON PROGRAMMING UNIT–I

Python Standard Files


• There are generally three standard files that are made available to us when our
program starts.
• These are standard input (usually the keyboard), standard output (buffered output
to the monitor or display), and standard error (unbuffered output to the screen).
• Python makes these file handles available to you from the sys module. Once we
import sys, you have access to these files as sys.stdin, sys.stdout, and
sys.stderr. The print statement normally outputs to sys.stdout while the
raw_input() built-in function receives its input from sys.stdin.

File System:
• Access to your file system occurs mostly through the Python os module. This
module serves as the primary interface to your operating system facilities and
services from Python.
• The os module is actually a front-end to the real module that is loaded, a module
that is clearly operating system dependent.
• This "real" module may be one of the following: posix (Unix-based, i.e., Linux,
MacOS X, *BSD, Solaris, etc.), nt (Win32), mac (old MacOS), dos (DOS), os2 (OS/2),
etc.
• Depending on what your system supports, you may not have access to some of the
attributes, which may be available in other operating system modules.
• In addition to managing processes and the process execution environment, the os
module performs most of the major file system operations that the application
developer may wish to take advantage of.
• These features include removing and renaming files, traversing the directory tree,
and managing file accessibility.
• Table: lists some of the more common file or directory operations available to you
from the os module.

RK VIGNAN VITS – AI&DS 13 | P a g e


PYTHON PROGRAMMING UNIT–I

File Execution:
• Whether we want to simply run an operating system command, invoke a binary
executable, or another type of script (perhaps a shell script, Perl, or Tcl/Tk), this
involves executing another file somewhere else on the system. Even running other
Python code may call for starting up another Python interpreter, although that may
not always be the case.

Persistent Storage Modules:


• In many of the exercises in this text, user input is required. After many iterations,
it may be somewhat frustrating being required to enter the same data repeatedly.
The same may occur if you are entering a significant amount of data for use in the
future. This is where it becomes useful to have persistent storage.
• Persistent storage is a way to archive your data so that you may access them at a
later time instead of having to re-enter all of that information.

RK VIGNAN VITS – AI&DS 14 | P a g e


PYTHON PROGRAMMING UNIT–I

• Python's built-in file object returned by Python's built-in open() function has one
important shortcoming. When opened with 'w' mode, the write() method accepts
only the string object.
• That means, if you have data represented in any non-string form, the object of
either in built-in classes (numbers, dictionary, lists or tuples) or other user-defined
classes, it cannot be written to file directly. Before writing, you need to convert it
in its string representation.
• When simple disk files are no longer acceptable and full relational database
management systems (RDBMSs) are overkill, simple persistent storage fills the gap.
• The majority of the persistent storage modules deals with storing strings of data,
but there are ways to archive Python objects as well.

Python Data Persistence - Object Serialization:

pickle and marshal Modules:


• Python provides a variety of modules that implement minimal persistent storage.
One set of modules (marshal and pickle) allows for pickling of Python objects.
Pickling is the process whereby objects more complex than primitive types can be
converted to a binary set of bytes that can be stored or transmitted across the
network, then be converted back to their original object forms.
• Pickling is also known as flattening, serializing, or marshalling.
• Another set of modules (dbhash/bsddb, dbm, gdbm, dumbdbm) and their
"manager" (anydbm) can provide persistent storage of Python strings only.
• The last module (shelve) can do both.
• Both marshal and pickle can flatten Python objects. These modules do not provide
"persistent storage" however, is to pickle Python objects to allow them to be stored
or transmitted. Storage, of course, is sequential in nature (you store or transmit
objects one after another).
• The difference between marshal and pickle is that marshal can handle only simple
Python objects (numbers, sequences, mapping, and code) while pickle can
transform recursive objects, objects that are multi-referenced from different places,
and user-defined classes and instances.
• The pickle module is also available in a turbo version called cPickle, which
implements all functionality in C.
DBM-style Modules:
• The *db* series of modules writes data in the traditional DBM format.
• There are a large number of different implementations: dbhash/bsddb, dbm, gdbm,
and dumbdbm.
• The dumbdbm module is the most limited one, and is the default used if none of the
other packages is available.
• These modules do provide a namespace for your objects, using objects that behave
similar to a combination of a dictionary object and a file object.
• The one limitation of these systems is that they can store only strings.
• In other words, they do not serialize Python objects.

RK VIGNAN VITS – AI&DS 15 | P a g e


PYTHON PROGRAMMING UNIT–I

Shelve:
• Finally, we have a somewhat more complete solution, the shelve module. The shelve
module uses the any dbm module to find a suitable DBM module, then uses cPickle
to perform the pickling process. The shelve module permits concurrent read access
to the database file, but not shared read/write access.
• This is about as close to persistent storage as you will find in the Python standard
library.

Persistent Storage Modules other external extension modules that implement "true" persistent
storage. The diagram in Figure shows the relationship between the pickling modules and the
persistent storage modules, and how the shelve object appears to be the best of both worlds.

Related Modules:
There are plenty of other modules related to files and input/output, all of which work on most
of the major platforms.
Below Table lists some of the file related modules.
Table: Related File Modules
Module(s) Contents
base64 Encoding/decoding of binary strings to/from text strings
binascii Encoding/decoding of binary and ASCII-encoded binary strings
bz2 Allows access to BZ2 compressed files
csv Allows access to comma-separated value files
filecmp Compares directories and files
fileinput Iterates over lines of multiple input text files

RK VIGNAN VITS – AI&DS 16 | P a g e


PYTHON PROGRAMMING UNIT–I

getopt/optparse Provides command-line argument parsing/manipulation


glob/fnmatch Provides Unix-style wildcard character matching
Reads and writes GNU zip (gzip) files (needs zlib module for
gzip/zlib
compression)
shutil Offers high-level file access functionality
c/StringIO Implements file-like interface on top of string objects
tarfile Reads and writes TAR archive files, even compressed ones
tempfile Generates temporary file names or files
uu uuencode and uudecode files
zipfile Tools and utilities to read and write ZIP archive file

Exceptions in Python:
Before knowing about Exception, let’s understand about errors in programming.
What’s an Error?
▪ Errors are the problems in a program due to which the program will stop the
execution. On the other hand, exceptions are raised when some internal events occur
which changes the normal flow of the program.
▪ Two types of Error occur in python.
▪ Syntax errors
▪ Logical errors (Exceptions)

▪ Syntax Errors:
Syntax errors, also known as parsing errors, are perhaps the most common kind
of complaint you get while you are still learning Python:

>>> while True print ('Hello world')


File "<stdin>", line 1
while True print ('Hello world')
^
SyntaxError: invalid syntax

Exceptions (Logical Errors):


▪ Even if a statement or expression is syntactically correct, it may cause an error
when an attempt is made to execute it.
▪ Errors detected during execution are called exceptions and are not unconditionally
fatal: Most exceptions are not handled by programs, however, and result in few
error messages as shown here:
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>

RK VIGNAN VITS – AI&DS 17 | P a g e


PYTHON PROGRAMMING UNIT–I

NameError: name 'spam' is not defined


>>> '2' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

Why Exceptions (Now)? (Why Exceptions at All?)


Why should we use Exceptions?
Here are the reasons for using exceptions in Python:

• Exception handling allows you to separate error-handling code from normal code.
• As with code comments, exceptions helps you to remind yourself of what the
program expects.
• It clarifies the code and enhances readability.
• Allows you to stimulate consequences as the error-handling takes place at one
place and in one manner.
• An exception is a convenient method for handling error messages.
• Raising an exception helps you to break the current code execution and returns
the exception back to expectation until it is handled.
• Processing exceptions for components which can’t handle them directly.

Detecting and Handling Exceptions:


In Python, we can throw an exception in the try block and catch it in except block.

Syntax:
try:
• The try block lets you test a block of code for errors.

except:
• If the try block encounters an exception, except block will handle it.

else:
• If there is no exception, else code block will be executed.

finally:
The finally block lets you execute code,
regardless of the result of the try- and except
blocks.

Figure to understand each block objective:

RK VIGNAN VITS – AI&DS 18 | P a g e


PYTHON PROGRAMMING UNIT–I

Example:
print(x) #error if x not defined.
Output:
Traceback (most recent call last):
Cell In[25], line 1
print(x) #error if x not defined.
NameError: name 'x' is not defined

Example:
#Exception when x is not defined
try:
print("x is defined and x= ",x)

except:
print("exception raised Something went wrong")

Output:
exception raised Something went wrong

Example:
#Named Exception when x is not defined
try:
print("x is defined and x= ",x)

except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")

Output:
Variable x is not defined

Example:
# Exception with else: else executes if try didn't raise exception
try:
x=3
print("x is defined and x= ",x)

except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
else:
print("Nothing went wrong")

Output:
x is defined and x= 3

RK VIGNAN VITS – AI&DS 19 | P a g e


PYTHON PROGRAMMING UNIT–I

Nothing went wrong

Program:
#Exception with something else: x is defined, but raising another exception
x = 4
try:
print("x is defined and x= ", x)
print("x/0", x/0)

except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")

else:
print("Nothing went wrong")
Output:
x is defined and x= 4
Something else went wrong

Program:
#finally block & out of try & exception blocks
try:
print("x/0",x/0)
print("x is defined and x= ",x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
else:
print("Nothing went wrong")
finally:
print("finally executes 'finally block' ")
print("Out of try block")
Output:
Something else went wrong
finally executes 'finally block'
Out of try block

RK VIGNAN VITS – AI&DS 20 | P a g e


PYTHON PROGRAMMING UNIT–I

List of Standard/In-Built Exceptions in Python:

Sr.No. Exception Name Description


1 Exception Base class for all exceptions
Raised when division or modulo by zero takes place
2 ZeroDivisionError
for all numeric types.
3 SystemExit Raised by the sys.exit() function.
4 FloatingPointError Raised when a floating-point calculation fails.
5 AssertionError Raised in case of failure of the Assert statement.
Raised when an identifier is not found in the local
6 NameError
or global namespace.
7 IndexError Raised when an index is not found in a sequence.
8 IndentationError Raised when indentation is not specified properly.
9 SyntaxError Raised when there is an error in Python syntax.
10 IOError Raised for operating system-related errors.
Base class for all built-in exceptions except
11 StandardError
StopIteration and SystemExit.
Base class for all errors that occur for numeric
12 ArithmeticError
calculation.
Raised when a calculation exceeds maximum limit for
13 OverflowError
a numeric type.
Raised when there is no input from either the
14 EOFError raw_input() or input() function and the end of file
is reached.
Raised in case of failure of attribute reference or
15 AttributeError
assignment.
Raised when the next() method of an iterator does
16 StopIteration
not point to any object.
17 ImportError Raised when an import statement fails.
Raised when the user interrupts program execution,
18 KeyboardInterrupt
usually by pressing Ctrl+c.
19 LookupError Base class for all lookup errors.
Raised when the specified key is not found in the
20 KeyError
dictionary.

Raise an exception:
• As a Python developer you can choose to throw an exception if a condition occurs.
• To throw (or raise) an exception, use the raise keyword.
• The raise keyword is used to raise an exception.
• You can define what kind of error to raise, and the text to print to the user.
Example:
Python code to show how to raise an exception in Python
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")

RK VIGNAN VITS – AI&DS 21 | P a g e


PYTHON PROGRAMMING UNIT–I

Ouput:
TypeError: Only integers are allowed

Example:
#raise and exception under condition, with list
l = [1,2,3,4,5]
ln=len(l)
if ln > 3:
raise Exception ("Length of the given list must be less than or
equal to 3 but is", ln)

Assertion Error:

▪ The assert keyword is used when debugging code.

▪ The assert keyword lets you test if a condition in your code returns True, if not,
the program will raise an AssertionError.

▪ If the assert statement fails, this exception will be raised.

Example:
n=16
assert (n>0), "Needs a +ve Number"
n**(1/2)
Output:
4.0

Example:
n=-16
assert (n>0), "Needs a +ve Number"
n**(1/2)
Output:
Needs a +ve Number

User-defined Exception in Python? (Creating an exception)


▪ There is a lot built-in exception like IndexError, IOError, ImportError, ZeroDivisionError,
TypeError, etc. But, sometimes it is not enough and we have to create some custom exceptions
so that we can handle the errors in a better way and can create more meaningful exceptions.

▪ To create a custom Exception, we must create a new class. This exception class has to be
derived, directly or indirectly, from the built-in Exception class.

▪ Usually, the defined exception name ends with the word Error which follows the standard
naming convention; however, it is not compulsory to do so.

Example:
class MyError(Exception):

RK VIGNAN VITS – AI&DS 22 | P a g e


PYTHON PROGRAMMING UNIT–I

print("Calling Successful")

raise MyError("Error Present")

Output:
Calling Successful
Traceback (most recent call last):

Cell In[2], line 4


raise MyError("Error Present")

MyError: Error Present

Context Management - The ‘with’ Statement Approach:


• The Python with statement creates a runtime context that allows you to run a group of
statements under the control of a context manager. PEP 343 added the with statement to
make it possible to factor out standard use cases of the try … finally statement.
• Compared to traditional try … finally constructs, the with statement can make your code
clearer, safer, and reusable. Many classes in the standard library support
the with statement. A classic example of this is open(), which allows you to work with file
objects using ‘with’.

Example:
# Context Management - The with Statement Approach
with open("file1.txt", mode="a+") as f:
f.write("\nMore Contents!")
print("file contents added!")
Output:
file contents added!

Note: Though in the above code, we didn’t close the file, as we used context
using ‘with’, file closed once write operation is done. Hence you find the below
error.

Example:
f.tell() #Check the error
f.seek(0) #Check the error
Output:
ValueError: I/O operation on closed file.
ValueError: I/O operation on closed file.

Example: Again open and read the file


with open("file1.txt", mode="r+") as f:
print(f.read())
Output:
Hello, World!<file1.txt>
This is a text document
to test file read write operations in python
AI&DSHello, World!More Contents!

RK VIGNAN VITS – AI&DS 23 | P a g e


PYTHON PROGRAMMING UNIT–I

Modules In Python:

• Modules in Python are simply Python files with the .py extension that can contain a
set of functions, classes, or variables.
• In simple Python module is a file containing Python definitions and statements.
• Grouping related code into a module makes the code easier to understand and use.
• It also makes the code logically organized. We import those module/s to the required
program.
• An example_module.py file is a module we will create and whose name is
example_module.
• Rather than duplicating their definitions into several applications, we may define
our most frequently used functions in a separate module and then import the
complete module.

Let's construct a module. Save the file as example_module.py after entering the following.
First create a python file <file.py> and save, to use it as module.
#Program to create ‘mymodule.py’
#<mymodule.py>
#Creating a module with name ‘mymodule.py’.
def message(name):
print ("Imported from "+name)
d1 = {2:"Two", 'b':22, 3.4:"Three"}

def add(a,b):
return a*b
Note: No need to run the program
Importing mymodule.py in current file:
Program: <modexmple.py>
import mymodule
mymodule.message("mymodule.py")

Output:
Imported from mymodule.py

Importing mymodule.py in current file: modemple.py


Example:
import mymodule
a=mymodule.d1[‘b’]
print(a)
print(mymodule.d1["3.4"])

Output:
22
Three

RK VIGNAN VITS – AI&DS 24 | P a g e


PYTHON PROGRAMMING UNIT–I

Import methods or variables only instead of whole module:


Example:
from mymodule import d1
print(d1[3.4])
Output:
Three

Module can be imported and renamed:


Example:
import mymodule as mm
mm.message("mymodule.py and module can be renamed")
Output:
Imported from mymodule.py and module can be renamed

Importing add() method from mymodule.py and calculating


Example:
from mymodule import add as ad
ad(4,5)
Output:
20

System modules / standard modules / inbuilt modules:


Example:
import platform
x = platform.system()
print(x)
Output:
Windows
List of files and directories in platform:
Example:
x = dir(platform)
print(x)
Output:
['_WIN32_CLIENT_RELEASES', '_WIN32_SERVER_RELEASES', '__builtins__',
'__cached__', '__copyright__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__', '__version__',
'_comparable_version', '_component_re', '_default_architecture',
'_follow_symlinks', '_ironpython26_sys_version_parser',
'_ironpython_sys_version_parser', etc.]

Namespaces in Python Modules:


• In Python, a namespace is a mapping from names to objects. A namespace is
created whenever a new module is imported or a new function or class is defined.
Namespaces are used to keep variable and function names separate between
different modules and functions, so that there are no naming conflicts.
• A module is a single file that contains Python definitions and statements. When a
module is imported into a Python program, the code in the module is executed and

RK VIGNAN VITS – AI&DS 25 | P a g e


PYTHON PROGRAMMING UNIT–I

the module's namespace is created. This namespace contains all the variables,
functions, and classes defined in the module.
• When you import a module in Python, the contents of the module are added to a
new namespace, which is created specifically for that module. The namespace is
then made available to the rest of the program through the module's name.
• For example, if you have a module named "mymodule" and you import it using the
statement "import mymodule", you can access the contents of the module by
prefixing the names with the module name and a dot (.) like
mymodule.function_name or mymodule.class_name.

Here are a few examples to help understand how namespaces work in Python:
Using the import statement:
Example:
<mymodule.py>
x = 5
def print_x():
print(x)

# main.py
import mymodule

print(mymodule.x) # prints 5
mymodule.print_x() # prints 5

Here are a few examples to help understand how namespaces work in Python:
Using the import statement:
Example:
# mymodule.py
x = 5
def print_x():
print(x)

# main.py
import mymodule

print(mymodule.x) # prints 5
mymodule.print_x() # prints 5

Here, mymodule is a separate namespace with the variable x and function print_x() in it.
To access them, we need to use the namespace mymodule before the variable or function
name.

Example:
Using the 'from' statement:
<mymodule.py>
x = 5
def print_x():
print(x)
Copy code

RK VIGNAN VITS – AI&DS 26 | P a g e


PYTHON PROGRAMMING UNIT–I

# main.py
from mymodule import x, print_x

print(x) # prints 5
print_x() # prints 5

Here, we imported x and print_x() from the mymodule namespace into the current
namespace, so we can use them directly without referencing the namespace.

Related Modules:
The following are auxiliary modules that you may use when dealing with the import of Python
modules. Of these listed below, modulefinder, pkgutil, and zipimport are new as of Python 2.3,
and the distutils package was introduced back in version 2.0
• imp: this module gives you access to some lower-level importer functionality.
• Modulefinder: this is a module that lets you find all the modules that are used by a Python
script. You can either use the ModuleFinder class or just run it as a script giving it the
filename of a (nother) Python module with which to do module analysis on.
• pkgutil this module gives those putting together Python packages for distribution a way to
place package files in various places yet maintain the abstraction of a single "package" file
hierarchy. It uses *.pkg files in a manner similar to the way the site module uses *.pth files to
help define the package path.
• site using this module along with *.pth files gives you the ability to specify the order in which
packages are added to your Python path, i.e., sys.path, PYTHONPATH. You do not have to
import it xplicitly as the importer already uses it by defaultyou need to use the -S switch when
starting up Python to turn it off. Also, you can perform further arbitrary site-specific
customizations by adding a sitecustomize module whose import is attempted after the path
manipulations have been completed.
• zipimport this module allows you to be able to import Python modules that are archived in
ZIP files. Note that the functionality in this file is "automagically" called by the importer so
there is no need to import this file for use in any application. We mention it here solely as a
reference.
• distutils this package provides support for building, installing, and distributing Python
modules and packages. It also aids in building Python extensions written in C/C++.

Organize your code in Python packages:


We now have the following tools in our belt to properly organize our Python code:
• Packages
• Sub-packages
• Modules

RK VIGNAN VITS – AI&DS 27 | P a g e


PYTHON PROGRAMMING UNIT–I

Packages in Python:
• A Python package is a directory that contains zero or more Python modules.
• A Python package can contain sub-packages, which are also directories containing
modules.
• Each package always contains a special file named __init__.py.
• A package is a container that contains various functions to perform specific tasks.
• For example, the math package includes the sqrt() function to perform the square root of
a number.
• While working on big projects, we have to deal with a large amount of code, and writing
everything together in the same file will make our code look messy. Instead, we can
separate our code into multiple files by keeping the related code together in packages.

Structure of a Python package:


A Python package is a folder that contains Python modules and an __init__.py file. The structure
of a simple Python package with two modules is as follows:
.
└── package_name
├── __init__.py
├── module1.py
└── module2.py
As mentioned, packages can contain sub-packages. We can use sub-packages to organize our
code further. I’ll show you how to do that in more detail in one of the sections below. Let’s first
take a look at the structure of a package with sub-packages:
.
└── package_name
├── __init__.py
├── subpackage1
├── __init__.py
├── module1.py
└── subpackage2
├── __init__.py
├── module2.py
As you can see, packages are hierarchical, just like directories.

What is __init__.py in a Python package?


• The __init__.py file is a special file that is always executed when the package is
imported. When importing the package from above with import package_name, the
__init__.py file is executed.
• When importing the nested package from above, with import
package_name.subpackage1, the __init__.py file of both package_name and
subpackage1 are executed.
The order is as follows:
1. first the __init__.py file of package_name is executed,
2. then the __init__.py file of subpackage1.

RK VIGNAN VITS – AI&DS 28 | P a g e


PYTHON PROGRAMMING UNIT–I

Other Features of Modules:


Some key features of modules in Python include:
• Namespaces: Modules provide a way to organize and group related code, and to
separate it from other code in your program.
• Reusability: Modules can be imported and used in multiple projects, making it
easy to reuse and share code.
• Namespacing: Each module has its own namespace, which means that variables
and functions defined in one module do not interfere with those defined in another
module.
• Access control: Modules can define variables and functions that are intended for
internal use only, using the "private" naming convention.
• Built-in module system: Which allows you to import modules from the Python
standard library, as well as external libraries.
• Auto-Loaded Modules: When the Python interpreter starts up in standard mode, some
modules are loaded by the interpreter for system use. The only one that affects you is the
__builtin__ module, which normally gets loaded in as the __builtins__ module.

• The sys.modules variable consists of a dictionary of modules that the interpreter has
currently loaded (in full and successfully) into the interpreter. The module names are the
keys, and the location from which they were imported are the values.

• For example, in Windows, the sys.modules variable contains a large number of loaded
modules, so we will shorten the list by requesting only the module names. This is
accomplished by using the dictionary's keys() method:

>>> import sys


>>> sys.modules.keys()
[dict_keys(['sys', 'builtins', '_frozen_importlib', '_imp', '_thread',
'_warnings', '_weakref', 'winreg', '_io', 'marshal', 'nt',
'_frozen_importlib_external', 'time', 'zipimport', '_codecs', 'codecs',
'encodings.aliases', 'encodings', 'encodings.utf_8', 'encodings.cp1252',
'_signal', '_abc', 'abc', 'io', '__main__', '_stat', 'stat',
'_collections_abc', 'genericpath', '_winapi', 'ntpath', 'os.path', 'os',
'_sitebuiltins',…]

*** End of Unit – 2 ***

RK VIGNAN VITS – AI&DS 29 | P a g e

You might also like