Python Chap 6
Python Chap 6
Syntax Errors:
Errors that occur due to incorrect syntax.
Ex:
x=10
If x==10:
print(“x is 10”) #error (print spelling mistake)
Ex:
print(10/0) #ZeroDivisionErro
r
print(10/”Ten”) #TypeError
ZeroDivisionError
TypeError
ValueError
FileNotFoundError
EOFError
Output:
print(“Hello”) Hello
print(10/0) ZeroDivisionError:
print(“hi”)
Standard Built in exception
Exception
Base class
for all
exceptions
2 StopIteration
Raised when the next() method of an iterator does not point to any object.
3 SystemExit
Raised by the sys.exit() function.
4 StandardError
Base class for all built-in exceptions except StopIteration and SystemExit.
5 ArithmeticError
Base class for all errors that occur for numeric calculation.
6 OverflowError
Raised when a calculation exceeds maximum limit for a numeric type.
7 FloatingPointError
Raised when a floating point calculation fails.
8
ZeroDivisonError
Raised when division or modulo by zero takes place for all numeric types.
9
AssertionError
Raised in case of failure of the Assert statement.
10
AttributeError
Raised in case of failure of attribute reference or assignment.
11
EOFError
Raised when there is no input from either the raw_input() or input()
function and the end of file is reached.
12
ImportError
Raised when an import statement fails.
13
KeyboardInterrupt
Raised when the user interrupts program execution, usually by pressing
Ctrl+C.
LookupError
Base class for all lookup errors.
15
IndexError
Raised when an index is not found in a sequence.
16
KeyError
Raised when the specified key is not found in the dictionary.
17
NameError
Raised when an identifier is not found in the local or global namespace.
18
EnvironmentError
Base class for all exceptions that occur outside the Python
environment.
20
IOError
Raised when an input/ output operation fails, such as the print
statement or the open() function when trying to open a file that
does not exist.
21
OSError
Raised for operating system-related errors.
22
SyntaxError
Raised when there is an error in Python syntax.
23
IndentationError
Raised when indentation is not specified properly.
24
SystemError
Raised when the interpreter finds an internal problem, but when
this error is encountered the Python interpreter does not exit.
Exception Handling
Customized Exception Handling:
try:
block to check
except:
block to execute if try block fails
Ex:
x=10
y=0
try:
print(x/y) Output:
------------
except ZeroDivisionError: cannot divide 10 by 0
print("cannot divide 10 by 0")
Exception Handling
Control flow of try – except block:
---------------------------------------------
try:
statement – 1
statement – 2
statement – 3
except:
statement – 4
statement – 5
else:
statement – 6
Exception
Ex:
Handling
x=int(input("Enter the value of x: "))
Output:
y=int(input("Enter the value of y: "))
Enter the value of x: 4
try: Enter the value of y: 5
sum of x and y is: 9
print("sum of x and y is: ", x+y)
division of x and y is: 0.8
print("division of x and y is: ", x/y) Multiplicatn of x and y is: 20
print("Multiplication of x and y is: ", This is the end of statement
-----------------------------------------
x*y)
Enter the value of x: 4
except: Enter the value of y: 'f'
print("sorry, cannot perform the sorry, cannot perform
operation") the operation
This is the end of statement
print("This is the end of
statement")
Exception
Ex: Handling
import os
try:
print("writing the Risky code")
print(10/20)
os._exit(0)
except:
print("Nothing here") Output:
try:
Risky Code
except:
will be executed if exception inside try
else:
will be executed if there is no exception inside try
finally:
will be executed whether exception raised or not raised and
handled or not handled
Exception
try:
Handling
print("writing the Risky code")
except: Output:
print("Nothing here")
writing the Risky code
nothing went wrong
else: clean up code
print("nothing went wrong")
finally:
print("clean up code")
Exception
try:
Handling
print("writing the Risky code")
print(10/0)
Output:
except:
writing the Risky code
print("Nothing here") nothing went wrong
clean up code
else:
print("nothing went
wrong")
finally:
print("clean up code")
Exception Handling
Types of Exceptions:
In Python there are 2 types of exceptions are possible
⮚ Predefined Exceptions
⮚ User Defined Exceptions
Predefined Exceptions:
⮚ Also known as inbuilt exceptions.
⮚ The exceptions which are raised automatically by Python virtual
machine whenever a particular event occurs are called pre
defined exceptions.
Ex:
ZeroDivisionErro
r TypeError
…..
Exception Handling
User Defined Exceptions:
----------------------------------
⮚ Also known as Customized Exceptions or Programmatic Exceptions
⮚ Based on our requirement, we can define our own exceptions,
such type of programmer defined exceptions are called user
defined exceptions
⮚ Programmer is responsible to define these exceptions and
Python not having any idea about these. Hence we have to raise
explicitly based on our requirement by using "raise" keyword.
Eg:
InSufficientFundsException
InvalidInputException
………
……….
Exception Handling
How to Define and Raise Customized Exceptions:
⮚ Every exception in Python is a class that extends Exception class
either directly or indirectly.
Syntax:
class Classname(predefined exception class name):
def __init__ (self,arg):
self.msg=arg
Ex:
class TooYoungException(Exception):
def __init__ (self,arg):
self.msg=arg
class TooOldException(Exception):
def__init__(self,arg):
self.msg=arg
age=int(input("Enter Age:"))
if age>60:
raise TooYoungException("Plz wait some more time you will get
best match soon!!!")
elif age<18:
raise TooOldException("Your age already crossed marriage
age...no chance of getting marriage")
else:
File
Handling
File Handling
⮚ Used for storing date
⮚ As the part of programming requirement, we have to store our data
permanently for future purpose.
⮚ Generally files are used to store less amount of data. For storing the
large volumes of date we should go with databases.
Ex:
if I have to store a the data of 200 students in my class I will go
with file
if I have to store 200000 students data, it will be difficult to store
in a file, so we will go with database
⮚ We have 2 types of files
⮚ Text Files: to store character data
⮚ Binary Files: to store binary data like images, video files, audio files etc..
File Handling
⮚ If we want to perform any operation on a file, first we need to
open
a file.
⮚ In python, if we want to open a file, we need to specify for which
purpose we are opening the file (Ex: reading, writing, appending
etc)
Opening a file:
Python have an inbuilt function for opening a file.
Open()
Syntax:
f = open(‘filename’, ‘mode’)
⮚ r 🡪 Opens the file for reading. File must exist; otherwise, it raises
an error.
⮚ w 🡪 Opens the file for writing. Creates a new file or truncates the
existing file.
Note: All the modes are for text files only, if we want to use
these
modes for binary files then these should be suffixed with b
Ex: rb, wb, ab, xb
File Handling
⮚ After completing our operations on the file, it is highly recommended to
close the file.
⮚ For closing a file we have an inbuilt method f.close()
Output:
f=open("abc.txt","w") -----------
print("file Name is: ", f.name) file Name is: abc.txt
print("File Mode is: ", File Mode is: w
is file readable: False
f.mode) is file writable: True
print("is file readable: ", is file closed: False
f.readable()) print("is file writable: ", is file closed: True
f.writable()) print("is file closed: ",
f.closed) f.close()
print("is file closed: ", f.closed)
Ex:2 Output:
f=open("abc1.txt","r") -----------
FileNotFoundError
File Handling
Writing Data to text files:
⮚ We can write character data to the text files by using the following
2
methods.
⮚ write(str)
⮚ writelines(sequence of lines)#sequence may be list/tuple/set
Ex:1
Output:
f=open("C:\\Anand\\abc.txt","w"
-----------
) f.write("Hai this is the first line ") File will be created with Name
f.write("this is the second line abc.txt in the given path
\n") f.write("this is the last line")
First two lines will be copied in
a single line and third will be in
f.close( the second line
)
File Handling
⮚ Write mode always overrides the existing file and that is not good
practice for every scenario, if we want to add the content to the
file with out overriding the file then we should go with append
(“a”)
Ex:2
f=open("C:\\Anand\\abc.txt","w")
l=["Donkey \n","Monkey \n", "Rhino \n"]
Ex:3
f=open("C:\\Anand\\abc.txt","r") Output:
print(f.readline())
f.close() Hai, My Name is
Ex:4 Output:
f=open("C:\\Anand\\abc.txt","r"
Hai, My Name is I Teach Python &
) lines=f.readlines() Software Testing Donkey
for line in lines: Monkey
print(line, end=“ ”) Rhino
f.close()
File Handling
The with Statement:
⮚ Every time when ever we open a file, it should be closed at the
end, but if we want to close the file automatically with out using
close method at the end of using a file, then we can go with - with
statement
⮚ The advantage of with statement is it will take care of closing a
file, after completing all operations automatically even in the case
of exceptions also, and we are not required to close explicitly.
⮚ We can use with - statement to group file operation statements
within a block.
Syntax:
with open(‘filename’, ‘mode’) as f:
block of code for operations
File Handling
Ex:
Output:
os.path.isfile(fname ------------
) Enter File Name: abc.txt
import os
file with name abc.txt exists
fname = input("Enter File Name: hi how are you
this is a sample file
") if os.path.isfile(fname):
---------------------------------
print("file with
Enter File Name: gxx.txt
name",fname,"exists") file doesn't exists with name
f=open(fname,'r') gxx.txt
lcount=wcount=ccount=0
for line in f: Output:
lcount=lcount+1 ------------
ccount=ccount+len(line) Enter File Name: abc.txt
words=line.split() file with name abc.txt exists
wcount=wcount+len(words) no of lines: 2
no of words: 9
print("no of lines: ",lcount) no of chars: 36
print("no of words:
",wcount) print("no of chars:
",ccount)
else:
print("file doesn't exists with name ", fname)
File Handling
To change a directory:
import os
os.chdir('C:\\Users\\Veva
Das\\AppData\\Local\\Programs\\Python\\Python37-
32\\anand1')
cwd= os.getcwd()
print("current path: ", cwd)
To remove a
directory import os
cwd= os.rmdir('anand/hai')
print("dir hai deleted successfully")
Renaming a directory:
------------------------------
import os
cwd= os.rename('anand', 'python')
print("name changed successfully")
File Handling
To know contents of a directory:
---------------------------------------------
import os
cwd= os.listdir('C:\\Users\\Veva Das\\AppData\\Local\\Programs\\Python\\Python37-
32')
print(cwd)
Or
import os
cwd= os.listdir('.')
print(cwd)
Copying a file:
---------------------
import os
os.popen('copy argv_program.py file6.txt')
File Handling
To display the all contents of a directory:
-------------------------------------------------------
import os
forprint("dirpath:
dirpath, dirnames, filenames in os.walk('.'):
", dirpath)
print("dirnames: ", dirnames) Output:
print("filenames: ", ------------
filenames) print() List of all the files and sub files in
the current directory
File Handling
To get the information about the file:
--------------------------------------------------
-import os
print(os.stat('abc.txt') os.stat_result(st_mode=33206,
) st_ino=5910974511095568, st_dev=1620535598,
st_mode: Protection Bits st_nlink=1, st_uid=0, st_gid=0, st_size=37,
st_atime=1575541187,
st_ino: Inode number
st_mtime=1575605235, st_ctime=1575541187)
st_dev: Device
st_nlink: Number of Hard
Links st_uid: User id of Owner
st_gid: Group id of Owner
st_size: Size of File in Bytes
st_atime: Time of Most Recent Access
st_mtime: Time of Most Recent
Modification
st_ctime: Time of Most Recent Meta Data
Change
File Handling
Pickling & Unpickling:
---------------------------
⮚ The process of writing state of object to the file is called pickling
⮚ The process of reading state of an object from the file is called
unpickling
⮚ We can implement pickling and unpickling by using pickle module
of
Python.
⮚ pickle module contains dump() function to perform pickling.
pickle.dump(object,file)
⮚ pickle module contains load() function to perform unpickling
obj=pickle.load(file)
File Handling
.
File Handling
import pickle
class Employee:
def init (self,no,name,sal):
self.no=no
self.name=nam
e
self.sal=sal
def display(self):
withprint(self.no,"\t",self.name,"\t",self.sal
open("emp.txt",'wb') as f:
)
e=Employee(1,"Anand",20000) Output:
pickle.dump(e,f)
File with name emp.txt will be created with
with open("emp.txt",'rb') as f: the details.
obj=pickle.load(f)
print("printing employee printing employee details
details") obj.display() 1 Anand 20000
File Handling
Writing multiple employee objects to a file:
Thank
Q