[go: up one dir, main page]

0% found this document useful (0 votes)
32 views33 pages

11 23CS2301 B 6 24Unit-4Module

System application

Uploaded by

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

11 23CS2301 B 6 24Unit-4Module

System application

Uploaded by

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

IFETCE R 2023 ACADEMIC YEAR 2023-2024

IFET COLLEGE OF ENGINEERING


(An Autonomous Institution)
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE
(Common to CSE,CS,IT,ECE, AIDS & AIML)
SUB CODE: 23CS2301
SUB NAME: PYTHON PROGRAMMING
YEAR/SEM: I/II
UNIT-4 EXCEPTIONS AND FILE HANDLING
MODULES
Exceptions - Errors and Exceptions – Handling Exception – Built in and user defined Exceptions – Files-
Types- Operations. Activities: Program to perform word count, copy file, Voter’s age validation, Marks
range validation (0-100).

4.1 Exceptions:

 When a Python program meets an error, it stops the execution of the rest of the program. An error
in Python might be either an error in the syntax of an expression or a Python exception.
 An exception in Python is an incident that happens while executing a program that causes the
regular course of the program's commands to be disrupted. When a Python code comes across a
condition it can't handle, it raises an exception. An object in Python that describes an error is called
an exception.
 When a Python code throws an exception, it has two options: handle the exception immediately or
stop and quit.
 If an exception is not caught in Python, it will propagate up through the call stack until it either
reaches a higher-level exception handler or, if no such handler exists, it will cause the program to
terminate. This termination typically results in the Python interpreter displaying a traceback, which
includes information about where the exception occurred and what type of exception it was.
 In essence, if an exception is not caught, it will lead to an unhandled exception error, which can halt
the execution of the program abruptly. It's generally a good practice to catch exceptions where they
occur and handle them appropriately to prevent unexpected terminations and to gracefully manage
errors in the program.
 Exceptions versus Syntax Errors- When the interpreter identifies a statement that has an error,
syntax errors occur.
For Example in below Code
string = "Python Exceptions"
for s in string:
if (s != o:
print( s )

1
IFETCE R 2023 ACADEMIC YEAR 2023-2024

Output:
if (s != o:
^
Syntax Error:
invalid syntax
 The arrow in the output shows where the interpreter encountered a syntactic error. There was one
unclosed bracket in this case. Close it and rerun the program:

Code:
string = "Python Exceptions"
for s in string:
if (s != o):
print( s )
Output:
string = "Python Exceptions"
for s in string:
----> if (s != o):
print( s )
Name Error: name 'o' is not defined
 We encountered an exception error after executing this code. When syntactically valid Python code
produces an error, this is the kind of error that arises.
 The output's last line specified the name of the exception error code encountered. Instead of
displaying just "exception error", Python displays information about the sort of exception error that
occurred.
 It was a Name Error in this situation. Python includes several built-in exceptions. However, Python
offers the facility to construct custom exceptions.
4.2 ERRORS AND EXCEPTIONS:
 Errors and exceptions can lead to unexpected behavior or even stop a program from executing.
Python provides various functions and mechanisms to handle these issues and improve the
robustness of the code.
 An error is an issue in a program that prevents the program from completing its task. In
comparison, an exception is a condition that interrupts the normal flow of the program. Both errors
and exceptions are a type of runtime error, which means they occur during the execution of a
program.
 In simple words, the error is a critical issue that a normal application should not catch, while an
exception is a condition that a program should catch.
4.2.1 Errors:
 Errors or mistakes in a program are often referred to as bugs. They are almost always the fault of
the programmer.
 The error message has two parts:

2
IFETCE R 2023 ACADEMIC YEAR 2023-2024

a. The type of error before the colon, and


b. Specics about the error after the colon.
The process of finding and eliminating errors is called debugging. Errors can be classified into three
major groups:
1. Syntax errors
2. Runtime errors
3. Logical errors
1. Syntax errors
Syntax errors are mistakes in the use of the Python language, and are analogous to spelling
or grammar mistakes in a language like English: for example, the sentence Would you some
tea? does not make sense, it is missing a verb.
Common Python syntax errors include:
 Leaving out a keyword
 Putting a keyword in the wrong place
 Leaving out a symbol, such as a colon, comma or brackets
 Misspelling a keyword
 Incorrect indentation
 Empty block
Example :
# initialize the amount variable amount = 10000
# check that You are eligible to
# purchase Dsa Self Paced or not
if(amount>2999)
print("You are eligible to purchase Dsa Self Paced")
Output:

It returns a syntax error message because after the if statement a colon: is missing. We can fix this by
writing the correct syntax.
2. Runtime errors
If a program is syntactically correct – that is, free of syntax errors – it will be run by the
Python interpreter. However, the program may exit unexpectedly during execution if it encounters
a runtime error, a problem which was not detected when the program was parsed, but is only
revealed when a particular line is executed.(i.e) Runtime errors are also known as exceptions and
can occur for various reasons such as division by zero, attempting to access an index that is out of
range, or calling a function that does not exist.
Examples of Python runtime errors:
 Division by zero.

3
IFETCE R 2023 ACADEMIC YEAR 2023-2024

 Performing an operation on incompatible types.


 Using an identifier which has not been defined.
 Accessing a list element, dictionary value or object attribute which doesn’t exist.
 Trying to access a file which doesn’t exist.
The following program returns the runtime error if we perform operation on incompatible
data types –
# Input string
inputString = "hi"
# Input Number
inputNumber = 11
# Adding both integer and string values
print(inputString + inputNumber)
Output:
Traceback (most recent call last):
File "main.py", line 6, in <module>
print(inputString + inputNumber)
TypeError: must be str, not int
We can't add an integer to the string data type here, so we get a type error (runtime error).
3. Logical errors
Logical errors are the most difficult to fix. They occur when the program runs without
crashing, but produces an incorrect result. The error is caused by a mistake in the program’s logic.
Some examples of mistakes which lead to logical errors:
 Using the wrong variable name.
 Indenting a block to the wrong level.
 Using integer division instead of floating-point division.
 Getting operator precedence wrong.
 Making a mistake in a boolean expression.
 Off-by-one, and other numerical errors.
Here is an example of a logical error in Python:
def calculate_factorial(n):
result = 1
for i in range(1, n):
result = result * i
return result
print(calculate_factorial(5))
Output:
24
In this example, the function calculate_factorial() is designed to calculate the factorial of a given
number n. So when we run it, let's say for n = 5 , it runs without any problem but gives an output
of 24 instead of 120. The reason is a logical error in the code that causes it to produce incorrect

4
IFETCE R 2023 ACADEMIC YEAR 2023-2024

results. The for loop is iterating from 1to n-1instead of from 1 to n , causing the issue. This means
that the factorial is being calculated incorrectly, resulting in an incorrect output.
Solution
To fix this logical error, we need to change the range of the for loop to include the number n itself.
Here's the corrected code:
def calculate_factorial(n):
result = 1
for i in range(1, n+1):
result = result * i
return result
print(calculate_factorial(5))
Output:
120
4.3 HANDLING EXCEPTION
 Exception handling in python allows you to separate error-handling code from normal code.
 An exception is a Python object which represents an error.
 As with code comments, exceptions help 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 in one place and in one
manner.
 An exception is a convenient method for handling error messages.
 In Python, you can raise an exception in the program by using the raise exception method.
 Raising an exception helps you to break the current code execution and returns the exception
back to expection until it is handled.
 Processing exceptions for components that can’t handle them directly.
Exceptions can come in the following two exception classes:
 Checked exceptions. Also called compile-time exceptions, the compiler checks these exceptions
during the compilation process to confirm if the exception is being handled by the programmer.
If not, then a compilation error displays on the system. Checked exceptions include
SQLException and ClassNotFoundException.
 Unchecked exceptions. Also called runtime exceptions, these exceptions occur during program
execution. These exceptions are not checked at compile time, so the programmer is responsible
for handling these exceptions. Unchecked exceptions do not give compilation errors. Examples
of unchecked exceptions include NullPointerException and IllegalArgumentException.
4.3.1 Rules of Exceptions
Here are some essential rules of Python exception handling:
 Exceptions must be class objects
 For class exceptions, you can use a try statement with an except clause which mentions a
particular class.

5
IFETCE R 2023 ACADEMIC YEAR 2023-2024

 Even if a statement or expression is syntactically correct, it may display an error when an


attempt is made to execute it.
 Errors found during execution are called exceptions, and they are not unconditionally fatal.
4.3.2 Python Exception Handling Mechanism
Exception handling in python is managed by the following 3 keywords:
 try
 catch
 finally
 Throw or raise
i. Python Try Statement
 A try statement consists of the keyword try, a colon (:), and a group of code that may contain
exceptions. It contains a clause or clauses.
 If no exceptions arise during the try statement’s execution, the interpreter ignores the try
statement’s specified exception handlers.
 A try suite expires if an exception occurs within it, and program control then passes to the
matching except for the handler that came after the try suite.
 you can suppress exceptions by using a try-except block without specifying any particular
exception to catch. This essentially catches any exception that occurs within the try block and
prevents it from propagating further up the call stack.
 However, it's generally considered bad practice to suppress exceptions without handling them
or at least logging them.
 Suppressing exceptions indiscriminately can make debugging difficult and hide potential issues
in your code. It's usually better to catch specific exceptions that you expect and handle them
appropriately, while allowing unexpected exceptions to propagate up the call stack (or handling
them at a higher level).
Syntax:
try:
statement(s)
ii. The catch Statement
 The sort of exception that it is likely to catch is one that is taken one argument at a time by
catch blocks. These justifications might be anything from a particular sort of exception that
can be changed to a general category of exceptions.
Norms for the catch block:
 You can define a catch block by using the keyword catch
 The catch Exception parameter is always enclosed in parentheses
 It always represents the type of exception that the catch block handles.
 An exception handling code is written between two {} curly braces.
 You can place multiple catch block within a single try block.
 You can use a catch block only after the try block.
 All the catch block should be ordered from subclass to superclass exception.

6
IFETCE R 2023 ACADEMIC YEAR 2023-2024

Example:
try

}
catch (ArrayIndexOutOfBoundsException e) {

System.err.printin("Caught first " + e.getMessage()); } catch (IOException e) {


System.err.printin("Caught second " + e.getMessage());

}
iii. Finally Statement in Python
 Whether or not there is an exception, the finally block always runs. You may write a
block of code that comes after a try-catch block by using the final keyword.
 A clause is optional, to sum up. It aims to provide cleanup procedures that must be
followed in all circumstances.
try:
raise KeyboardInterrupt
finally:
print 'welcome, world!'
Output:
Welcome, world!
Keyboard Interrupt
Finally, the clause is executed before the try statement.
iv. Raise Statement in Python - The raise statement specifies an argument that initializes the exception
object. Here, a comma follows the exception name, and argument or tuple of the argument that
follows the comma.
Syntax:
raise [Exception [, args [, traceback]]]
In this syntax, the argument is optional, and at the time of execution, the exception
argument value is always none.
4.4 Built-In Exceptions:
 The built-in exceptions can be generated by the interpreter or built-in functions.
 There are several built-in exceptions in Python that are raised when errors occur. These
built-in exceptions can be viewed using the local() built-in functions as follows :
>>> locals()['__builtins__']
 This returns a dictionary of built-in exceptions, functions and attributes.
 In Python, all errors must be instances of BaseException class. The language provides a
set of built-in exceptions which you can use in built-in functions.
1. Base Classes:
 The following exceptions are used mostly as base classes for other exceptions.

7
IFETCE R 2023 ACADEMIC YEAR 2023-2024

 This is the base class for all built-in exceptions. It is not meant to be directly inherited by
user-defined classes. For, user-defined classes, Exception is used. This class is
responsible for creating a string representation of the exception using str() using the
arguments passed. An empty string is returned if there are no arguments.
 args : The args are the tuple of arguments given to the exception constructor.
 with_traceback(tb) : This method is usually used in exception handling. This method
sets tb as the new traceback for the exception and returns the exception object.
Code :
try:
...
except SomeException:
tb = sys.exc_info()[2]
raise OtherException(...).with_traceback(tb)
i. exceptionException - This is the base class for all built-in non-system-exiting
exceptions. All user-defined exceptions should also be derived
from this class.
ii. exceptionArithmeticError - This class is the base class for those built-in exceptions
that are raised for various arithmetic errors such as
 OverflowError
 ZeroDivisionError
 FloatingPointError
Example :
try:
a = 10/0
print (a)
print ("This statement is raising an arithmetic exception.")
else:
print ("Success.")
Output :
This statement is raising an arithmetic exception.
iii. exceptionBufferError:
This exception is raised when buffer related operations cannot be performed.
iv. exceptionLookupError:
This is the base class for those exceptions that are raised when a key or index used on a
mapping or sequence is invalid or not found. The exceptions raised are :
 KeyError
 IndexError
Example :
try:
a = [1, 2, 3]

8
IFETCE R 2023 ACADEMIC YEAR 2023-2024

print (a[3])
print ("Index out of bound error.")
else:
print ("Success")
Output : Index out of bound error.
2. CONCRETE EXCEPTIONS:
The following exceptions are the exceptions that are usually raised.
 The previously handled exception can serve as the implicit context for a new exception
that is raised inside of an exception handler.
 This can help with exception chaining and provide you more details about the error. You
can designate the original exception as the new exception’s cause by using the syntax
raise raise new_exc from original_exc.
i. exceptionAssertionError: - An AssertionError is raised when an assert statement fails.
Example :
assert False, 'The assertion failed'
Output :
Traceback (most recent call last):
File "exceptions_AssertionError.py", line 12, in
assert False, 'The assertion failed'
AssertionError: The assertion failed
ii. exception AttributeError: - An AttributeError is raised when an attribute reference or
assignment fails such as when a non-existent attribute is referenced.
Example :
class Attributes(object):
pass
object = Attributes()
print (object.attribute)
Output :
Traceback (most recent call last):
File "d912bae549a2b42953bc62da114ae7a7.py", line 5, in
print object.attribute
AttributeError: 'Attributes' object has no attribute 'attribute'
iii. exception EOFError: - An EOFError is raised when built-in functions like input() hits an end-
of-file condition (EOF) without reading any data. The file methods like readline() return an
empty string when they hit EOF.
Example :
while True:
data = input('Enter name : ')
print ('Hello ', data)
Output :

9
IFETCE R 2023 ACADEMIC YEAR 2023-2024

Enter Name :Hello Aditi


Enter Name :Traceback (most recent call last):
File "exceptions_EOFError.py", line 13, in
data = raw_input('Enter name :')
EOFError: EOF when reading a line
iv. exception FloatingPointError: - A FloatingPointError is raised when a floating point operation
fails. This exception is always defined, but can only be raised when Python is configured with
the–with-fpectl option, or the WANT_SIGFPE_HANDLER symbol is defined in the pyconfig.h
file.
Example :
import math
print (math.exp(1000))
Output :
Traceback (most recent call last):
File "", line 1, in
FloatingPointError: in math_1
v. exceptionGeneratorExit: - This exception directly inherits from BaseException instead of
Exception since it is technically not an error. A GeneratorExit exception is raised when a
generator or coroutine is closed.
Example :
def my_generator():
try:
for i in range(5):
print ('Yielding', i)
yield i
except GeneratorExit:
print ('Exiting early')
g = my_generator()
print (g.next())
g.close()
Output :
Yielding 0
0
Exiting early
vi. exception ImportError: - An ImportError is raised when the import statement is unable to load
a module or when the “from list” in from … import has a name that cannot be found.
Example :
import module_does_not_exist
Output :
Traceback (most recent call last):

10
IFETCE R 2023 ACADEMIC YEAR 2023-2024

File "exceptions_ImportError_nomodule.py", line 12, in


import module_does_not_exist
ImportError: No module named module_does_not_exist
Example :
from exceptions import Userexception
Output :
Traceback (most recent call last):
File "exceptions_ImportError_missingname.py", line 12, in
from exceptions import Userexception
ImportError: cannot import name Userexception
vii. exception ModuleNotFoundError: - This is the subclass of ImportError which is raised by
import when a module could not be found. It is also raised when None is found in sys.modules.
viii. exception IndexError: - An IndexError is raised when a sequence is referenced which is out of
range.

Example :
array = [ 0, 1, 2 ]
print (array[3])
Output :
Traceback (most recent call last):
File "exceptions_IndexError.py", line 13, in
print array[3]
IndexError: list index out of range
ix. exception KeyError: - A KeyError is raised when a mapping key is not found in the set of
existing keys.
Example :
array = { 'a':1, 'b':2 }
print (array['c'])
Output :
Traceback (most recent call last):
File "exceptions_KeyError.py", line 13, in
print array['c']
KeyError: 'c'
x. exception KeyboardInterrupt: - This error is raised when the user hits the interrupt key such as
Control-C or Delete.
Example :
try:
print ('Press Return or Ctrl-C:',)
Output :
Press Return or Ctrl-C: ^CCaught KeyboardInterrupt

11
IFETCE R 2023 ACADEMIC YEAR 2023-2024

xi. exception MemoryError: - This error is raised when an operation runs out of memory.
Example :
def fact(a):
factors = []
for i in range(1, a+1):
if a%i == 0:
factors.append(i)
return factors
num = 600851475143
print (fact(num))
Output :
Traceback (most recent call last):
File "4af5c316c749aff128df20714536b8f3.py", line 9, in
print fact(num)
File "4af5c316c749aff128df20714536b8f3.py", line 3, in fact
for i in range(1, a+1):
xii. MemoryErrorexception NameError: - This error is raised when a local or global name is not
found. For example, an unqualified variable name.
Example :
def func():
print ans
func()
Output :
Traceback (most recent call last):
File "cfba0a5196b05397e0a23b1b5b8c7e19.py", line 4, in
func()
File "cfba0a5196b05397e0a23b1b5b8c7e19.py", line 2, in func
print ans
NameError: global name 'ans' is not defined
xiii. exception NotImplementedError: - This exception is derived from RuntimeError. Abstract
methods in user defined classed should raise this exception when the derived classes override the
method.
Example :
class BaseClass(object):
"""Defines the interface"""
def __init__(self):
super(BaseClass, self).__init__()
def do_something(self):
"""The interface, not implemented"""
raise NotImplementedError(self.__class__.__name__ + '.do_something')

12
IFETCE R 2023 ACADEMIC YEAR 2023-2024

class SubClass(BaseClass):
"""Implements the interface"""
def do_something(self):
"""really does something"""
print (self.__class__.__name__ + ' doing something!')
SubClass().do_something()
BaseClass().do_something()
Output :
Traceback (most recent call last):
File "b32fc445850cbc23cd2f081ba1c1d60b.py", line 16, in
BaseClass().do_something()
File "b32fc445850cbc23cd2f081ba1c1d60b.py", line 7, in do_something
raise NotImplementedError(self.__class__.__name__ + '.do_something')
NotImplementedError: BaseClass.do_something
xiv. exception OSError([arg]): - The OSError exception is raised when a system function returns a
system-related error, including I/O failures such as “file not found” or “disk full” errors.
Example :
def func():
print (ans)
func()
Output :
Traceback (most recent call last):
File "442eccd7535a2704adbe372cb731fc0f.py", line 4, in
print i, os.ttyname(i)
OSError: [Errno 25] Inappropriate ioctl for device
xv. exception OverflowError: - The OverflowError is raised when the result of an arithmetic
operation is out of range. Integers raise MemoryError instead of OverflowError. OverflowError
is sometimes raised for integers that are outside a required range. Floating point operations are
not checked because of the lack of standardization of floating point exception handling in C.
Example :
import sys
print ('Regular integer: (maxint=%s)' % sys.maxint)
try:
i = sys.maxint * 3
print ('No overflow for ', type(i), 'i =', i)
except OverflowError, err:
print ('Overflowed at ', i, err)
print()
print ('Long integer:')
for i in range(0, 100, 10):

13
IFETCE R 2023 ACADEMIC YEAR 2023-2024

print ('%2d' % i, 2L ** i)
print()
print ('Floating point values:')
try:
f = 2.0**i
for i in range(100):
print (i, f)
f = f ** 2
except OverflowError, err:
print ('Overflowed after ', f, err)
Output :
Regular integer: (maxint=9223372036854775807)
No overflow for i = 27670116110564327421
Long integer:
01
10 1024
20 1048576
30 1073741824
40 1099511627776
50 1125899906842624
60 1152921504606846976
70 1180591620717411303424
80 1208925819614629174706176
90 1237940039285380274899124224
Floating point values:
0 1.23794003929e+27
1 1.53249554087e+54
2 2.34854258277e+108
3 5.5156522631e+216
Overflowed after 5.5156522631e+216 (34, 'Numerical result out of range')
xvi. exception RecursionError: - The RecursionError is derived from the RuntimeError. This
exception is raised when the interpreter detects that the maximum recursion depth is exceeded.
xvii. exception ReferenceError: - The ReferenceError is raised when a weak reference proxy is used
to access an attribute of the referent after the garbage collection.
Example :
import gc
import weakref
class Foo(object):
def __init__(self, name):
self.name = name

14
IFETCE R 2023 ACADEMIC YEAR 2023-2024

def __del__(self):
print ('(Deleting %s)' % self)
obj = Foo('obj')
p = weakref.proxy(obj)
print ('BEFORE:', p.name)
obj = None
print ('AFTER:', p.name)
Output :
BEFORE: obj
(Deleting )
AFTER:
Traceback (most recent call last):
File "49d0c29d8fe607b862c02f4e1cb6c756.py", line 17, in
print 'AFTER:', p.name
ReferenceError: weakly-referenced object no longer exists
xviii. exception RuntimeError:- The RuntimeError is raised when no other exception applies. It
returns a string indicating what precisely went wrong.
xix. exception StopIteration:- The StopIteration error is raised by built-in function next() and an
iterator‘s __next__() method to signal that all items are produced by the iterator.
Example :
Arr = [3, 1, 2]
i=iter(Arr)
print (i)
print (i.next())
print (i.next())
print (i.next())
print (i.next())
Output : 3
1
2
Traceback (most recent call last):
File "2136fa9a620e14f8436bb60d5395cc5b.py", line 8, in
print i.next()
StopIteration
xx. exception SyntaxError: -
The SyntaxError is raised when the parser encounters a syntax error. A syntax error may occur in
an import statement or while calling the built-in functions exec() or eval(), or when reading the
initial script or standard input.
Example :
try:

15
IFETCE R 2023 ACADEMIC YEAR 2023-2024

print (eval('geeks for geeks'))


except SyntaxError, err:
print ('Syntax error %s (%s-%s): %s' % \
(err.filename, err.lineno, err.offset, err.text))
print (err)
Output :
Syntax error (1-9): geeks for geeks
invalid syntax (, line 1)
xxi. exception SystemError: - The SystemError is raised when the interpreter finds an internal error.
The associated value is a string indicating what went wrong.
xxii. exception SystemExit: - The SystemExit is raised when sys.exit() function is called. A call to
sys.exit() is translated into an exception to execute clean-up handlers (finally clauses of try
statements) and to debug a script without running the risk of losing control.
xxiii. exception TypeError:- TypeError is raised when an operation or function is applied to an object
of inappropriate type. This exception returns a string giving details about the type mismatch.
Example :
arr = ('tuple', ) + 'string'
print (arr)
Output :
Traceback (most recent call last):
File "30238c120c0868eba7e13a06c0b1b1e4.py", line 1, in
arr = ('tuple', ) + 'string'
TypeError: can only concatenate tuple (not "str") to tuple
xxiv. exception UnboundLocalError : - UnboundLocalError is a subclass of NameError which is
raised when a reference is made to a local variable in a function or method, but no value has been
assigned to that variable.
Example :
def global_name_error():
print (unknown_global_name)
def unbound_local():
local_val = local_val + 1
print (local_val)
try:
global_name_error()
except NameError, err:
print ('Global name error:', err)
try:
unbound_local()
except UnboundLocalError, err:
print ('Local name error:', err)

16
IFETCE R 2023 ACADEMIC YEAR 2023-2024

Output :
Global name error: global name 'unknown_global_name' is not defined
Local name error: local variable 'local_val' referenced before assignment
xxv. exception UnicodeError: -This exception is a subclass of ValueError. UnicodeError is raised
when a Unicode-related encoding or decoding error occurs.
xxvi. exception ValueError: - A ValueError is raised when a built-in operation or function receives
an argument that has the right type but an invalid value.
Example :
print (int('a'))
Output :
Traceback (most recent call last):
File "44f00efda935715a3c5468d899080381.py", line 1, in
print int('a')
ValueError: invalid literal for int() with base 10: 'a'
xxvii. exception ZeroDivisionError: - A ZeroDivisionError is raised when the second argument of a
division or modulo operation is zero. This exception returns a string indicating the type of the
operands and the operation.
Example :
print (1/0)
Output : Traceback (most recent call last):
File "c31d9626b41e53d170a78eac7d98cb85.py", line 1, in
print 1/0
xxviii. ZeroDivisionError: - integer division or modulo by zero.
Example:
a = 10
b=0
print(a/b)
Output:
File "test.py", line 3, in <module>
print(a/b)
ZeroDivisionError: division by zero
The code in the earlier example can be updated to use an if statement to check if the
denominator is 0:
a = 10
b=0
if b == 0:
print("Cannot divide by zero")
else:
print(a/b)
Output: Cannot divide by zero . A try-except block can also be used to catch and handle this error

17
IFETCE R 2023 ACADEMIC YEAR 2023-2024

if the value of the denominator is not known beforehand:


try:
a = 10
b=0
print(a/b)
except ZeroDivisionError as e:
print("Error: Cannot divide by zero")
Surrounding the code in try-except blocks like the above allows the program to continue execution
after the exception is encountered:
Error: Cannot divide by zero
The Built-In Exception Types and the most typical conditions in which they occur given below

Exception Cause of Error

AssertionError When an assert statement fails, an error is raised.

ArithmeticError It specifies when an error in numerical calculations occurs.

AttributeError When attribute assignment or reference fails, this exception is raised.

EOFError When the input() method encounters a “end of file” circumstance, it throws an
error (EOF)

FloatingPointError When a floating-point calculation fails, this error is generated.

GeneratorExit When the close() method of a generator is called, this variable is raised.

ImportError When the imported module cannot be found, this exception is thrown.

IndexError When the index of a sequence is out of range, this value is raised.

KeyError When a key is not found in a dictionary, this error is raised.

18
IFETCE R 2023 ACADEMIC YEAR 2023-2024

KeyboardInterrupt When the user pushes Ctrl+C, Ctrl+Z, or Delete, this exception is thrown.

MemoryError When a program runs out of memory, an error is generated.

When a variable is not discovered in the local or global scope, this exception
NameError
is raised.

NotImplementedError Raised through abstract methods.

OSError When a system operation results in a system-related error, this flag is raised.

OverflowError When the result of a numerical calculation is too huge, an error is raised.

This Is an Exception When a weak reference object does not exist, an error is
ReferenceError
raised.

RuntimeError When an error does not fit into any of the other categories, it is raised.

StopIteration Raised by the next() function for the iterator that has no more items to return.

SyntaxError When a syntax problem occurs, the parser raises this exception.

IndentationError It raises an error when the indentation is incorrect.

TabError It raises an error when the indentation consists of tabs or spaces.

SystemError It is triggered when a system error occurs.

SystemExit The sys.exit() function raised this exception.

19
IFETCE R 2023 ACADEMIC YEAR 2023-2024

When a function or operation is applied to an object of the wrong type, this


TypeError
exception is raised.

When a reference to a local variable in a function or method is made but no


UnboundLocalError
value is bound to that variable, an exception is raised.

UnicodeError Unicode-related encoding or decoding problem occurs, this flag is raised.

UnicodeEncodeError When a Unicode-related problem occurs during encoding, this flag is raised.

UnicodeDecodeError When a Unicode-related error occurs while decoding, this flag is raised.

It defines an error. When there is an issue with a Unicode translation, this flag
UnicodeTranslateError
is raised.

When there is an incorrect value in a specified data type, this exception is


ValueError
raised.

ZeroDivisionError When the second operator in a division is zero, an error is raised.

Table 4.1 The Built-In Exception Types And The Most Typical Conditions In Which They Occur.

4.4.1 USER DEFINED EXCEPTION HANDLINGS:


 As the name implies, user-defined exceptions are exceptions made by a user to address
particular scenarios in their code. By defining a new class that derives from the built-in
Exception class or one of its subclasses, programmers can create unique exceptions in
Python.
 While doing the coding and programming, it might happen that the code might go wrong at
some or the other places. In such a case, the python program throws an error or exception,
which sometimes may result in the complete end of the program execution there itself.
These situations can be handled by using the user defined exceptions and try-except
statements.
 Using this, we can define what should be done exactly when a particular error or exception
occurs or create new exceptions that we want to handle in our program.

20
IFETCE R 2023 ACADEMIC YEAR 2023-2024

Definition of user-defined exceptions


 User-defined exceptions are ones that the developer writes in their code to address particular
errors. These exceptions are defined by creating a new class that inherits from the Exception
class or one of its subclasses.
Syntax of Python User Defined Exception: - class yourUserDefinedExceptionError (Exception)
 And further, you should specify the body of your exception, like what your program should
exactly do when that exception occurs. Then, with the help of try-except statements used for
exception and error handling, you can use your user defined exception.
 We can use the error handling mechanism like try and except provided in python to use the
exceptions which we have defined and handle those errors or exceptions.
 In order to get the complete detail or to get additional information about the Exception in
python, you can execute the following command.
help (Exception).
Output:
The execution of the above command gives the output similar to the image given below:

21
IFETCE R 2023 ACADEMIC YEAR 2023-2024

Examples of Python User Defined Exception:


Example #1 - Let us create a small exception by creating a new class for our user defined exception. It is
necessary that out class should extend the base exception class. Our exception class name will be
MyUserDefinedError, and we will use the ty except to check the working of our exception. The except
statement will help to display the message containing the returned value from the exception.
Code:
# Sample example to demonstrate the working and creation of user defined exception in python
# It is necessary that MyUserDefinedError class should be derived from the main super class of the
Exception
class MyUserDefinedError(Exception):

# Initializer (Constructor) for the class


def __init__(self, value):

self.value = value
# This will help to display the message of the exception

22
IFETCE R 2023 ACADEMIC YEAR 2023-2024

def message(self):
return(repr(self.value))

try:
raise(MyUserDefinedError(9*8))

# returnedErrorMessage will store the value of the message or anything which will
be returned by the exception
except MyUserDefinedError as returnedErrorMessage:
print ('The occurrence of the new exception is identified : ', returnedErrorMessage.value)
The execution of the above program gives the following output showing the calculated value of 9 * 8
returned from the exception class, which we defined.
Output:

Example #2 - Let us consider one more example of a user-defined exception. In this example, we will try
to derive the error from the super class of Exception. This type of superclass exception is mostly used when
we have a single module that should handle many different types of errors. We will try to do this by using
this module to define the base class for our exceptions. Then, different subclasses will be created to define
each exception class for distinct possible errors that need to be handled.
Code:
# Class which is derived from the main base class of Exception is DerivedClassError class
class DerivedClassError(Exception):
# Even though DerivedClassError is derived from the main base class of exceptions,
# it will be used and considered as the base class for our user defined exception class
pass
class TransDerivedClassError(DerivedClassError):
# This transition will occur when the transition will try to
# perform the state which is actually not permitted to it
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
# message will store the value generated from the error
self.message = message
try:
raise(TransDerivedClassError(4,6*4,"Not Permitted"))
# DerivedClassError will store the value of the user defined exception
except TransDerivedClassError as DerivedClassError:
print('There is an occurrence of exception: ',DerivedClassError.message)

23
IFETCE R 2023 ACADEMIC YEAR 2023-2024

The execution of the above program gives the following output showing the message “Not Permitted”
returned from the exception class, which we defined.
Output:

Example #3 - We can even consider the standard predefined exceptions as the base class while creating our
new user defined exception. Let us consider one of the examples of that type. RuntimeError is raised when
the error which is occurred cannot be considered in any of the available categories of exceptions.
RuntimeError is the in-built exception in python. Therefore, we can consider this class as the base class for
our user-defined class instead of the main Exception class. The following program illustrates the usage of
the same.
Code:
# SampleError is derived from the RuntimeError instead of main base class of Exception
class SampleError(RuntimeError):
def __init__(self, arg):
self.args = arg
try:
raise SampleError("Exception")
except SampleError as message:
print (message.args)
The execution of the above program gives the following output and works in a similar way as it would
have in case if we must have extended the main Exception class instead of RuntimeError class as the
consideration of base class.
Output:

4.5 FILES:
 File is a named location on disk to store related information. It is used to permanently store data
in a non-volatile memory (e.g. hard disk).For example, main.py is a file that is always used to
store Python code.
 File handling in Python is a powerful and versatile tool that can be used to perform a wide
range of operations. Since, random access memory (RAM) is volatile which loses its data
when computer is turned off, we use files for future use of the data.
 In Python, there is no need for importing external library to read and write files. Python
provides an inbuilt function for creating, writing and reading files.
 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.

24
IFETCE R 2023 ACADEMIC YEAR 2023-2024

Advantages of File Handling in Python:


 Versatility: File handling in Python allows you to perform a wide range of operations, such as
creating, reading, writing, appending, renaming, and deleting files.
 Flexibility: File handling in Python is highly flexible, as it allows you to work with different
file types (e.g. text files, binary files, CSV files, etc.), and to perform different operations on
files (e.g. read, write, append, etc.).
 User–friendly: Python provides a user-friendly interface for file handling, making it easy to
create, read, and manipulate files.
 Cross-platform: Python file-handling functions work across different platforms (e.g.
Windows, Mac, Linux), allowing for seamless integration and compatibility.
Disadvantages of File Handling in Python:
 Error-prone: File handling operations in Python can be prone to errors, especially if the code
is not carefully written or if there are issues with the file system (e.g. file permissions, file
locks, etc.).
 Security risks: File handling in Python can also pose security risks, especially if the program
accepts user input that can be used to access or modify sensitive files on the system.
 Complexity: File handling in Python can be complex, especially when working with more
advanced file formats or operations. Careful attention must be paid to the code to ensure that
files are handled properly and securely.
 Performance: File handling operations in Python can be slower than other programming
languages, especially when dealing with large files or performing complex operations.
4.6 Types of Files:
In Python, a file is categorized as
1. Binary file
2. Text file
1. Binary files in Python- Binary files are those which store entire data in the form of bytes, i.e a
group of 8 bits each. While retrieving data from the binary file, the programmer can retrieve it
in the form of bytes. Most of the files that we see in our computer system are called binary files.
Example:
 Document files: .pdf, .doc, .xls etc.
 Image files: .png, .jpg, .gif, .bmp etc.
 Video files: .mp4, .3gp, .mkv, .avi etc.
 Audio files: .mp3, .wav, .mka, .aac etc.
 Database files: .mdb, .accde, .frm, .sqlite etc.
 Archive files: .zip, .rar, .iso, .7z etc.
 Executable files: .exe, .dll, .class etc.
All binary files follow a specific format. We can open some binary files in the normal text
Editor but we can’t read the content present inside the file.

25
IFETCE R 2023 ACADEMIC YEAR 2023-2024

 That’s because all the binary files will be encoded in the binary format, which can be
understood only by a computer or machine. For handling such binary files we need a specific
type of software to open it.
 For Example, You need Microsoft word software to open .doc binary files. Likewise, you
need a pdf reader software to open .pdf binary files and you need a photo editor software to
read the image files and so on.
2. Text files in Python- Text files don’t have any specific encoding and it can be opened in
normal text editor itself. Text files are those which store data in the form of characters or
strings.
Example:
 Web standards: html, XML, CSS, JSON etc.
 Source code: c, app, js, py, java etc.
 Documents: txt, tex, RTF etc.
 Tabular data: csv, tsv etc.
 Configuration: ini, cfg, reg etc.
4.7 File Operations:
 In Python, file operations are essential for reading and writing data to files, and they play a
crucial role in data manipulation, analysis, and storage.
 When working with large datasets in machine learning problems, working with files is a basic
necessity. Since Python is a majorly used language for data science, For performing file
operations, a file needs to be opened first.
 Then follows the necessary operations to be performed by the user on our file. After all the
desired operations are performed, the file needs to be closed. Closing a file is necessary as
it would save the changes made on our file from the current session.

Fig 4.1 Python File Operations


 you need to be proficient with the different file operations that Python offers are as follows.
 Open a file
 Read or write (perform operation)
 Close the file

26
IFETCE R 2023 ACADEMIC YEAR 2023-2024

List of File Operations in Python:


Method Description

Opens a file and returns a file object. The filename argument is a string that specifies
open(filename,
the name of the file to open, and the mode argument specifies the mode in which to
mode)
open the file (e.g. ‘r’ for read mode, ‘w’ for write mode, etc.).

Closes the file object. Any further operations on the file object will raise a
close()
ValueError. It’s a good practice to always close files after they have been opened.

Reads and returns a string from the file. If size is specified, at most size characters
read(size=-1)
will be read. If size is not specified or is negative, the entire file will be read.

Reads and returns a single line from the file. If size is specified, at
readline(size=-1) most size characters will be read from the line. If size is not specified or is negative,
the entire line will be read.

Reads and returns a list of lines from the file. If hint is specified, at most hint bytes
readlines(hint=-1)
will be read. If hint is not specified or is negative, all the lines will be read.

write(string) Writes the string to the file. Returns the number of characters written.

Writes a sequence of strings to the file. The sequence can be any iterable object (e.g. a
writelines(sequence)
list, a tuple, etc.).

Changes the file position to the given offset. The whence argument is optional and
seek(offset[, defaults to 0, which means the offset is relative to the beginning of the file. Other
whence]) values for whence are 1 (relative to the current position) and 2 (relative to the end of
the file).

tell() Returns the current file position.

Truncates the file to at most size bytes. If size is not specified, the entire file will be
truncate(size=None)
truncated.

Flushes the write buffer of the file. This is useful when writing to a file that is being
flush()
accessed by multiple processes or threads.

Table 4.2 File Operations in Python


1. Opening a File - Opening a file is the fundamental step in every file handling task. This makes
sense because, in any file explorer, we first open before performing any reading or writing
operations to it.
 Files in Python can be opened with a built-in open() function. Ideally, it takes two string
arguments:

27
IFETCE R 2023 ACADEMIC YEAR 2023-2024

 The file path including the file name and the extension we want to open, is to be passed
as a string
 The mode in which we want to open the file, to be passed as a string.Thus, the syntax for
opening a file would look like this:
1. open(“”, “”)- Indeed there are other arguments as well in the open() function which are
optional and are used as per the requirement of the user. Let’s look at an example for
opening a file. Suppose if we have a file named myfile.txt on our desktop, it can be opened
by:
open(“C:UsersRahulDesktopmyfile.txt”)
Unquestionably, if our current working directory of the Python file is the same as
our file (here desktop), there is no need to specify the full path. In such a case, our
open() function would look like:
2. open(“myfile.txt”) - For the ease of code implementation, let us consider our current
working directory the same as the location our text files .Python has a wide range of file
opening modes available by default. These modes specify in which mode our file needed to
be opened. Each file opening mode comes with its default functionality and one can select
the appropriate model based on the need. As discussed above, the file opening mode
argument is an important factor that decides whether we want to read, write or update the
contents of an existing file.
File Opening Modes in Python:
Mode Description Example

Read mode. Opens the file for reading (default mode). If the file doesn’t
r file = open('example.txt', 'r')
exist, an error will be raised.

Write mode. Opens the file for writing. If the file exists, it will be
w file = open('example.txt', 'w')
truncated. If the file doesn’t exist, it will be created.

Append mode. Opens the file for writing, but appends new data to the
a end of the file instead of overwriting existing data. If the file doesn’t file = open('example.txt', 'a')
exist, it will be created.

Exclusive creation mode. Opens the file for writing, but only if it doesn’t
x file = open('example.txt', 'x')
already exist. If the file exists, an error will be raised.

b Binary mode. Opens the file in binary mode instead of text mode. file = open('example.txt', 'rb')

t Text mode (default). Opens the file in text mode instead of binary mode. file = open('example.txt', 'rt')

+ Update mode. Opens the file for both reading and writing. file = open('example.txt', 'r+')

Table 4.3 File Opening Modes in Python:

28
IFETCE R 2023 ACADEMIC YEAR 2023-2024

 The modes discussed above are being used on a text file. To use these modes for a binary
file, we need to use a different combination of file opening mode arguments.
Using ‘b’ with any mode, For example, ‘ab’, ‘rb’, ‘wb’, ‘rb+’, the file opens in binary
mode. It is used for non-textual files like image, sound, executable (.exe) files.
Example: To open our file myfile.txt in b mode:
open("myfile.txt", "rb")
Opening a file is not enough. This open function needs to be stored into a variable as this will
be used later for writing & reading the file. Here we will assign a variable to our file:
file = open("myfile.txt", "r")
2. Reading a File Operation in Python- Now that we have opened a file, we can start performing
operations to it. In this section, we will look at the reading functionality of files using Python.
 Before start reading the file, as discussed, we must open the file in ‘r’ mode, since we are
going to read the contents of the file. Let us assume that our file myfile.txt already has
some textual data present in it.
file = open("myfile.txt", "r")
print(file.read())
On executing this code, we get:

 The .read() method to our variable file gives the content of the file as output. We can also
specify the number of characters we want to read at once.
file = open("myfile.txt", "r")
print(file.read(8))
On executing this code, we get:

 This will print the 8 characters from the point until the file has been read earlier.Since we
executed the open statement before the .read() method, the file is opened again and the
cursor is moved at the start point, i.e. index 0. Thus 8 characters are being read from the
start point.
 Let’s understand this with another example. Given our file named myfile.txt having some
content “Hello, how you all have been doing?”. After opening a file, if we
use print(file.read(6)), it will first give “Hello,” as output & if use print(file.read(8)), it
will start reading 8 characters file from the point where the first read function left off i.e. ”
how you”
file = open("myfile.txt", 'r')
print(file.read(6))
print(file.read(8))
On executing this code, we get:

29
IFETCE R 2023 ACADEMIC YEAR 2023-2024

 As a result, when all the characters of the file are being read & if we try to use
the .read() method again, it will give an empty string as output.
 The .readline() method prints each line from our file, every time we execute this function,
until the end of the file is reached. Let’s add some additional lines to our text file to
illustrate this example.
file = open("myfile.txt", 'r')
print(file.readline())
print(file.readline())
On executing this, we get:

 This will print the first two lines of our file, separated by a newline character.
 The .readlines() method always gives a list of all the lines of our file as list elements.
file = open("myfile.txt", 'r')
print(file.readlines())
On executing this we get:

 A major difference between the .read() method and the .readline() method
is, .read() method focuses on reading each character from a file while
the .readline() focuses on reading individual lines from a file.
3. Writing/Creating a File - Another useful operation widely used, after opening a file, is writing
into a file. Writing into a file in Python is easy but an attentive task. Writing into a file is typically
done by opening the file in write ‘w’ or append ‘a’ mode. Writing into a file can be done using
the .write() method to our file.
 Caution needed to be followed while using the ‘w’ write mode as it can erase existing
content present in the file.
 Let’s understand this with an example. If we want to add content to our existing file,
myfile.txt, first we need to open it in the ‘w’ write mode and use the .write() method on
our file.
 The content to be written into the file needs to be passed as a string. It’s a good practice to
add a newline character ‘n’ to add a line between sentences. This improves the readability
for the user and is also useful while using the .readline() and .readlines() methods to
distinguish between the lines.
file = open("myfile.txt", "w")
file.write("Hello Alln")
On executing this code, we get:

30
IFETCE R 2023 ACADEMIC YEAR 2023-2024

Here, on execution, the .write() method returns the number of characters written into the
file.
 While writing into a file, if the file opened in ‘w’ or ‘w+‘ mode does not exist, a new file
will be created in the same name in our present working directory.
Example:
file = open("file.txt", "w")
On executing this code, we get:

Fig 4.2 Output of File Creation

 Here, previously the file file.txt does not exist in the current working directory and later it
got created. If file.txt would have already existed, it will erase all the content and the file
will become empty.
 Another file mode used for writing to the file is the ‘a’ append mode. This creates a new
file if the specified file does not exist in the current working directory.
 Unlike ‘w’ mode, it does not remove the existing content from the file. Instead, it appends
or adds the new content at the end of the file. Writing in append mode can be done using
the .write() method.
Example: file = open("myfile.txt", "a"
file.write("I am using append moden")
On executing this code, we get:

This will append the new content at the end of existing into our specified file.
4. Closing a File in Python- At last, after opening and performing the reading, writing operations, it
is important to close the file. This is done using .close() method. Let’s understand this with an
Example:
file = open("myfile.txt", 'r')
print(file.read())
file.close()

It is always a good practice to close a file after performing desired operations to it. Thus makes
sure that all our changes have been saved to the file. In the later sections, where we will try to
rename and remove the files. To accomplish these tasks, we mu st close the files to permit
renaming and removing the files.

31
IFETCE R 2023 ACADEMIC YEAR 2023-2024

5. Cursor Positioning Methods - Python has a couple of essential methods for the positioning of the
cursor in our file. The methods are as follows:
i. The .seek() method - The .seek() method in Python is used to change the cursor to a specific
position.
file = open("myfile.txt", 'r')
file.seek(0)
file.close()
This will move our cursor to index position 0 & file reading will start from the start point
again.
ii. The .tell() method - The .tell() method in Python prints the current position of our cursor.
file = open("myfile.txt", 'r')
file.tell()
 This will give the position up to which file has been read.

 Since we have used the .seek(0) method previously to move the cursor at index position 0,
we got 0 as output for using the .tell() method.
iii. Truncating a File - Truncating a File is also possible in Python. By using
the .truncate() method, we can truncate the file up to the desired length. Let’s understand this
with an example:
file = open('myfile.txt', 'w')
file.truncate(20)
file.close()

 In this example, we truncated a file up to 20 bytes by passing 20 as an argument into


the .truncate() method. This reduced the file size of the file to 20 bytes. Reducing the file
size also reduces the contents of the file size.
 If we don’t specify the size parameter inside the .truncate() method, the file will get
truncated up to the current cursor position of the file.
 A point to note in the .truncate() method is, the file must be opened in write mode to
perform truncating task.
iv. Renaming a File - Renaming a file in Python can be done using the os Module and needed
to be imported to perform such tasks. The os module in Python has a vast collection of
methods to perform all the essential file management tasks in Python itself .To rename our
file, we will use the .rename() method from the os module. The .rename() method takes two
arguments:
 The current file name, passed as a string type.The renamed file name, to be passed as a
string type. Let’s understand this with an example.
import os

32
IFETCE R 2023 ACADEMIC YEAR 2023-2024

os.rename('myfile.txt', 'ourfile.txt')

Fig 4.3 Output for Renaming the File


 Here, ‘myfile.txt’ is our file’s current name and ‘ourfile.txt’ is the name we want to set.
 Since we are just renaming the file and not changing the content of the file, we do not need to
open it to perform the renaming task.
v. Deleting a File - We can remove the files from a directory using Python’s versatile os
module.The os module has a method .remove() which performs the task.
The .remove() method takes a single argument as string type which is our file name. Let’s
understated this with an example.
import os
os.remove('myfile.txt')
file = open('myfile.txt', 'r')
On executing this, we get:

Since we deleted this file, we cannot open this again and as a result, getting errors.

33

You might also like