0% found this document useful (0 votes)
193 views96 pages

Unit 3: Exceptions and Files

This document discusses files in Python. It defines a file as stored data on a computer that can be characterized by its filename and extension. Files can be text or binary. Text files store data as characters while binary files store entire data as bytes. The document outlines how to open, read, write, and close files in Python using functions like open(), read(), write(), and close(). It also discusses different file opening modes and using the with statement for automatic closing of files.

Uploaded by

Rudrik Bhatt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
193 views96 pages

Unit 3: Exceptions and Files

This document discusses files in Python. It defines a file as stored data on a computer that can be characterized by its filename and extension. Files can be text or binary. Text files store data as characters while binary files store entire data as bytes. The document outlines how to open, read, write, and close files in Python using functions like open(), read(), write(), and close(). It also discusses different file opening modes and using the with statement for automatic closing of files.

Uploaded by

Rudrik Bhatt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 96

UNIT 3

EXCEPTIONS AND FILES


Introduction to File

A file is an essential data item stored in one’s


computer. Each file can be characterized with its
filename & file extension. 

Python treats files differently as text or binary and this


is important. Each line of code includes a sequence of
characters and they form a text file. Each line of a file is
terminated with a special character, called the EOL or
End of Line characters like comma {,} or newline
character. It ends the current line and tells the
interpreter a new one has begun. 
Types of Files in Python
Text File
Binary File
1. Text File
Text file store the data in the form of characters.
Text file are used to store characters or strings.
Usually we can use text files to store character data 
eg: abc.txt 
2. Binary File
Binary file store entire data in the form of bytes.
Binary file can be used to store text, image, audio and
video.
Usually we can use binary files to store binary data like
images,video files, audio files etc
Opening a File
Before performing any  operation (like read or write) on
the file,first we have to open that file.For this we should
use Python's inbuilt function open() 
But at the time of open, we have to specify mode,which
represents the purpose of opening file.
We should use open() function to open a file. This function
accepts 'filename' and 'open mode' in which to open the
file.
file handler = open("file name", "open mode",  "buffering")
f = open(filename, mode) 
The File Opening Mode
w
To write data into file. If any data is already present in the file, it
would be deleted and the present data will be stored.
open an existing file for write operation. If the file already contains
some data then it will be overridden. If the specified file is not
already available then this mode will create that file. 
r
To read the data form the file. The file pointer is positioned at the
beginning of the file.
open an existing file for read operation. The file pointer is positioned
at the beginning  of the file.If the specified file does not exist then we
will get FileNotFoundError.This is default mode. 
a
To append data to the file. Appending means adding at the
end of existing data. The file pointer is placed at the end of the
file. If the file does not exist, it will create new for writing data.
open an existing file for append operation. It won't override
existing data.If the specified file is not already avaialble then
this mode will create a new file. 
w+
To write and read data a file. The previous data in the file will
be deleted.
To write and read data. It will override existing data. 
r+
To read and write data into the file. The previous data in the
file will not be deleted.The file pointer is placed at the
beginning of the file.
a+
To append and read data from the file.It wont override
existing data. 
To append and read of a file. The file pointer will be at
the end of the file if the file exists. If the file does not
exist, it creates a new file for reading and writing.
x
To open a file in exclusive creation mode for write
operation. If the file already exists then we will get
FileExistsError. 
Note : All the above modes are applicable for text files.
If the above modes suffixed with 'b' then these
represents for binary files.
Eg: rb,wb,ab,r+b,w+b,a+b,xb 
f = open("abc.txt","w")
The key function for working with files in Python is
the open() function.

The open() function takes two parameters; filename,


and mode.

To open a file for reading it is enough to specify the name of


the file:
f = open("demofile.txt")
The code above is the same as:
f = open("demofile.txt", "rt")
Because "r" for read, and "t" for text are the default values,
you do not need to specify them.
Here's few simple examples of how to open
a file in different modes

file1 = open("test.txt")
# equivalent to 'r' or 'rt‘

file1 = open("test.txt",'w')
# write in text mode

file1 = open("img.bmp",'r+b')
# read and write in binary mode
Reading Files in Python

After we open a file, we use the read() method


to read its contents. For example,

# open a file
file1 = open("test.txt", "r")
# read the file
read_content = file1.read()
print(read_content)
Closing Files in Python
When we are done with performing operations on
the file, we need to properly close the file.
Closing a file will free up the resources that were
tied with the file. It is done using
the close() method in Python. For example,

# open a file
file1 = open("test.txt", "r")
# read the file
read_content = file1.read() print(read_content)
# close the file
file1.close()
Use of with...open Syntax

In Python, we can use the with...open syntax to


automatically close the file. For example,

with open("test.txt", "r") as file1:


read_content = file1.read()
print(read_content)

Note: Since we don't have to worry about closing


the file, make a habit of using
the with...open syntax.
Writing to Files in Python

There are two things we need to remember


while writing to a file.
If we try to open a file that doesn't exist, a
new file is created.
If a file already exists, its content is erased,
and new content is added to the file.
In order to write into a file in Python, we need to
open it in write mode by
passing "w" inside open() as a second argument.
Suppose, we don't have a file named test2.txt.
Let's see what happens if we write contents to
the test2.txt file.
with open(test2.txt', 'w') as file2:
# write contents to the test2.txt file
file2.write('Programming is Fun.')
file2.write('Python for beginners')
Here, a new test2.txt file is created and this file will
have contents specified inside the write() method.
When you access a file on an operating system, a file path
is required. The file path is a string that represents the
location of a file. It’s broken up into three major parts:

1.Folder Path: the file folder location on the file system


where subsequent folders are separated by a forward
slash / (Unix) or backslash \ (Windows)

2.File Name: the actual name of the file

3.Extension: the end of the file path pre-pended with a


period (.) used to indicate the file type
A path is either relative or absolute. An absolute path
always contains the root element and the complete
directory list required to locate the file. For
example, /home/sally/statusReport is an absolute path.
All of the information needed to locate the file is
contained in the path string.

A relative path needs to be combined with another path


in order to access a file. For example, joe/foo is a
relative path. Without more information, a program
cannot reliably locate the joe/foo directory in the file
system.
To find an absolute path in Python you import
the os module then you can find the current
working directory using 
os.path.abspath("insert-file-name-here") in
your Python script.

to find the absolute path in Python


To get the absolute path in Python you write
the following code:
import os
os.path.abspath("src/examplefile.txt")
to find the relative path in Python
To get the relative path in Python you write the following
code:
import os
absolute_path = os.path.dirname(__file__)
relative_path = "src/lib“
full_path = os.path.join(absolute_path, relative_path)
First, you have to import the os module in Python so you can
run operating system functionalities in your code.
Then you create the variable absolute_path which fetches
the current directory relative to the root folder. This is the
full path to your working directory, in this
case, ~/home/projects/example-project/.

The advantage to getting the absolute path on your


operating system is that it makes it possible to run the script
on different systems on different working directories.
The relative_path variable is a string in which you
define the location of the folder that you want to
fetch relative to the working directory.
In this case, "src/lib".

Then we use the absolute_path and combine it


via join with the relative_path to get the full path to
the lib folder which results in:

/Users/dannysteenman/projects/example-project/
src/lib/
Manipulating Pathnames 

Here are some different examples used mentioned below −


Getting the main filename from the file path
Getting the directory name from the file path
Joining path components together
Expanding the User's Home Directory
Splitting the file extension from the file path
Getting the main filename from the file path
The following program returns the main file name from the input
file using the os.path.basename() function −
# importing os module
import os
# input path of the file
inputFilepath = 'C:/Users/cirus/Desktop/test.pdf'
# Printing the given input path
print("Give Input Path is:",inputFilepath)
# getting the last component(main file name )of the input file path
print("Base Name of the given path is :", os.path.basename(inputFilepath))
Getting the directory name from the file path
Use the os.path.dirname() function(returns the directory name
from the given file path) to get the directory/folder of the given
input file path by passing the input file path as an argument to it.

Example
The following program returns the directory name from the input
file path using the os.path.dirname() function −
import os
inputFilepath = 'C:/Users/cirus/Desktop/test.pdf'
print("Give Input Path is:",inputFilepath)
# getting the directory/folder path from the input file path using
dirname() function
print("Directory path of the given path is: ", os.path.dirname(inputFilepath))
Joining path components together
os.path.join() function
Python's os.path.join() function effectively joins one or
more path components. With the exception of the last
path component, this approach concatenates different
path components by placing exactly one directory
separator ('/') after each non-empty portion. A directory
separator ('/') is added at the end of the last path
component to be joined is empty.
All previously joined components are deleted if a path
component represents an absolute path, and joining
moves on from the absolute path component.
Example
The following program joins the given path components with
the base name using the os.path.join() function −
# importing os module
import os
# input path of the file
inputFilepath = 'C:/Users/cirus/Desktop/kohli.pdf‘
# Printing the given input path
print("Give Input Path is:",inputFilepath)
# joining the components to the main file name of
the input file path
print("Joining the given paths to input Path:\n",
os.path.join('tutorials', 'python',
os.path.basename(inputFilepath)))
Output
Give Input Path is: C:/Users/cirus/Desktop/kohli.pdf
Joining the given paths to input Path: tutorials/python/kohli.pdf
Splitting the file extension from file path:

os.path.splitext() function − Splits the file path name into a


pair root and extension. The root here is everything except
the file extension.
If the given file path has no extensions, then the extension is
empty. The given path will be ignored if it has a leading
period ('.').
Syntax
Below is the syntax of the function.
os.path.splitext(path)
Use the os.path.splitext() function to split the file path and
file extension from the input file path.
Example
The following program splits the main file path and file
extension from the input file path using the os.path.splitext()
function −

import os
# input path of the file
inputFilepath ='C:/Users/cirus/Desktop/tutorial.pdf'
# Printing the given input path
print("Give Input Path is:",inputFilepath)
# splitting the file path and file extension from the input file
path
# using the splitext() function
print("Splitting the given path by extension :\n",os.path.splitext(inputFilepath))
Output

On execution, the above program will generate the following

output −

Give Input Path is: C:/Users/cirus/Desktop/tutorial.pdf


Splitting the given path by extension:
('C:/Users/cirus/Desktop/tutorial, '.pdf')
OS Path module

Following are some functions of OS Path module.


1. os.path.basename(path) : It is used to return the
basename of the file . This function basically return the
file name from the path given. 

import os
out = os.path.basename("/baz/foo")
print(out)
 
 os.path.dirname(path) : It is used to return the
directory name from the path given. This function
returns the name from the path except the path name. 

import os
out = os.path.dirname("/baz/foo")
print(out)
 
 os.path.isabs(path) : It specifies whether the path is
absolute or not. In Unix system absolute path means path
begins with the slash(‘/’) and in Windows that it begins
with a (back)slash after chopping off a potential drive
letter. 

import os
out = os.path.isabs("/baz/foo")
print(out)
os.path.isdir(path) : This function specifies whether
the path is existing directory or not.

import os
out = os.path.isdir("C:\\Users")
print(out)
 
 
os.path.isfile(path) : This function specifies whether
the path is existing file or not.

import os
out = os.path.isfile("C:\\Users\foo.csv")
print(out)
 
 
Getting file information

Because Python is a server-side language, it can access and


manipulate the file system just like any other language.
That means that you can use Python to get information
about files, such as their size, creation date, and more.

Get the file size


Now that you've imported the os module, you can use
the os.path.getsize() function to get the size of a file.
First define a file path to the file you want to get the size
of, and keep in mind that the path will be different
depending on your operating system.
file_path = "C:\\Users\\sabe\\text.txt"
# Windows

Then use the os.path.getsize() function to get the size of the


file:
import os
file_path = "/Users/sabe/text.txt“
file_size = os.path.getsize(file_path) print(file_size)
Get the file creation date
To get the creation date of a file, you can use
the os.path.getctime() function.
import os
file_path = "/Users/sabe/text.txt"
file_creation_date = os.path.getctime(file_path)
print(file_creation_date)

This returns the number of seconds since the epoch,


which is January 1, 1970.
Get the file modification date
To get the modification date of a file, you can use
the os.path.getmtime() function.

import os file_path = "/Users/sabe/text.txt"


file_modification_date = os.path.getmtime(file_path)
print(file_modification_date)
How to get the stats of a file
Another thing you can fetch about a file is its stats.
The os.stat() function returns a stat_result object that
contains a number of attributes about the file.

import os
file_path = "/Users/sabe/text.txt"
file_stats = os.stat(file_path)
print(file_stats)
These attributes include the file size, file owner id, file group
id, permissions, and more.
Traversing Directories and Processing Files
A common programming task is walking a directory
tree and processing files in the tree. Let’s explore
how the built-in Python function os.walk() can be
used to do this. os.walk() is used to generate
filename in a directory tree by walking the tree
either top-down or bottom-up. 

The following is an example that shows you how to


list all files and directories in a directory tree
using os.walk().
os.walk() defaults to traversing directories in a top-
down manner:
# Walking a directory tree and printing the names of the
directories and files
for dirpath, dirnames, files in os.walk('.'):
print(f'Found directory: {dirpath}')
for file_name in files:
print(file_name)

os.walk() returns three values on each iteration of the loop:


1. The name of the current folder
2. A list of folders in the current folder
3. A list of files in the current folder
To traverse the directory tree in a bottom-up manner, pass
in a topdown=False keyword argument to os.walk():

for dirpath, dirnames, files in os.walk('.', topdown=False):


print(f'Found directory: {dirpath}')
for file_name in files:
print(file_name)
Deleting Files in Python
To delete a single file,
use pathlib.Path.unlink(), os.remove(). or os.unlink().
os.remove() and os.unlink() are semantically identical. To
delete a file using os.remove(), do the following:

import os
data_file = 'C:\\Users\\vuyisile\\Desktop\\Test\\data.txt'
os.remove(data_file)
Example:
# Open function to open the file "MyFile1.txt" 
# (same directory) in append mode and
file1 = open("MyFile1.txt","a")
  
# store its reference in the variable file1 
# and "MyFile2.txt" in D:\Text in file2
file2 = open(r"D:\Text\MyFile2.txt","w+")

Example :
# Opening and Closing a file "MyFile.txt"
# for object name file1.
file1 = open("MyFile.txt","a")
file1.close()
# Program to show various ways to read and
# write data in a file.
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"] 
  
# \n is placed to indicate EOL (End of Line)
file1.write("Hello \n")
file1.writelines(L)
file1.close() #to change file access modes
  
file1 = open("myfile.txt","r+") 
  
print("Output of Read function is ")
print(file1.read())
print()
  
# seek(n) takes the file handle to the nth
# bite from the beginning.
file1.seek(0) 
  
print( "Output of Readline function is ")
print(file1.readline()) 
print()
  
file1.seek(0)
  
# To show difference between read and readline
print("Output of Read(9) function is ") 
print(file1.read(9))
print()  
file1.seek(0)
  
print("Output of Readline(9) function is ") 
print(file1.readline(9))
  
file1.seek(0)
# readlines function
print("Output of Readlines function is ") 
print(file1.readlines()) 
print()
file1.close()
Appending to a file

# Python program to illustrate


# Append vs write mode
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"] 
file1.writelines(L)
file1.close()
  
# Append-adds at last
file1 = open("myfile.txt","a")#append mode
file1.write("Today \n")
file1.close()
  
file1 = open("myfile.txt","r")
print("Output of Readlines after appending") 
print(file1.readlines())
print()
file1.close()
  
# Write-Overwrites
file1 = open("myfile.txt","w")#write mode
file1.write("Tomorrow \n")
file1.close()
file1 = open("myfile.txt","r")
print("Output of Readlines after writing") 
print(file1.readlines())
print()
file1.close()
What is the File Object?

Python file object provides methods and attributes to


access and manipulate files. Using file objects, we can
read or write any files.
Whenever we open a file to perform any operations on
it, Python returns a file object. To create a file object in
Python use the built-in functions, such
as open() and os.popen().
IOError exception is raised when a file object is misused,
or file operation fails for an I/O-related reason. For
example, when you try to write to a file when a file is
opened in read-only mode.

Types of File Object


In Python, there are two different categories of a file
object, which are listed below:
1. Text files
2. Binary files

All file types objects are defined in the io module.


Text files (TextIOWrapper)

The text file type is most common. Usually, we use text


files to store character data or storing information in plain
text with no special formatting beyond basic fonts and
font styles.
We open a text file using the open() function. For
example, open('test'.txt', 'r'). When we open a text file, it
returns a TextIOWrapper file object.
Example
file = open('test.txt', 'w')
print(type(file))
# Output: <class '_io.TextIOWrapper'>
Binary Files (BufferedReader and BufferedWriter)
Data is stored on a disk in the form of binary. For example, we
use binary files to store data like images or videos. Binary files
are a computer-readable form of storing data.
A program is needed to interpret the data in a binary file and
display it to the user. The binary files are also called buffered
files. This file type is used for reading and writing binary data.
Open the binary files using the open() function in binary mode.
For example, open('abc.txt', 'rb'). It opens the file to
read-only in binary mode. The file pointer exists at the
beginning of the file.
The open() function will return the BufferedReader when
we open the binary file for reading and
the BufferedWriter file object when we open a binary file
for writing.

Example
file = open('test.txt', 'rb') print(type(file))
# Output: <class '_io.BufferedReader'>
Writing to a file
There are two ways to write in a file.
1. write() : Inserts the string str1 in a single line in the
text file.
File_object.write(str1)

2. writelines() : For a list of string elements, each


string is inserted in the text file.Used to insert multiple
strings at a single time.
File_object.writelines(L) for L = [str1, str2, str3]
Reading from a file
There are three ways to read data from a text file.
1. read() : Returns the read bytes in form of a string.
Reads n bytes, if no n specified, reads the entire file.
File_object.read([n])

2. readline() : Reads a line of the file and returns in form


of a string.For specified n, reads at most n bytes.
However, does not reads more than one line, even if n
exceeds the length of the line.
File_object.readline([n])
3. readlines() : Reads all the lines and return them as each
line a string element in a list.

File_object.readlines()

Note: ‘\n’ is treated as a special character of two bytes 


# Program to show various ways to read and
# write data in a file.
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"] 
  
# \n is placed to indicate EOL (End of Line)
file1.write("Hello \n")
file1.writelines(L)
file1.close()
#to change file access modes
file1 = open("myfile.txt","r+") 
  
print("Output of Read function is ")
print(file1.read())
print()
  
# seek(n) takes the file handle to the nth
# bite from the beginning.
file1.seek(0) 
  
print( "Output of Readline function is ")
print(file1.readline()) 
print()
  
file1.seek(0)
# To show difference between read and readline
print("Output of Read(9) function is ") 
print(file1.read(9))
print()
  
file1.seek(0)
  
print("Output of Readline(9) function is ") 
print(file1.readline(9))
file1.seek(0)
# readlines function
print("Output of Readlines function is ") 
print(file1.readlines()) 
print()
file1.close()

Output of Read function is Output of Read(9) function is


Hello Hello
This is Delhi Th Output of Readline(9) function is
This is Paris Hello
This is London Output of Readlines function is
Output of Readline function is ['Hello \n', 'This is Delhi \n', 'This is
Hello Paris \n', 'This is London \n']
Working with Binary Files in Python

Python has tools for working with binary files. Binary files
use strings of type bytes. This means when reading binary
data from a file, an object of type bytes is returned.
The binary file is opened using the open() function,
whose mode parameter contains the character ‘b’. More
details about opening/closing binary files are described 
here.
Unlike text files, binary files do not convert characters to
the end of the string ‘\n’.
An example demonstrating the features of the
presentation of information in binary files.
# Open binary file for reading
f = open('myfile1.bin', 'rb')
# Get a string from binary file
d = f.read()
# Display this string.
# The output will be as a string of characters
print("d = ", d)
# d = b'\x80\x03]q\x00(K\x01\x88G@\x07\n=p\xa3\xd7\
ne.‘
# If print as a separate character, # then the character
code will be displayed - as an integer
print("d[5] = ", d[5]) # d[5] = 40
print("d[0] = ", d[0]) # d[0] = 128
# Use bin function for single character
print(bin(d[2])) # 0b1011101 f.close()
Output:
d = b'\x80\x03]q\x00(K\x01\x88G@\x07\n=p\xa3\xd7\ne.'
d[5] = 40
d[0] = 128
0b1011101

Based on the example above, the following conclusions can


be drawn:
a string of binary data is output as a string;
a single character (element) of binary data is represented
as 8-bit integers.
Introduction to Exceptions

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.
There are mainly three kinds of distinguishable errors
in Python: syntax errors, exceptions and logical errors.
Syntax errors are similar to grammar or spelling errors
in a Language. If there is such an error in your code,
Python cannot start to execute your code. You get a
clear error message stating what is wrong and what
needs to be fixed. Therefore, it is the easiest error type
you can fix.
Missing symbols (such as comma, bracket, colon),
misspelling a keyword, having incorrect indentation are
common syntax errors in Python.
Exceptions may occur in syntactically correct
code blocks at run time. When Python cannot
execute the requested action, it terminates the
code and raises an error message.

Trying to read from a file which does not exist,


performing operations with incompatible types of
variables, dividing a number by zero are
common exceptions that raise an error in Python.

We must eliminate the syntax errors to run our


Python code, while exceptions can be handled at
runtime.
Logical errors are the most difficult errors to fix
as they don’t crash your code and you don’t get
any error message.
If you have logical errors, your code does not run
as you expected.
Using incorrect variable names, code that is not
reflecting the algorithm logic properly, making
mistakes on boolean operators will result in logical
errors.
Exception Handling

The try and except block in Python is used to catch


and handle exceptions. Python executes code
following the try statement as a “normal” part of the
program. The code that follows the except statement
is the program’s response to any exceptions in the
preceding try clause.
Here, we have placed the code that might generate an
exception inside the try block. Every try block is
followed by an except block.
When an exception occurs, it is caught by
the except block. The except block cannot be used
without the try block.
try:
numerator = 10
denominator = 0
result = numerator/denominator print(result)
except:
print("Error: Denominator cannot be 0.")
# Output: Error: Denominator cannot be 0.
Catching Specific Exceptions in Python
For each try block, there can be zero or more except blocks.
Multiple except blocks allow us to handle each exception
differently.
The argument type of each except block indicates the type
of exception that can be handled by it. For example,

try:
even_numbers = [2,4,6,8]
print(even_numbers[5])
except ZeroDivisionError:
print("Denominator cannot be 0.")
except IndexError:
print("Index Out of Bound.")
# Output: Index Out of Bound
 try with else clause
In some situations, we might want to run a certain block
of code if the code block inside try runs without any
errors.
For these cases, you can use the optional else keyword
with the try statement.
# program to print the reciprocal of even numbers
try:
num = int(input("Enter a number: "))
assert num % 2 == 0
except:
print("Not an even number!")
else:
reciprocal = 1/num print(reciprocal)
try...finally
In Python, the finally block is always executed no matter
whether there is an exception or not.
The finally block is optional. And, for each try block,
there can be only one finally block.
try:
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
finally:
print("This is finally block.“)
The example below accepts two numbers from the user and performs
their division. It demonstrates the uses of else and finally blocks.
try:
print('try block')
x=int(input('Enter a number: '))
y=int(input('Enter another number: '))
z=x/y
except ZeroDivisionError:
print("except ZeroDivisionError block")
print("Division by 0 not accepted")
else:
print("else block")
print("Division = ", z)
finally:
print("finally block")
x=0
y=0
print ("Out of try, except, else and finally blocks." )
Raise an Exception
Python also provides the raise keyword to be used in the
context of exception handling. It causes an exception to be
generated explicitly. Built-in errors are raised implicitly.
However, a built-in or custom exception can be forced
during execution.
The following code accepts a number from the user. The
try block raises a ValueError exception if the number is
outside the allowed range.
try:
x=int(input('Enter a number upto 100: '))
if x > 100:
raise ValueError(x)
except ValueError:
print(x, "is out of allowed range")
else:
print(x, "is within the allowed range")

Here, the raised exception is a ValueError type.


However, you can define your custom exception type to
be raised. 
What is assertion 
Assertions are statements that assert or state a fact
confidently in your program. For example, while writing a
division function, you're confident the divisor shouldn't be
zero, you assert divisor is not equal to zero. Assertions are
simply boolean expressions that check if the conditions
return true or not.
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.
You can write a message to be written if the code returns
False, check the example below.
Example
Write a message if the condition is False:

x = "hello"

#if condition returns False, AssertionError is raised:


assert x == "goodbye", "x should be 'hello'"
Syntax – Assert in Python:
In Python, assert statements are being used in two
ways as mentioned below. 

1. assert <expression>, <error message>

2. assert <expression>
Example
Here is a function that converts a temperature from degrees Kelvin
to degrees Fahrenheit. Since zero degrees Kelvin is as cold as it
gets, the function bails out if it sees a negative temperature −

def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)

When the above code is executed, it produces the following result −


32.0 451 Traceback (most recent call last):
File "test.py", line 9, in <module>
print KelvinToFahrenheit(-5)
File "test.py", line 4, in KelvinToFahrenheit assert (Temperature >= 0),"Colder
than absolute zero!" AssertionError: Colder than absolute zero!
Example:

x = 10
assert x > 0
print('x is a positive number.')

Output
x is a positive number.
The assert statement can optionally include an error message
string, which gets displayed along with the AssertionError.
Consider the following assert statement with the error
message.
x=0
assert x > 0, 'Only positive numbers are allowed'
print('x is a positive number.')

Output
Traceback (most recent call last):
assert x > 0, 'Only positive numbers are allowed'
AssertionError: Only positive numbers are allowed
The following example uses the assert statement in the
function.

def square(x):
assert x>=0, 'Only positive numbers are allowed'
return x*x

n = square(2) # returns 4
n = square(-2) # raise an AssertionError
The AssertionError is also a built-in exception that can be
handled using try-except construct as shown below:

def square(x):
assert x>=0, 'Only positive numbers are allowed'
return x*x

try:
square(-2)
except AssertionError as msg:
print(msg)
Defining new exceptions :

To create a custom exception class, you define a class


 that inherits from the built-in Exception class or one of its
subclasses such as ValueError class:
The following example defines a CustomException class
that inherits from the Exception class:

class CustomException(Exception):
""" my custom exception class """
Example: 

class CustomError(Exception):
pass

raise CustomError("Example of Custom Exceptions in Python")

Output: CustomError:
Example of Custom Exceptions in Python
The Python Exception Class Hierarchy

BaseException
Exception
ArithmeticError
FloatingPointError
OverflowError
ZeroDivisionError
AssertionError
AttributeError
BufferError
EOFError
ImportError
ModuleNotFoundError
LookupError
IndexError
KeyError
MemoryError
NameError
UnboundLocalError
OSError
BlockingIOError
ChildProcessError
ConnectionError
BrokenPipeError
ConnectionAbortedErro
r
ConnectionRefusedErro
r
ConnectionResetError
FileExistsError
FileNotFoundError
InterruptedError
IsADirectoryError
NotADirectoryError
PermissionError
ProcessLookupError
TimeoutError
ReferenceError
RuntimeError
NotImplementedError
RecursionError
StopIteration
StopAsyncIteration
SyntaxError
IndentationError
TabError
SystemError
TypeError
ValueError
UnicodeError
UnicodeDecodeError
UnicodeEncodeError
UnicodeTranslateError
Warning
BytesWarning
DeprecationWarning
FutureWarning
ImportWarning
PendingDeprecationWa
rning
ResourceWarning
RuntimeWarning
SyntaxWarning
UnicodeWarning
UserWarning
GeneratorExit
KeyboardInterrupt
SystemExit
UNIT -3
COMPLETED

You might also like