Unit - 2

You might also like

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

Unit – 2

Chapter – 1 (Files)

Topic – File objects


 A file object in Python is an object that represents a file on your
computer's storage system.
 It allows you to interact with files, reading from them, writing to them,
and performing various file operations.
 File objects are an essential part of file I/O (Input/Output) in Python, and
they are created using the open() function.
Here's a basic overview of file objects in Python:
 Opening a File: You create a file object by opening a file using the open()
function. This function takes two primary arguments: the file name (or
path) and the mode (read, write, append, etc.). The mode specifies how
you intend to interact with the file.
SYNTAX:
file = open('example.txt', 'r') # Opens 'example.txt' for reading ('r'
stands for read mode)
 Reading from a File: Once you have a file object, you can use methods
like read(), readline(), or readlines() to read the contents of the file.
1. read(): Reads the entire file as a single string.
2. readline(): Reads the next line in the file.
3. readlines(): Reads all lines into a list.
content = file.read() # Reads the entire file into a string
line = file.readline() # Reads a single line
lines = file.readlines() # Reads all lines into a list

 Writing to a File: To write to a file, you open it in write ('w') or append


('a') mode and use the write() method.
with open('output.txt', 'w') as file:
file.write("Hello, World!")

 Closing a File: It's important to close the file using the close() method
when you are done. This ensures that any pending data is written to the
file, and it frees up system resources.
file.close() # Close the file when you're done

 Context Managers: The with statement is commonly used when working


with file objects. It ensures that the file is automatically closed when you
exit the block.
with open('example.txt', 'r') as file:
content = file.read()
# File is automatically closed when you exit the 'with' block

 File Modes: File modes allow you to specify how you intend to interact
with the file. Common modes include 'r' for reading, 'w' for writing
(creates a new file or truncates an existing one), and 'a' for appending
(creates a new file or appends to an existing one). You can also use
modes like 'rb' and 'wb' for binary files.
 Error Handling: It's good practice to use error handling (e.g., try and
except blocks) to handle potential issues when working with files, like file
not found errors or permission issues.

Topic – File Build in Function


Python provides several built-in functions for working with files, in addition to
the methods available on file objects. These functions allow you to perform
various file-related operations. Here are some of the commonly used built-in
functions for file operations in Python:
1. open(file, mode='r', buffering=-1, encoding=None, errors=None,
newline=None, closefd=True, opener=None): The open() function is
used to open a file and create a file object. It takes various parameters,
including the file name (or path), mode (read, write, append, etc.), and
encoding (for text files). It returns a file object that you can use to
interact with the file.
file = open('example.txt', 'r')

2. fileinput.input(files=None, inplace=False, backup='', bufsize=0,


mode='r', openhook=None): The fileinput.input() function is used to
read lines from multiple files. It is often used in scripts that need to
process multiple input files.
import fileinput
for line in fileinput.input(['file1.txt', 'file2.txt']):
print(line, end='')

3. os.remove(path): The os.remove() function is used to delete a file at the


specified path.
import os
os.remove('file_to_delete.txt')

4. os.rename(src, dst): The os.rename() function is used to rename a file or


directory from the source name to the destination name.
import os
os.rename('old_name.txt', 'new_name.txt')

5. os.path.exists(path): The os.path.exists() function checks whether a file


or directory exists at the specified path and returns a boolean value.
import os
if os.path.exists('file_to_check.txt'):
print('File exists')
else:
print('File does not exist')

6. os.path.isfile(path): The os.path.isfile() function checks if the specified


path points to a regular file (not a directory) and returns a boolean value.
import os
if os.path.isfile('file_to_check.txt'):
print('It is a regular file')
else:
print('It is not a regular file')

7. os.path.isdir(path): The os.path.isdir() function checks if the specified


path points to a directory and returns a boolean value.
import os

if os.path.isdir('directory_to_check'):
print('It is a directory')
else:
print('It is not a directory')

8. os.path.join(path, *paths): The os.path.join() function is used to join one


or more path components intelligently to create a complete file path. It
takes care of platform-specific path separators.
import os
full_path = os.path.join('directory', 'subdirectory', 'file.txt')

9. os.path.splitext(path): The os.path.splitext() function splits a file path


into its root and extension and returns them as a tuple.
import os
root, ext = os.path.splitext('file.txt')

Topic – File Build in Methods


File objects in Python come with several built-in methods that allow you to
perform various operations on files. Here are some of the most commonly used
file methods:
 read(size=-1): Reads and returns the specified number of bytes from the
file. If size is not provided or is negative, it reads the entire file.
content = file.read() # Reads the entire file
partial_content = file.read(1024) # Reads the next 1024 bytes

 readline(size=-1): Reads and returns the next line from the file. If size is
specified, it reads up to that number of bytes.
line = file.readline() # Reads the next line
partial_line = file.readline(20) # Reads up to the next 20 bytes or until
the end of the line

 readlines(hint=-1): Reads and returns a list of lines from the file. If hint is
specified, it reads at most hint bytes, seeking the end of the line
lines = file.readlines() # Reads all lines into a list
partial_lines = file.readlines(100) # Reads lines up to the next 100
bytes or until the end of the line

 write(string): Writes the specified string to the file. This method is used
when the file is opened in write ('w') or append ('a') mode.
with open('output.txt', 'w') as file:
file.write("Hello, World!")

 writelines(lines): Writes a list of lines to the file. Each line in the list
should end with a newline character if necessary.
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open('output.txt', 'w') as file:
file.writelines(lines)

 close(): Closes the file, releasing system resources. It's important to close
the file explicitly when you are done with it.
File.close()

 seek(offset, whence=0): Moves the file pointer to a specified position in


the file. The offset is the number of bytes to move, and whence specifies
the reference point (0 for the beginning of the file, 1 for the current
position, and 2 for the end of the file).
file.seek(0) # Move to the beginning of the file
file.seek(20, 0) # Move to the 20th byte from the beginning

 tell(): Returns the current file pointer position


position = file.tell() # Get the current file pointer position

 flush(): Flushes the internal buffer to the file. This ensures that any data
you've written is actually saved to the file.
file.flush()

 truncate(size=None): Resizes the file to the specified size. If size is not


provided, it truncates the file at the current file pointer position. It's
typically used when the file is opened in write ('w') mode
file.truncate() # Truncate the file at the current position
file.truncate(1024) # Truncate the file to 1024 bytes in length
Topic – File Build in Attributes
In Python, file attributes refer to various properties or characteristics
associated with a file, such as its name, size, and permissions. You can access
and manipulate these attributes using the built-in os and os.path modules.
Here are some commonly used file attributes and how to work with them in
Python:
File Path and Name:
1. os.path.basename(path): Returns the base name of the file, i.e., the file
name without the directory path.
2. os.path.dirname(path): Returns the directory name of the file.
File Existence:
1. os.path.exists(path): Returns True if the file or directory at the given
path exists, and False otherwise.
File Size:
1. os.path.getsize(path): Returns the size of the file in bytes.
File Type:
1. os.path.isfile(path): Returns True if the path points to a regular file.
2. os.path.isdir(path): Returns True if the path points to a directory.
File Permissions:
1. os.access(path, mode): Checks if the file at the given path has the
specified mode of access (e.g., os.R_OK for read, os.W_OK for write,
os.X_OK for execute).
Example program to demonstrate the file attributes:

import os

path = "/path/to/your/file.txt"

if os.path.exists(path):
print(f"File name: {os.path.basename(path)}")
print(f"File size: {os.path.getsize(path)} bytes")

if os.path.isfile(path):
print("This is a regular file.")
elif os.path.isdir(path):
print("This is a directory.")

if os.access(path, os.R_OK):
print("The file is readable.")

print(f"Last modification time: {os.path.getmtime(path)}")


else:
print("File does not exist.")

Topic – Standard Files


 In Python, standard files, also known as standard I/O (input/output)
streams, are predefined streams for reading and writing data.
 These standard files are associated with the terminal or console, and
they are commonly used for interacting with the user and performing
basic input and output operations.
There are three standard files in Python:
 sys.stdin: This is the standard input stream. It is used for reading input
from the user or external sources. By default, it is associated with the
keyboard, so you can use functions like input() to read user input from
the terminal.
 sys.stdout: This is the standard output stream. It is used for writing text
or data to the screen or console. Functions like print() send their output
to this stream by default.
 sys.stderr: This is the standard error stream. It is used for writing error
messages or diagnostic information to the console. It's typically used to
distinguish error messages from regular output.
You can access these standard files through the sys module, which is part of the
Python standard library. To use them, you need to import the sys module at
the beginning of your script.

Topic – Command line arguments


 Command-line arguments in Python are parameters or values provided
to a Python script when it is executed from the command line.
 These arguments allow you to pass information to your script from the
terminal, making your script more versatile and adaptable to different
use cases.
 Command-line arguments are commonly used in various applications,
such as scripts, programs, and utilities, to modify their behavior or
specify input data.
 In Python, you can access command-line arguments using the sys.argv
list, which is provided by the sys module.
 sys.argv[0] contains the name of the script itself (e.g., "script.py"). The
actual arguments start from sys.argv[1]
 Command-line arguments are always passed as strings. If you need them
as integers or other types, you must convert them using functions like
int() or float().
 To improve the handling of command-line arguments, you might
consider using the argparse module, which provides more advanced
features for defining and parsing command-line arguments, including
help messages, optional arguments, and more complex argument
structures.
Topic – File System
 The file system in Python refers to the way Python interacts with the
operating system's file and directory structure.
 Python provides several built-in modules for performing various file
system operations, which include creating, reading, writing, deleting,
and manipulating files and directories.
 The primary modules for working with the file system in Python are os,
os.path, and shutil
Here's an overview of some common file system operations in Python:
1. File and Directory Manipulation:
o os module: This module provides functions for interacting with
the file system, such as creating and removing directories, listing
directory contents, and checking file existence and permissions.
Common functions include:
i. os.mkdir(directory): Create a new directory.
ii. os.rmdir(directory): Remove a directory.
iii. os.remove(file): Remove a file.
iv. os.rename(src, dst): Rename or move a file or directory.
v. os.listdir(directory): List the contents of a directory.
vi. os.path.exists(path): Check if a file or directory exists.
vii. os.path.isfile(path): Check if a path points to a regular file.
viii. os.path.isdir(path): Check if a path points to a directory.
o shutil module: This module provides higher-level file operations,
including copying, moving, and deleting files and directories.
Common functions include:
i. shutil.copy(src, dst): Copy a file or directory.
ii. shutil.move(src, dst): Move a file or directory.
iii. shutil.rmtree(directory): Remove a directory and its
contents.
2. File I/O:
o Python provides several ways to read and write files. The most
commonly used methods are using the built-in open() function
and the with statement. You can open a file for reading ('r'),
writing ('w'), appending ('a'), and more. Some common file I/O
operations include:
1. Reading: open(filename, 'r')
2. Writing: open(filename, 'w')
3. Appending: open(filename, 'a')
3. Path Manipulation:
o The os.path module provides functions for working with file and
directory paths in a platform-independent manner. This is
important because file paths may differ between operating
systems (e.g., Windows, Linux, macOS).
Common path-related functions include:
1. os.path.join(path1, path2): Join two paths together to
create a valid path.
2. os.path.abspath(path): Get the absolute path of a file or
directory.
3. os.path.dirname(path): Get the directory name of a path.
4. os.path.basename(path): Get the base name (filename)
from a path.

Topic – File Execution


File execution in Python refers to the process of running Python scripts or
programs stored in external files.
You can execute Python files by invoking the Python interpreter from the
command line or by running scripts from within a Python IDE or code editor.
Here how you can execute python files:
1. Command Line Execution:
o To execute a Python script from the command line, open a
terminal or command prompt, navigate to the directory containing
the Python script, and use the python command followed by the
script's filename.
For example:

python my_script.py

2. Interactive Python Shell:


o You can also run Python scripts interactively in a Python shell, such
as the standard Python shell (IDLE) or an IPython shell. To do this,
open the shell and use the execfile() or %run command followed
by the filename of the script:
Using execfile() in the standard Python shell:
execfile('my_script.py')

3. IDE or Code Editor Execution:


o Most integrated development environments (IDEs) and code
editors designed for Python, such as Visual Studio Code, PyCharm,
and Jupyter Notebook, allow you to execute Python files directly
from the editor. You can typically run scripts by clicking a "Run"
button or using keyboard shortcuts. Open your Python script in
the IDE or code editor. Use the provided execution options to run
the script.
4. Module Execution:
 You can also import Python files as modules and execute specific
functions or code blocks within them. To do this, use the import
statement to bring the script into your current Python session.

Topic – Persistent Storage Modules


Persistent storage modules in Python are libraries or tools that enable you to
work with different forms of data storage, such as databases, files, and key-
value stores, in a way that allows data to be saved and retrieved across
different program executions.
These modules help you manage and store data in a way that makes it
durable and accessible over time.
Here are some common persistent storage modules and tools in Python:
SQLite (sqlite3 module):
 SQLite is a lightweight, embedded relational database that is
included with Python.
 You can use the sqlite3 module to create, read, update, and delete
data stored in SQLite databases.
 SQLite databases are self-contained and can be stored as files,
making them a good choice for small to medium-sized
applications.
SQLAlchemy:
 SQLAlchemy is a powerful and flexible Object-Relational Mapping (ORM)
library that allows you to interact with various relational databases using
Python.
 It provides a high-level, Pythonic interface for working with databases
and is often used in web applications and larger database-driven
projects.
MongoDB (pymongo module):
 MongoDB is a NoSQL database, and you can use the pymongo module to
interact with MongoDB databases from Python.
 MongoDB is a document-based database, and pymongo allows you to
work with unstructured data.
File I/O:
 Python's built-in file I/O capabilities are often used for persistent storage.
You can read and write data to and from files in various formats,
including plain text, JSON, XML, and more.
 Python's open() function is used for working with files.
Shelve:
 The shelve module is a built-in Python module that provides a simple
way to persistently store data as key-value pairs in a file.
 It's useful for storing Python objects and retrieving them later.
Pickle:
 The pickle module is a built-in Python module that allows you to serialize
and deserialize Python objects.
 You can use it to save and load Python objects to and from files.

Topic – Related Modules


Related modules are those modules that are often used in conjunction with
working with files and file-related operations.
These modules provide additional functionality and features that complement
file handling in Python.
Some of the commonly used related modules for file operations in Python are:
 os and os.path:
o The os module and os.path module provide functions for
performing file system operations, including file and directory
manipulation, path manipulation, and checking file attributes.
 shutil:
o The shutil module provides a high-level interface for file
operations, including copying, moving, and deleting files and
directories. It complements the basic file I/O functions.
 io:
o The io module contains classes for working with file-like objects,
which can be useful for managing data streams or string-based file
operations.
 csv:
o The csv module provides functionality for reading and writing CSV
(Comma-Separated Values) files, which are commonly used for
storing structured data.
 io.BytesIO and io.StringIO:
o The io.BytesIO and io.StringIO classes allow you to work with in-
memory file-like objects. These can be used to read and write data
as if it were in a file, which is particularly useful for testing or for
working with data without writing it to disk

Write a py program to copy the contents from one file


to another file
def copy_file(source_file, destination_file):
try:
with open(source_file, 'rb') as source:
with open(destination_file, 'wb') as destination:
destination.write(source.read())
print(f'File copied from {source_file} to {destination_file}')
except FileNotFoundError:
print('One or both files not found.')
except Exception as e:
print(f'An error occurred: {str(e)}')

if __name__ == "__main__":
source_file = 'source.txt' # Replace with the path to your source file
destination_file = 'destination.txt' # Replace with the path to your
destination file

copy_file(source_file, destination_file)

Chapter – 2 (Exceptions)

Topic – Exceptions in python


Errors in python program
In general, we can classify errors in program into one of these three types
1. Compile time error
2. Runtime error
3. Logical error
What is compile time errors?
 These are syntactical errors found in the code due to which a program
fails to compile.
 For example forgetting a colon in the statement like if, while, for, def, etc
Will result in compile time error.
 Such errors are detected by python compiler and the line number along
with error description is displayed by the python compiler.

What is Run time errors?


 When PVM cannot execute the byte code it flags runtime error
 For example, insufficient memory to store something or inability of the P
V M to execute some statement come’s under runtime error.
 Runtime errors are not detected by the python compiler they are
detected by PVM only at runtime.

What is logical error?


 These errors depict flaws in the logic of the program, the programmer
might be using a wrong formula or the design of the program itself is
wrong.
 Logical errors are not detected either by python compiler or PVM.
 The programmer is solely responsible for them.
 For example: The programmer wants to calculate incremented salary of
the employee but he gets wrong output since he uses wrong formula.
What are exceptions in python
 An exception is a runtime error which can be handled by the
programmer that means if the programmer can guess an error in the
program and he can do something to eliminate the harm caused by that
error then it is called as an exception.
 If the programmer cannot do anything in case of an error, then it is
called as an error and not an exception.
 All exceptions are represented as classes in python the exception which
are already available in python are called as built in exceptions.
 The base class for all build in exception is “base exception class” from
“base exception class” the sub class “exception” is derived, from
exception class the subclasses “standard errors” and “warnings” are
derived.
 All errors or exceptions are defined as sub classes of stranded errors, an
error or exceptions should be compulsory handled otherwise the
program will not execute.
 Similarly, all warnings are derived as subclasses from warning class a
warning represents a caution and even though it is not handled the
program will execute so warnings can be neglected but errors cannot be
neglected.
 Just like the exception which are already available in python language a
programmer can also create his own exceptions called user defined
exception when the programmer wants to create his own exception, he
should derive his class from exception class and not from base exception
class.
Important classes available in exception hierarchy is as follows:
Some of the exceptions are given below:
 ZeroDivisionError: This exception is raised when a division or modulo
operation is performed with a divisor of zero.
a=5
b=0
try:
result = a / b
except ZeroDivisionError as e:
print(f"Error: {e}")

 TypeError: This exception is raised when an operation or function is


applied to an object of an inappropriate type.
a = "Hello"
b=5
try:
result = a + b
except TypeError as e:
print(f"Error: {e}")

 ValueError: This exception is raised when a function receives an


argument of the correct type but with an inappropriate value.
try:
num = int("hello")
except ValueError as e:
print(f"Error: {e}")

 NameError: This exception is raised when a local or global name is


not found.
try:
print(x)
except NameError as e:
print(f"Error: {e}")

 FileNotFoundError: This exception is raised when a file or directory is


requested but cannot be found.
try:
with open('nonexistent_file.txt', 'r') as file:
print(file.read())
except FileNotFoundError as e:
print(f"Error: {e}")

 IndexError: This exception is raised when a sequence is indexed with


a number outside the available range.
my_list = [1, 2, 3]
try:
print(my_list[5])
except IndexError as e:
print(f"Error: {e}")

Topic – Detecting and handling exception


In Python, exceptions are errors that disrupt the normal flow of the program.
It's essential to handle these exceptions properly to ensure that the program
executes smoothly even when unexpected issues occur.
Here's a guide to detecting and handling exceptions in Python:
1. Using Try and Except Blocks:
try:
# Code that might raise an exception
# ...
except SomeException:
# Code to handle the exception
# ...

 The try block is used to enclose the code that might raise an
exception.
 If an exception occurs in the try block, Python looks for an except
block that can handle that particular type of exception.
 You can specify the type of exception to be handled in the except
block. If the exception raised matches the type specified in the except
block, the code inside the except block is executed.
2. Handling Multiple Exceptions:
You can handle multiple exceptions using multiple except blocks or a
single except block with multiple exception types:
try:
# Code that might raise an exception
# ...
except (FirstException, SecondException):
# Code to handle the first or second exception
# ...
except ThirdException:
# Code to handle the third exception
# ...

3. Handling Exceptions with Else and Finally:


 else block: Executed when no exceptions are raised.
 finally block: Always executed, regardless of whether an exception
was raised or not. This block is often used for cleanup operations.
try:
# Code that might raise an exception
# ...
except SomeException:
# Code to handle the exception
# ...
else:
# Code that runs if no exceptions are raised
# ...
finally:
# Code that always runs, regardless of exceptions
# ...
A simple program to demonstrate to exception handling
def divide_numbers(a, b):
try:
result = a / b
print(f"The result of division is: {result}")
except ZeroDivisionError as e:
print(f"Error: {e}. Cannot divide by zero.")
finally:
print("This will execute for sure!!")

# Example 1: Division with valid numbers


divide_numbers(10, 2)

# Example 2: Division by zero


divide_numbers(5, 0)

Topic – Context Management


 Context management in Python refers to a programming pattern used
to manage resources and ensure their proper setup and cleanup.
 It's particularly useful for resources that need to be explicitly initialized
and released, such as file handles, network connections, and database
connections.
 The context management protocol allows for the use of the with
statement, which simplifies resource management and ensures that
resources are properly cleaned up, even in the event of exceptions or
errors.
 The with statement provides a way to bind and release context
managers in a convenient and reliable way. It automatically takes care
of the resource's setup and teardown.
 A context manager is an object that has the __enter__ and __exit__
methods defined.
 When a context manager is used in a with statement, it triggers the
__enter__ method at the beginning of the block and the __exit__
method at the end, ensuring proper resource management.
Here's an example of using the with statement for file handling:
with open('example.txt', 'r') as file:
data = file.read()
# Perform operations on the file

# The file is automatically closed after the block

 In this example, the open() function returns a file object that acts as a
context manager. The with statement ensures that the file is properly
closed after the block of code is executed, even if an exception occurs.
 Python's standard library provides the contextlib module, which
includes utilities for working with context managers. It also offers the
@contextmanager decorator, which can convert a generator function
into a context manager.
Topic – Exceptions as strings
o In Python, you can catch and handle exceptions as strings by using the
traceback module.
o This technique is helpful when you want to obtain detailed information
about an exception, including the traceback and the context in which it
occurred, and then handle it as a string for logging or other purposes.
Here's an example of how to catch and handle exceptions as strings:
import traceback
try:
a=5
b=0
result = a / b
except Exception as e:
error_message = traceback.format_exc()
print(f"An exception occurred: {error_message}")

o In this example, the traceback.format_exc() function is used to obtain


the traceback information as a string.
o The except block catches any exception that occurs within the try block
and stores the traceback information as a string in the error_message
variable
o Using the traceback module in this way allows you to handle exceptions
more gracefully and gain insights into the cause of the exceptions in
your Python code.
o However, it's important to use this technique judiciously, as it can
potentially expose sensitive information about your code.

Topic – Raising Exception


 In Python, you can raise exceptions using the raise statement to
interrupt the normal flow of a program when a certain condition is
met.
 This is particularly useful when you want to explicitly signal that an
error has occurred or that a specific situation is exceptional and needs
to be handled differently.
Raising Built-in Exceptions:
Here's an example of how to raise a built-in exception:
x = -1

if x < 0:
raise ValueError("x cannot be negative.")

In this example, the ValueError is raised with a custom error message if the
value of x is negative.
Raising Custom Exceptions:
You can also create custom exceptions by subclassing the built-in Exception
class. This allows you to define your own exception types that suit your
application's specific needs.
class CustomError(Exception):
pass

def do_something():
raise CustomError("This is a custom error.")

try:
do_something()
except CustomError as e:
print(f"Custom error occurred: {e}")

In this example, the CustomError class is defined by inheriting from the built-in
Exception class.
The do_something() function raises this custom exception, and the except
block catches and handles it appropriately.

Topic – Assertions
 In Python, an assertion is a statement that you can use to test if a
condition is true or not.
 It is primarily used during the development and debugging phase to
identify and fix bugs in the code.
 The assert statement takes an expression and an optional message. If
the expression evaluates to false, the program will raise an
AssertionError with the specified message.
 If the expression is true, the program will continue its execution.
The basic syntax for an assert statement in Python is:
assert expression, message

 Here, 'expression' is the condition you want to test, and 'message' is an


optional argument that you can include to provide more information
about the assertion failure.
 The message is useful for debugging, as it helps you identify which
specific condition failed.
For example, consider the following code snippet:
x = 10
assert x == 5, "x should be 5"

If the value of x is not 5, the assert statement will raise an AssertionError with
the message "x should be 5".

Topic – Standard Exception


Standard exceptions are predefined built-in exceptions that provide a
structured way to handle errors and exceptional situations during the
execution of a program. Understanding these exceptions can help you
effectively handle errors and create robust programs.
1. Exception: This is the base class for all built-in exceptions. It captures all
types of errors and can be used to catch all exceptions.
2. AssertionError: This exception is raised when an assert statement fails. It
typically occurs when a condition specified in the assert statement is
false.
3. TypeError: This exception is raised when an operation or function is
applied to an object of an inappropriate type. For example, trying to add
a string and an integer would raise a TypeError.
4. ValueError: This exception is raised when a function receives an
argument of the correct type but an inappropriate value. Examples
include converting a string to an integer if the string does not represent a
valid integer.
5. IndexError: This exception is raised when a sequence subscript is out of
range. It occurs when trying to access an index that does not exist in a
list, tuple, or string.
6. KeyError: This exception is raised when a dictionary key is not found in
the set of existing keys. It occurs when trying to access a key that is not
present in the dictionary.
7. NameError: This exception is raised when a local or global name is not
found. It can occur when trying to access a variable that has not been
defined.
8. ZeroDivisionError: This exception is raised when the second operand of a
division or modulo operation is zero. It occurs when attempting to divide
a number by zero.
9. FileNotFoundError: This exception is raised when a file or directory is
requested but cannot be found. It occurs when trying to access a file that
does not exist or is misspelled.
10. ImportError: This exception is raised when a module, package, or object
cannot be imported. It occurs when the Python interpreter cannot locate
the module or if there's an issue with the module's contents.

Topic – Creating Exceptions


In Python, you can create custom exceptions to handle specific situations that
are not covered by the built-in exceptions.
Creating custom exceptions allows you to define your own error classes
accorrding to your application's needs. Here's how you can create a custom
exception in Python:
class CustomError(Exception):
def __init__(self, message):
# Call the base class constructor with the parameters it needs
super().__init__(message)
self.message = message

# Example usage of the custom exception


def check_value(x):
if x < 0:
raise CustomError("Value cannot be negative")
# Handling the custom exception
try:
check_value(-5)
except CustomError as e:
print("Custom error occurred:", e.message)

In this example:
 We define a custom exception class CustomError that inherits from the
base Exception class.
 The __init__ method is used to initialize the exception with a custom
error message.
 We define a function check_value that raises the CustomError if the
input value is negative.
 In the try block, we call the check_value function with a negative value.
If the value is negative, the CustomError is raised.
 We handle the CustomError in the except block and print the custom
error message.

Topic – Why Exceptions(now), Why exception at all


Exceptions in Python, serve several important purposes that contribute to the
overall robustness, maintainability, and reliability of the code. Here are some
key reasons why you should use exceptions in Python:
1. Error Handling: Exceptions provide a systematic way to handle errors
that may occur during the execution of a program. They allow you to
gracefully handle unexpected situations, such as invalid input, file not
found, or network connection issues, without causing the program to
crash.
2. Separation of Concerns: Exception handling allows you to separate the
normal flow of code from error-handling logic. This separation improves
the overall structure of the code and makes it easier to read and
maintain.
3. Debugging and Maintenance: When an exception occurs, it provides a
detailed stack trace that helps identify the specific location and cause of
the error. This information is crucial for debugging and maintaining the
code, as it helps developers quickly identify and resolve issues.
4. Predictable Behavior: By using exceptions, you can define specific error-
handling routines for different types of errors, ensuring predictable
behavior under various circumstances. This predictability enhances the
overall stability and reliability of your code.
5. Resource Management: Exceptions are useful for managing resources
such as files, database connections, and network resources. They allow
you to release resources safely, even in the presence of errors,
preventing memory leaks or resource exhaustion.
6. User Experience: When developing user-facing applications, proper
exception handling can provide a more user-friendly experience. Instead
of displaying cryptic error messages, you can present meaningful and
informative messages that guide users on how to resolve issues or take
appropriate actions.

Topic - Exceptions and the sys Module


In Python, exceptions are used to handle errors and other exceptional events
that occur during the execution of a program.
The sys module, provides access to some variables used or maintained by the
interpreter and to functions that interact strongly with the interpreter. It can
be used to manipulate the Python runtime environment.
Here is an overview of both concepts:
Exceptions:
 In Python, exceptions are raised when errors occur during the execution
of code. They disrupt the normal flow of the program and can be
caught and handled using the try, except, else, and finally blocks.
 Exceptions come in various types, such as TypeError, ValueError,
FileNotFoundError, and KeyError, among others. Python also allows you
to create custom exceptions
 You can use the raise statement to manually raise an exception when a
certain condition is met. This is helpful for handling specific scenarios
that may not be covered by built-in exceptions.
sys Module:
 The sys module provides access to some variables used or maintained
by the Python interpreter, such as system-specific parameters and
functions.
 It allows you to interact with the interpreter in various ways, such as
accessing the command-line arguments passed to the script,
manipulating the Python path, and interacting with the runtime
environment.
 Some commonly used functions in the sys module include sys.argv for
accessing command-line arguments, sys.path for accessing the module
search path, and sys.exit() for exiting the Python interpreter.

Topic – Related Modules


Sub Topic – Modules and files
In Python, modules and files play important roles in organizing and
structuring code. They allow you to break down your program into smaller,
manageable components and promote code reusability.
Here's an overview of modules and files in Python:
MODULES:
 Modules in Python are simply Python files with the extension .py. They
consist of Python code that can define functions, classes, and variables.
 Modules can be imported into other Python scripts or modules using the
import statement. This allows you to use the functionality defined in one
module within another module.
 Python also has a standard library of modules that provide a wide range
of functionalities, such as math, os, sys, and datetime. These modules
can be imported and used in your Python programs.
FILES:
 In Python, files are used for various operations related to reading,
writing, and manipulating data. You can open files using the open()
function, which returns a file object that can be used to read or write
data to the file.
 Python supports various file modes, such as read mode ('r'), write mode
('w'), append mode ('a'), and read-write mode ('r+'), among others.
These modes determine the operations you can perform on the file.
 File handling in Python includes operations such as reading from a file
using the read() or readline() method, writing to a file using the write()
method, and closing a file using the close() method.

Sub Topic – Namespaces


 In Python, a namespace is a mapping of names to objects. It's a system
that ensures that names are unique and can be used without any
conflict.
 Namespaces are an essential concept in Python that helps to avoid
naming conflicts and provides a way to organize and manage names in
a program.
There are different types of namespaces in Python, including the following:
 Local Namespace: This namespace includes local names inside a
function. It is created when a function is called and deleted when the
function returns or raises an exception.
 Global Namespace: This namespace includes names from various
modules that are currently imported and can be accessed throughout the
module.
 Built-in Namespace: This namespace includes built-in functions and built-
in exception names, such as print(), len(), and ValueError. These names
are available in all modules by default.
Here's a simple example that demonstrates the concept of namespaces in
Python:
# Example of namespaces in Python

# Global namespace
x = 10

def example_function():
# Local namespace
y=5
print(f'Local variable y: {y}')

example_function()
print(f'Global variable x: {x}')
# Using the built-in namespace
z = len([1, 2, 3, 4, 5])
print(f'Built-in function len(): {z}')

Sub Topic – Importing Modules


 In Python, modules are files that contain Python code. They allow you
to organize your code into reusable, structured components.
 When you want to use functions or classes defined in other modules,
you can import those modules into your current Python script.
 This allows you to access the functionality defined in those modules.
Here are some ways to import modules in Python:
1. Importing the Entire Module: You can import the entire module using
the import keyword.
For example:
import math

You can then access functions and classes from the math module using
dot notation, like math.sqrt() or math.sin().
2. Importing Specific Items: You can import specific functions or classes
from a module using the from...import statement.
For example:
from math import sqrt, sin

This allows you to use the sqrt() and sin() functions directly without
referencing the module name.
3. Importing with an Alias: You can import a module with an alias to
simplify the name.
For example:
import math as m

You can then use the alias to access functions from the math module,
like m.sqrt() or m.sin().
4. Importing All Items: You can import all items from a module using the
from...import * statement.
For example:
from math import *

This allows you to use all the functions defined in the math module,
However, this approach is generally discouraged because it can lead to
naming conflicts and make the code less readable.

Sub Topic – Importing Module Attributes


When you import a module in Python, you can access its attributes, such as
functions, classes, or variables, using dot notation. Here's how you can import
module attributes in Python:
1. Importing Specific Attributes: If you only need a few attributes from a
module, you can import them directly using the from...import statement.
For example:
from module_name import attribute_name

This allows you to use the specific attribute directly without referencing
the module name.
2. Importing All Attributes: If you want to import all attributes from a
module, you can use the from...import * statement.
For example:
from module_name import *

This method is generally discouraged because it can lead to naming


conflicts and make the code less readable. It's recommended to import
only the specific attributes you need from a module.
3. Importing with an Alias: You can import an attribute with an alias to
simplify the name.
For example:
from module_name import attribute_name as alias_name

This allows you to use the alias to reference the attribute instead of its
original name.

Sub Topic – Module Built in functions


Python provides several built-in functions that can be used with modules.
These functions can help you perform various operations related to modules.
These built-in functions are helpful for exploring and working with modules in
Python. They provide information about the attributes and functions within a
module, help you understand the module's documentation, and allow you to
update and reload modules during runtime.
Here are some of the important built-in functions for working with modules in
Python:
 dir(module): This function returns a sorted list of strings containing the
names defined by a module. It lists all the attributes and functions in
the module.
import math
print(dir(math))

 help(module): This function displays the documentation or help string of


the module. It provides information about the module and its contents.
import math
help(math)

 globals(): This function returns a dictionary representing the current


global symbol table. It can be used to access all the global variables
and functions in the current module.
print(globals())

 locals(): This function returns a dictionary representing the current local


symbol table. It can be used to access all the local variables and
functions within a specific scope, such as a function or a method.
print(locals())

 reload(module): This function reloads a previously imported module. It


is useful when you make changes to a module and want to see the
effects without restarting the interpreter.
import example_module
# make changes to example_module.py
import importlib
importlib.reload(example_module)
Sub Topic – Packages
 package is a way to structure Python's module namespace by using
"dotted module names."
 Packages are essentially directories that contain modules and an
additional __init__.py file, which can be used to indicate that the
directory should be treated as a package.
Here are some key points about packages in Python:
 Package Structure: A package typically has a hierarchical structure,
allowing you to organize a large number of modules into a single or
multiple levels of sub-packages. This structure helps in organizing and
maintaining large codebases.
 __init__.py File: The __init__.py file inside a package directory can be
used to execute package initialization code, and it is executed each time
the package is imported. It can also be used to control what symbols are
exported when from package import * is used.
 Sub-packages: Packages can contain other sub-packages, allowing for a
nested structure of modules. This helps in creating a logical and
organized structure for your project.
 Importing from Packages: You can import modules and sub-packages
from a package using the dot notation. For example, if you have a
package mypackage with a module mymodule, you can import it as
follows:
import mypackage.mymodule

 Relative Imports: Relative imports can be used within a package to


import modules or sub-packages located in the same package.
 Using Third-Party Packages: Python also has a rich ecosystem of third-
party packages and libraries, which can be easily installed using package
managers like pip.

Sub Topic – Other features of modules


1. Module Search Path: Python has a specific search path to locate
modules. The interpreter searches for modules in the directories listed in
the sys.path variable. You can modify the search path at runtime to
include additional directories.
2. Package Initialization: The __init__.py file in a package directory is
executed when the package is imported and can be used to perform
package initialization tasks.

3. Namespace Control: Modules and packages help in controlling the


namespace by encapsulating code within separate files. This aids in
preventing naming conflicts and organizes code logically.

4. Module Documentation: You can add documentation to modules using


docstrings (multi-line strings). This documentation can be accessed using
the help() function or tools like Sphinx for generating documentation.

5. Module as Scripts: Python modules can be run as scripts when executed


directly. The if __name__ == "__main__": construct is often used to
execute certain code only when the module is run as the main program.

6. Module Aliasing: You can provide aliases for modules or import specific
functions/classes from modules using aliases, making it easier to
reference them in your code.

You might also like