[go: up one dir, main page]

0% found this document useful (0 votes)
38 views39 pages

App Dev Using Python-Chapter 2

Chapter 2 discusses file handling in Python, covering types of files, file objects, and operations such as reading and writing. It explains built-in functions and methods for file manipulation, including standard files and command line arguments. The chapter emphasizes the importance of properly managing file objects and their attributes for effective data handling.

Uploaded by

Titus Martin
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)
38 views39 pages

App Dev Using Python-Chapter 2

Chapter 2 discusses file handling in Python, covering types of files, file objects, and operations such as reading and writing. It explains built-in functions and methods for file manipulation, including standard files and command line arguments. The chapter emphasizes the importance of properly managing file objects and their attributes for effective data handling.

Uploaded by

Titus Martin
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/ 39

CHAPTER – 2 FILES, EXCEPTIONS

Files:

Python File handling is an essential concept in Python's programming framework. It enables you to use your
Python code directly to create, read, write, and manage files. The ability to handle data storage, retrieval,
and modification in a flexible manner facilitates the management and processing of huge datasets.
Types of Files in Python

1. Text files: Typically ending in.txt, these files contain data in a readable format for humans
to access.
 Any text editor can be used to edit the plain text that they contain.
 Text files can be handled in Python utilizing modes like a for appending, w for writing, and r
for reading.
2. Binary Files: Unlike text files, binary files contain data like pictures, films, or computer programs
that are not readable by humans. .bin or.dat are typical extensions for them.
 Python handles similar to text files, binary files with the addition of a b suffix, such as rb for
reading binary files and wb for writing them.

Q) File Objects
A file object is an object in Python that gives access to files. These could be the on-disk files, meaning files
in the hard disk, or files present in other storage and communication devices. Once such a file object is
created, then we can use different methods like read() and write(), to read from
and write to the files, respectively.
Create a file object: We create a file object using the open() built-in function. In the "open()" function, we
also provide certain parameters or values within the parenthesis.
The file object can be closed using the close() method: After the file object has been created and
contents have been read or written to the file, we need to close the file object. The file object can be closed
using the close() method. If you don’t use with and also don’t call .close() then the file object remains
open until Python’s garbage collector eventually destroys it. This can take time. On some systems, too
many open files can cause errors
File Operations in Python

1. Opening Files in Python: To open a file using both relative and absolute paths. Different
file access modes for opening a file read and write mode.
Syntax:
file = open("filename", "mode")
Where, filename is the name of the file to open and mode is the mode in which the file is opened (e.g., 'r'
for reading, 'w' for writing, 'a' for appending).
There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
Example:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
Example:
f=open(“C:\users|download\file.txt”,”r”)
print(f.read())
f.close()
Using with statement
with open("C:/Users/IQAC/Downloads/file.txt","r") as f:
print(f.read())
"a" - Append - Opens a file for appending, creates the file if it does not exist
Example:
with open("C:/Users/IQAC/Downloads/file.txt","a") as f:
f.write("File has added with some extra content")
"w" - Write - Opens a file for writing, creates the file if it does not exist
Example:
with open("Example.txt","a") as f:
f.write("\nFile has added with some extra content")
"x" - Create - Creates the specified file, returns an error if the file exists
Example:
with open("C:/Users/IQAC/Downloads/filedemo.txt","x") as f:
f.write("This file is created using x mode")
Q. File Built-in Function [open()]
Python has a built-in function open() to open a file. Which accepts two arguments, file name and access
mode in which the file is accessed. The function returns a file object which can be used to perform
various operations like reading, writing, etc.
Syntax: Fileobject open (file-name, access-mode)
 file-name: It specifies the name of the file to be opened.
 access-mode: There are following access modes for opening a file:
Access Descrption
mode
“w” Write – opens a file writing, creates the file it doesnot exist

“r” Read-default value. opens a file for reading error if the file
doesnot exist
“a” Append-open a file for appending , creates the file if doesnot
exist
“x” Create-create the specified file, returns an error if the file exist

“w+” Open a file for updating, overwrite if the file exist

“r+” Open a file for updating doesn’t overwrite if the file exists

Q. File Built-in Methods


Python supports file handling and allows users to handle files i.e., to read and write files, along with
many other file handling options, to operate on files. For this, python provides following built-in
functions, those are
 close()
 read()
 readline()
 write()
 writelines()
 tell()
 seek()
Close(): The close() method used to close the currently opened file, after which no more writing or
Reading can be done. Python automatically closes a file when the reference object of a file is reassigned
to another file. It is a good practice to use the close() method to close a file.
Syntax: Fileobject.close()
Example: f.close()
Read(): The read () method is used to read the content from file. To read a file in Python, we must open
the file in reading mode.
Syntax: Fileobject.read([size])
Where 'size' specifies number of bytes to be read.
Example 1:
f=open(“C:\users|download\file.txt”,”r”)
print(f.read())
f.close()
Example 2:
f=open("Example.txt","r")
print(f.read(6))
Example 3:
with open("Example.txt","r") as f:
print(f.read(2))
readline(): Python facilitates us to read the file line by line by using a function readline(). The
readline() method reads the lines of the file from the beginning, i.e., if we use the readline() method
two times, then we can get the first two lines of the file.
Syntax :Fileobject.readline()
Example :
with open("Example.txt",”r”) as f:
print(f.readline())
readlines():
Example :
with open("Example.txt") as f:
print(f.readlines())
write(): The write () method is used to write the content into file. To write some text to a file, we need
to open the file using the open method with one of the following access modes.
 w: It will overwrite the file if any file exists. The file pointer point at the beginning
of the file in this mode.
Syntax: Fileobject.write(content)
 a: It will append the existing file. The file pointer point at the end of the file.
Example :
with open("Example.txt","a") as f:
f.write("\nexplaing the write function)")
writelines(): The writelines () method is used to write multiple lines of content into file. To write
some lines to a file
Syntax: Fileobject.writelines(list)
Here list This is the Sequence of the strings.
Ex:
lines = ["Apple\n", "Banana\n", "Cherry\n"]
with open("Example.txt", "w") as f:
f.writelines(lines)
print("File written successfully.")
Output
Apple
Banana
Cherry
Tell(): Returns the current position of the file pointer (cursor) in the file. The position is measured in
bytes from the beginning of the file. You can change the current file position with the seek() method.
Syntax:
file.tell()
Ex:
with open("Example.txt", "w") as f:
f.write("Hello")
print("Position after writing:", f.tell())
Output:
Position after writing: 5
(because "Hello" is 5 characters long)
seek(): The seek() method sets and returns the current file position in a file stream.
Syntax:
file.seek(offset)
EX:
f = open("new.txt", "r")
f.seek(1)
print(f.readline())

Q. File Built-in Attributes


File objects also have data attributes in addition to its methods. These attributes hold auxiliary data
related to the file object they belong to, such as the file name (file.name), the mode with which the file
was opened (file.mode), whether the file is closed (file.closed), and a flag indicating whether an
additional space character needs to be displayed before successive data items when using the print
statement (file.softspace).
File objects in Python, created typically by the open() built-in function, possess several attributes that
provide information about the file and its state. These attributes include:
file.closed:
A boolean value indicating whether the file has been closed (True) or is still open (False).
Example:
f = open("example.txt", "w")
print(f.closed) # False → file is still open

f.close()
print(f.closed) # True → file is closed
file.mode:
A string representing the access mode with which the file was opened (e.g., 'r' for read, 'w' for write, 'a' for
append, 'r+' for read and write).
Example:
# Open a file in write mode
f = open("example.txt", "w")
print(f.mode) # Output: 'w'
f.close()

# Open a file in read mode


f = open("example.txt", "r")
print(f.mode) # Output: 'r'
f.close()

# Open a file in read+write mode


f = open("example.txt", "r+")
print(f.mode) # Output: 'r+'
f.close()
file.name:
file.name returns the name (or path) of the file that was passed to the open() function..
f = open("example.txt", "w")
print(f.name) # Output: example.txt
f.close()

# With full path


f = open("C:/Users/IQAC/Desktop/test.txt", "r")
print(f.name) # Output: C:/Users/IQAC/Desktop/test.txt
f.close()
file.encoding:
The encoding used to convert Unicode strings to byte strings when writing to the file, and vice-versa
when reading. This attribute is present when the file is opened in text mode.
Example:
# Open a file in text mode (default is UTF-8 in most systems)
f = open("example.txt", "w")
print(f.encoding) # Output: UTF-8 (or system default)
f.close()

# Explicitly specify encoding


f = open("example.txt", "w", encoding="utf-16")
print(f.encoding) # Output: utf-16
f.close()
file.newlines:
When a file is opened in universal newline mode ('U' or 'r' with newline=None), this attribute reflects the
newline convention(s) encountered in the file (e.g., '\r', '\n', '\r\n', or a tuple of seen types).
Example:
f = open("example.txt", "r", newline=None)
data = f.read()
print(f.newlines)
f.close()

Q. Standard Files
Standard files in Python refer to the way Python handles input and output operations. Python treats
every input and output as a file, allowing for a consistent way to interact with various data streams.
When a Python program starts, three standard file objects are automatically opened and available for
use. They correspond to the standard input, output, and error streams of the operating system These
standard files are automatically available when a Python program runs.
 These streams provide a way for the program to interact with the external environment, such as the
user's console or other programs. The three standard files are:
Types of Standard Files
Standard Input (stdin)
This is the default input stream, typically connected to the user's keyboard. It allows the program to
receive input from the user. In Python, the input() function reads data from stdin.
 Represents the source of input for the program, typically the keyboard. Accessed using
sys.stdin.
 Used to read data provided by the user or another program.
 We need to import sys to use standard files like sys.stdin, sys.stdout, and sys.stderr in Python.
Example:
import sys
print("Enter your name:")
name=sys.stdin.readline()
print("Hello",name)
Standard Output (stdout)
This is the default output stream, usually connected to the user's console or terminal it allows the
program to display output to the user In Python, the print() function writes data to stdout
 Represents the destination for output from the program, typically the console
 Accessed using sys.stdout or the print() function.
Example:
import sys
sys.stdout.write("This is standard output.\n")
Standard Error (stderr)
 Used to display information to the user or another program Standard Error (stderr)
 Used to display error messages separately from normal output.
This is a separate output stream specifically for error messages and diagnostic information. It is also
typically connected to the user's console, but it can be redirected separately from stdout. In Python,
you can write to stderr using the sys.stderr object.
 Represents the destination for error messages and diagnostics.
 Accessed using sys.stderr
 Used to output error information separately from regular output.
Example:
import sys
sys.stderr.write("This is an error message!\n")

Q. Command Line Arguments


Python Command Line Arguments provides a convenient way to accept some information at the
command line while running the program. We usually pass these values along with the name of the
Python script.
Syntax: python program_name.py arg1 arg2 arg3...
 python: The keyword to invoke the Python interpreter.
 program_name.py: The name of your Python program file.
 arg1, arg2, arg3, and so on: The command-line arguments you want to pass to the
program. These arguments are separated by spaces.
Python provides various ways of dealing with these types of arguments. The three most common are
1. Using sys.argv
2. Using getopt module
3. Using argparse module

a) Using sys.argv:
The simplest way to handle command line arguments is by using the sys module's argy. The argy is a list
in Python, which contains the command-line-arguments pass argument to python script. The first
argument, argv[0], is always the script name itself.
Ex:
import sys
print("Script Name is:", sys.argv[0])
print("Arguments are:", sys.argv[1:])
Command Line Interface:
python generate random.py 1 100 5
Output:
Script Name is generate_random.py
Arguments are:[1,100.5]

b) Using getopt Module:


The getopt module is a more powerful tool for parsing command line arguments. It offers functions like
getopt() and gnu_getopt() that parse argument lists and return a tuple containing two lists. The first list
contains simple options, and the second list contains arguments that are associated with some option.
Here's how you can use it:
Ex
import sys import getopt
try:
opts, args getopt.getopt(sys.argv[1], "ho:", ["help", "output="])
except
getopt.GetoptError as err print(err) #
Process options
for opt, arg in opts:
if opt in("-h", "--help"):
print("Help Needed")
elif opt in ("-o", "-output"):
print("Arguments Passed with-o Option:-",arg)
Command Line Interface:
python CML.py-h
Output: Help Needed
Command Line Interface:
python CML.py -0 5 Output:
Arguments Passed with -o Option:-5

c) Using Argparse Module :


Argparse is the recommended command-line parsing module in Python's standard library. It's the in-
built solution for command line arguments. It creates a parser that reads command- line arguments,
where you can specify what options the command-line of your script should have. Ex
import argparse
parser =argparse.ArgumentParser() parser.add_argument("--
arguments", help="insert argg") args =parser.parse_args()
print(args.arguments.lower())
Command Line Interface:
python Lower py-arguments Hi,
Himanshu Output: hi,himanshu

Q. File System
In python, the file system contains the files and directories. To handle these files and directories python
supports "os" module. Python has the "os" module, which provides us with many useful methods to
work with directories (and files as well).
The os module provides us the methods that are involved in file processing operations and directory
processing like renaming, deleting, get current directory, changing directory etc.
Renaming the file rename():
The os module provides us the rename() method which is used to rename the specified file to a new
name.
Syntax: os.rename ("current-name", "new-name") Ex:
import os;
#rename file2.txt to file3.txt
os.rename("file2.txt","file3.txt")
Removing the file - remove():
The os module provides us the remove() method which is used to remove the specified file. Syntax:
os.remove("file-name")
Ex:
import os:
#deleting the file named
file3.txt os.remove("file3.txt")
Creating the new directory - mkdir()
The mkdir() method is used to create the directories in the current working directory
Syntax: os.mkdir("directory-name")
Ex: import os;
#creating a new directory with the name new
os.mkdir("dirnew")
Changing the current working directory-chdir()
The chdir() method is used to change the current working directory to a specified directory

Q. File Execution
Python is a well-known high-level programming language. The Python script is a file containing
Python-written code. The file containing Python script has the extension py' or can also have the
extension pyw if it is being run on a Windows 10 machine or various techniques for executing a
Python script...
Running Python Scripts in Terminal:
1. Open a Terminal: If you're using a Linux or macOS system, you can usually find a terminal
application in your applications or through a system search. Commonly used open terminal python
include the GNOME Terminal, Konsole, and macOS's Terminal.
On Windows, you can use the Command Prompt or PowerShell. You can find the Command
Prompt by searching for "cmd" or "Command Prompt" in the Start menu, while PowerShell can be
found similarly.
2. Navigate to Your Script's Directory: Use the ed (change directory) command to navigate to the
directory where your Python script is located. For example, if your script is in a folder called
"my_python_scripts," you can navigate to it like this while learning how to run a python script in
terminal
cd path/to/my_python_scripts
3. Run the Python Script: To run a Python script, use the Python command, followed by the name of
your script. For instance: python my_script.py
To run a python script in Linux
If you're using Linux, running a Python script in Python 3 is quite straightforward. First, open your
terminal. Navigate to the directory where your script is located using the ed command.
For example:
ed path/to/your/script
Once you're in the correct directory, type the following command: python3 script_name.py script
name.py can be replaced with your file name.
Running Python Scripts as Executables
You can also run Python scripts as executables on Unix-like systems. First, add the shebang line at the
top of your script:
#!/usr/bin/env python3

Then, with the following command, you can make the script executable: chmod +x script_name.py
Now simply, type the below command to run your script directly.
/script_name.py
How to Run Python on Windows
On Windows, Command Prompt can be used to run the Python scripts with ease. Just open Command
Prompt and use the cd command to go to your script's directory:
ed path\to\your script
Then, run your script with: python script_name.py
Ensure Python is added to your system PATH to run it from any directory Running Python command
line argument
Sometimes, you'll need to run scripts with command line arguments. Here's how you can do it. In
your script, you can handle arguments using the sys module:
import sys
print(sys.argv)
To run the script with arguments, use the terminal :python script_name.py arg1 arg2 Replace argl and
arg2 with your actual arguments.
Q. Exceptions in Python
In Python, an exception is an event that occurs during the execution of a program and disrupts the normal
flow of the program. It represents an error or an exception condition that the program encounters and
cannot handle by itself.
When an exception occurs, it is "raised" or "thrown" by the Python interpreter The exception then
propagates up the call stack, searching for an exception handler that can catch and handle the
exception. If no suitable exception handler is found, the program terminates, and an error message is
displayed.
Example:
n=10
try:
res=n/0
print(res)
except ZeroDivisionError:
print("cant divide by zero")
In this example, the code within the try block raises a ZeroDivisionError exception when attempting to
divide by zero. The exception is caught by the except block, and the specified error message is printed,
allowing the program to continue execution instead of abruptly terminating.
Different Types of Exceptions in Python:
1. SyntaxError: When the interpreter comes across a syntactic problem in the code, such as a misspelled
word, a missing colon, or an unbalanced pair of parentheses, this exception is raised.
2. TypeError: When an operation or function is done to an object of the incorrect type, such as
by adding a string to an integer, an exception is thrown.
3. NameError: When a variable or function name cannot be found in the current scope, the exception
NameError is thrown.
4. IndexError: This exception is thrown when a list, tuple, or other sequence type's index is outside of
bounds.
5. KeyError: When a key cannot be found in a dictionary, this exception is thrown.
6. ValueError: This exception is thrown when an invalid argument or input is passed to a function or
method. An example would be trying to convert a string to an integer when the string does not
represent a valid integer.
7. AttributeError: When an attribute or method is not present on an object, such as when attempting to
access a non-existent attribute of a class instance, the exception AttributeError is thrown.
8. IOError: This exception is thrown if an input/output error occurs during an I/O operation, such as
reading or writing to a file.
9. ZeroDivisionError: This exception is thrown whenever a division by zero is attempted.
10. ImportError: This exception is thrown whenever a module cannot be loaded or found by an
import statement.
Q. Types of Exceptions
There are two types of exceptions in Python.
1. Built-in Exceptions
2. User-Defined Exceptions
Built-in Python Exceptions
Built-in exceptions are the standard exceptions defined in Python. These exceptions are raised where the
program encounters an illegal operation like semantic errors.
These built-in exceptions are generated either by the interpreter or the built-in functions of Python
The interpreter returns a string indicating the error code and the related information whenever an
exception is raised.
Here is the list of default Python exceptions with descriptions:
1. Assertion Error: raised when the assert statement fails.
2. EOFError: raised when the input() function meets the end-of-file condition.
3. AttributeError: raised when the attribute assignment or reference fails.
4. TabError: raised when the indentations consist of inconsistent tabs or spaces.
5. ImportError: raised when importing the module fails.
6. IndexError: occurs when the index of a sequence is out of range
7. RuntimeError: occurs when an error does not fall into any category.
8. NameError: raised when a variable is not found in the local or global scope.
9. MemoryError: raised when programs run out of memory.
10. ValueError: occurs when the operation or function receives an argument with the
right type but the wrong value.
11. ZeroDivision Error: raised when you divide a value or variable with zero.
12. SyntaxError: raised by the parser when the Python syntax is wrong.
13. IndentationError: occurs when there is a wrong indentation.
14. SystemError: raised when the interpreter detects an internal error.
Ex: FileNotFoundError
This exception is raised when a file or directory is requested, but the specified file or directory
does not exist. When a file that should be read, accessed, or retrieved doesn't exist, Python throws
the FileNotFoundError exception.
#Python program for FileNotFoundError try:
with open(" myfile.txt") as f:
contents =f.read()
except FileNotFoundError as e:
print(" A file not found error occurred: ", e)
Output :A file not found error occurred. [Errno 2] No such file or directory: myfile.txt'
User-Defined Exceptions:
A user defined exception in Python is an exception that is constructed by the user or programmer to
represent a specific error condition or exceptional situation in a program. It is also known as a
custom exception.
Python offers a wide range of standard built-in exceptions to handle common errors. Sometimes,
there may be situations where built-in exceptions are not sufficient to handle the different exceptions
that occur in the application program.
In this situation, users may need to define their own custom exceptions to handle specific errors or to
add more context to error handling.
For example, if the user wants to withdraw greater than its balance from the ATM machine, it leads
to the exception. Any standard inbuilt exception cannot handle such a kind of exception.
In this case, the user can define its own custom exception that will occur when someone will want
to attempt to withdraw the amount greater than its balance. The exception handler in this case may
display a customize message that you cannot withdraw money greater than the account balance.

Syntax and Example

Handling Multiple User-Defined Exceptions: Python allows handling multiple user-defined


exceptions using multiple except blocks. By specifying different exception classes in each except block, we
can handle different types of exceptions separately. This enables developers to implement specific error-
handling logic based on the type of exception raised.
Benefits of Using User-Defined Exceptions
 Improved Code Readability: User-defined exceptions provide a clear indication of the specific error
conditions that can occur in the code. By using descriptive names for exceptions, developers can
easily understand the purpose and context of the exception.
Enhanced Error Handling: User-defined exceptions allow developers to handle errors in a more granular
and specific manner. By defining custom exception classes,
Handling Multiple User-Defined Exceptions: Python allows handling multiple user-defined
exceptions using multiple except blocks. By specifying different exception classes in each except block, we
can handle different types of exceptions separately. This enables developers to implement specific error-
handling logic based on the type of exception raised.
Benefits of Using User-Defined Exceptions
 Improved Code Readability: User-defined exceptions provide a clear indication of the specific
error conditions that can occur in the code. By using descriptive names for exceptions, developers
can easily understand the purpose and context of the exception.
 Enhanced Error Handling: User-defined exceptions allow developers to handle errors in a more
granular and specific manner. By defining custom exception classes, developers can catch and
handle different types of errors separately, leading to more effective error handling and debugging.
 Code Reusability: User-defined exceptions can be reused across multiple projects or modules,
promoting code reusability. By defining common exception classes, developers can ensure
consistent error-handling practices throughout their codebase.

Q. Exception Handling in Python (OR) Detecting and Handling Exceptions


Exceptions can be detected by incorporating them as part of a try statement. Any code suite of a try
statement will be monitored for exceptions.
Exception handling is a technique in Python for dealing with errors that occur during program
execution. It entails spotting potential error situations, responding appropriately to exceptions when
they arise, and identifying possible error conditions. Using the try and except keywords, Python
provides a structured approach to exception handling.

Try and Except Statement-Catching Exceptions: Try and except statements are used to catch and handle
exceptions in Python. Statements that can raise exceptions are wrapped inside the try block and the
statements that handle the exception are written inside except block.
Example:
a=[1,2, 3]
try:
print ("Second element = ", (a[1]))
print ("Fourth element = %d" %(a[3]))
except:
print ("An error occurred")
Output: Second element = 2
error occurred
In the above example, the statements that can cause the error are placed inside the try statement (second
print statement in our case). The second print statement tries to access the fourth element of the list which
is not there and this throws an exception. This exception is then caught by the except statement.
Catching Specific Exception
A try statement can have more than one except clause, to specify handlers for different exceptions. Please
note that at most one handler will be executed. For example, we can add IndexError in the above code.
Syntax:
try:
#statement(s) except IndexError:
#statement(s) except ValueError:
# statement(s)
Example:
def fun(a):
if a <4 :
b=a/(a-3)
print("Value of b =", b)
try:
fun(3)
fun(5)
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")
#Output: ZeroDivisionError Occurred and Handled
Try with Else Clause: In Python, you can also use the else clause on the try-except block which must be
present after all the except clauses. The code enters the else block only if the try clause does not raise an
exception.
Example:
def AbyB(a, b):
try:
c=((a+b)/(a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)

Output: -5.0 a/b result in 0


Finally Keyword in Python: Python provides a keyword finally, which is always executed after the try
and except blocks. The final block always executes after the normal termination of the try block or after
the try block terminates due to some exception. The code within the finally block is always executed.
Syntax:
try:
#Some Code.....
except:
#optional block
#Handling of exception (if required)
else:
#execute if no exception
finally:
#Some code (always executed)
Example:
try:
k=5//0
print(k)
except ZeroDivisionError:
print("Can't divide by zero")
finally:
print('This is always executed')
Output:Can't divide by zero This is always executed
Q. Context Management
Context managers in Python provide a powerful way to manage resources efficiently and safely. A
context manager in Python is an object that defines a runtime context for use with the with statement. It
ensures that setup and cleanup operations are performed automatically.
For instance, when working with file operations, context managers handle the opening and closing of
files, ensuring that resources are managed correctly.
How Context Managers Work?
Python context managers work by implementing the __enter__() and __exit__() methods. These methods
ensure that resources are correctly acquired and released. Also, Python's contextlib module further
simplifies the creation of custom context managers.
Example
Here's a simple example demonstrating how a context manager works with file operations in Python.
with open('example.txt', 'w') as file:
file.write('Hello, World')
In this example, a file is opened in the write mode, and then automatically closed when the block inside
the with statement is exited.
A context manager in Python is a design pattern that facilitates the allocation and deallocation of
resources, ensuring that certain tasks are performed before and after a section of code. The most common
use case is file handling, where a file needs to be opened, then eventually closed, whether the operations
in between were successful or not.
 Context managers are useful for managing files, network connections, database connections, and
any other resources that require setup and cleanup.
 They promote cleaner, more readable, and more robust code by ensuring resources are properly
handled.
In Python, you can use two general approaches to deal with resource management. You can wrap your
code in:
1. A try finally construct
2. A with construct
The with Statement Approach
The Python with statement creates a runtime context that allows you to run a group of statements under
the control of a context manager. Compared to traditional try finally constructs, the with statement can
make your code clearer, safer, and reusable. Many classes in the standard library support the with
statement. A classic example of this is open(), which allows you to work with file objects using with.
syntax:
with expression as target_var:
do_something (target_var) with open ('file.txt', 'r') as file:
example:
with open("example.txt", "r") as f:
data = f.read()
print(f.closed)
Here, after executing the block of code inside the 'with statement, the file is automatically closed, even if
an exception occurs within the block.
Context management protocol consists of two special methods:
1. enter () is called by the with statement to enter the runtime context.
2. exit () is called when the execution leaves the with code block.
Here's how the with statement proceeds when Python runs into it.
1. Call expression to obtain a context manager.
2. Store the context manager's . enter () and. exit () methods for later use.
3. Call . enter () on the context manager and bind its return value to target_var if provided.
4. Execute the with code block.
5. Call. exit () on the context manager when the with code block finishes.
Understanding Context Managers:
1. How They Work:
At the heart of a context manager are two magic methods:. enter() and exit()
 . enter () is called when the ‘with’ block is entered. It can return an object that will be used
within the block.
 . exit () is called when the ‘with’ block is exited. It handles cleanup operations, like closing a
file or releasing a lock.
2. Creating Custom Context Managers:
You can create your own context manager by defining a class with . enter () and
. exit () methods:
Example:
class MyContextManager:
def enter (self):
#Initialization or resource allocation return self
def exit (self, exc_type, exc_value, traceback):
#Cleanup or resource deallocation Pass
3. The contextlib Module:
Python's standard library provides a module named contextlib which offers utilities to create
context managers without always defining a new class. The @contextmanager decorator allows
you to build a context manager using a generator function:
Example:
from contextlib import contextmanager
@contextmanager
def managed_resource():
resource =allocate_resource()
yield resource
resource.deallocate()
Context managers in Python provide a structured and safe way to manage resources, ensuring that
initialization and cleanup tasks are reliably executed. By leveraging context managers, developers
can write cleaner, more maintainable, and error-resistant code, especially when dealing with
external resources or operations that require precise setup and teardown procedures.
Benefits of Python Context Manager
 Concise Syntax: It removes the need for explicit setup and takedown code, simplifying the
code.
 Automatic Resource Handling: Context managers automatically manage resource
allocation and deallocation, ensuring that resources like files, network connections, and
appropriate releasing of locks after usage. This is known as automatic resource handling.
 Exception Safety: The context manager ensures that it properly cleans up the resources,
preventing leaks even in the case of an error within a block.
 Less Boilerplate Code: Context managers simplify and ease the maintenance of the
codebase by removing the boilerplate code required for resource management.

Q. Exceptions as Strings
 Before Python 1.5, exceptions were represented as strings. While this approach was simple, a
lacked the structure and flexibility of classes.
 In Python 1.5, standard exceptions were transitioned to classes, offering better organization and
extensibility. Although string exceptions are no longer recommended, understanding their usage
is helpful for working with older code or recognizing them when encountered.
 String exceptions were raised using the raise statement followed by a string literal or variable
containing the error message.
Example:
try:
#Code that might raise an exception x=10/0
except "division by zero" :
print("Caught a string exception: division by zero")
String exceptions could be caught using the except clause with the string literal matching the
exception.
Example:
try:
#Code that might raise an exception raise "File not found"
except "File not found":
print("Caught a string exception: File not found")
It's important to note that this approach is outdated and using class-based exceptions is now the
standard practice in Python.
Q. Raising Exceptions
The raise keyword is used to raise an exception. You can define what kind of error to raise, and the
text to print to the user.except is a keyword (case-sensitive) in python, it is used to raise an
Exception/Error with a customized message and stops the execution of the programs.
It is very useful when you want to work with the input validations. For example if you are working
with the positive numbers and someone inputs a negative number, in this case, we can raise an
error and stop the program's execution.
Syntax:
if test_condition:
raise Exception(Message) Ex:
string = "Hello"
if string =="Hello" or string== "Hi" or string =="Bye":

raise Exception("This word is not allowed")


Output:
Exception: This word is not allowed
Raising Built-in Exceptions
If you have a piece of code where along with exception handling you have put in place some
conditional statements to validate input etc, then in case of the conditions failing we can either just
print a message or simple raise an exception which can then get handled by the common exception
handling mechanism.
Syntax:
raise Exception("This is a general exception")

Example:
def divide(a, b):
if b==0:
raise ValueError("Cannot divide by zero") return a/b
try:
result divide(10, 0) except ValueError as e:
print(e)

Output: Cannot divide by zero


Custom Exceptions:
Custom exceptions is useful for handling specific error conditions that are unique to your
application, providing more precise error reporting and control.
To create a custom exception in Python, you define a new class that inherits from the built- in
Exception class or any other appropriate built-in exception class. This custom exception class can
have additional attributes and methods to provide more detailed context about the error condition.
Example:
class InvalidAgeError(Exception):

def init__(self, age, message="Age must be between 18 and 100"):

self.age = age
self.message== message
super(). init (self.message)
def set_age(age):
if age 18 or age > 100:
raise InvalidAgeError(age)
print(f"Age is set to {age}")
try:
set_age(150)

except InvalidAgeError as e:

print(f"Invalid age: {e.age}.{e.message}")

Output: Invalid age: 150. Age must be between 18 and 100

Advantages of the raise keyword


 It helps us raise error exceptions when we may run into situations where execution can't
proceed
 It helps us raise error in Python that is caught. Raise allows us to throw one exception at any
time.
 It is useful when we want to work with input validations.
Q. Assertions
There are two basic techniques to handle errors and unexpected issues while coding in Python:
assert statements and
exceptions.
The assert statement is used to determine whether or not a given condition is true. If the
condition not met, an AssertionError is thrown. Assert statements are mostly used for debugging
and a usually deactivated in production code.
Exceptions, on the other hand, are used to handle runtime problems and unexpected circumstances
When an error occurs, an exception is thrown and may be captured and handled using try-except
blocks. Exceptions are used in both the creation and execution of code to gracefully handle failures
and ensure that the program runs even when an error occurs.
Assertions in Python
Assertions in Python are statements that assert or assume a condition to be true. If the condition
turns out to be false, Python raises an AssertionError exception. They are used to detect
programming errors that should never occur if the code is correct.
Syntax:
assert <condition>
assert <condition>, <error message>
1. assert statement has a condition and if the condition is not satisfied the program will stop and give
AssertionError

2. assert statement can also have a condition and a optional error message. If the condition is not
satisfied assert stops the program and gives AssertionError along with the error message.

Example 1: Using assert without Error Message


def avg(marks):
assert len(marks) != 0
return sum(marks)/len(marks) mark1 = []
print("Average of mark 1:",avg(mark 1))
Output: AssertionError
We got an error as we passed an empty list mark1 to assert statement, the condition became false and
assert stops the program and give AssertionError.
Now let's pass another list which will satisfy the assert condition and see what will be our output.
Example 2: Using assert with error message
def avg(marks):
assert len(marks)!=0,"List is empty."
return sum(marks)/len(marks)
mark2= [55,88,78,90,79]
print("Average of mark2:",avg(mark2))
mark1 = []
print("Average of mark 1:",avg(mark1))
output :Average of mark2: 78.0
AssertionError List is empty.
Q.Standard Exceptions in Python

In Python versions 1.5 and later, the standard exceptions are Python classes, and a few new standard exceptions
have been added. Python supports various built-in exceptions, the commonly used exceptions are
NameError: It occurs when a name is not found.i.e attempt to access an undeclared variable
Example:
a=5
c=a+b
print("Sum =",c)
Output:
Traceback (most recent call last):
File "expdemo.py", line 2, in c=a+b
NameError: name 'b' is not defined

ZeroDivisionError: Occurs when a number is divided by zero.


Example:
a=5 b=0
print(a/b)
Output:
Traceback (most recent call last):
File "expdemo.py", line 3,
in print(a/b)
ZeroDivisionError: division by zero
ValueError: Occurs when an inappropriate value assigned to variable.
Example:
a=int(input("Enter a number: "))
b=int(input("Enter a number: "))
print("Sum=”+b)
Output:
Enter a number: 23
Enter a number :abc
Traceback (most recent call last):
File "<main.py>", line 2, in <module>
ValueError: invalid literal for int() with
base 10: 'abc'
Index Error: Occurs when we request for an out-of-range index for sequence
Example:
list=['e','java', 'python']
print("list item is ", list[5])
Output:
Traceback (most recent call last):
File "<main.py>", line 2, in
<module>
IndexError: list index out of range
KeyError: Occurs when we request for a non-existent dictionary key
Example:
dic={"name":"Madhu","location":"Hyd"}
print("The age is:",dic["age"])
Output:
ERROR!
Traceback (most recent call last):
File "<main.py>", line 2, in <module>
KeyError: 'age'
IOError: Occurs when we request for a non-existent input/output file
Example:
F=-open("exam.py") print(fn)
Output:
Traceback (most recent call last);
File "expdemo.py", line 1, in fn-open("exam.py")
FileNotFoundError: [IOError] No such file or directory: 'exam.py’
Q. Creating Exceptions
To create custom exceptions, define a Python class that inherits from the Exception class. The
Exception class offers base functionality you'll need to handle exceptions, and you can customize
it to add features based on your specific needs.
When creating custom exception classes, keep them simple while including necessary attributes
for storing error information. Exception handlers can then access these attributes to handle errors
appropriately.
Steps to Create a Custom Exception:
Define the Exception Class: Create a new class that inherits from the built-in "Exception" class or
any other appropriate base class. This new class will serve as your custom exception.
Example::
class CustomError(Exception):
"""Base class for other exceptions"“”
pass

class SpecificError(CustomError):
"""Specific exception type"""
def init (self, message):
self.message= message
super(). _init (self.message)
Initialize the Exception (Optional): Implement the" init "method to initialize any attributes or
provide custom error messages. This allows you to pass specific information about the error when
raising the exception.
class ValueError(Exception):
def init (self, message="Invalid value"):
self.message =message

27
super(). init (self.message)
Raise the Exception: Once you have defined a custom exception, you can raise it in your code to
signify specific error conditions. Raising user-defined exceptions involves using the raise
statement, which can be done with or without custom messages and attributes.
Syntax :
raise Exception Type (args)
Example:
def process data(value):
if not isinstance(value, int):
raise ValueError("Input must be an integer")
return value *2
Handle the Exception: Handling user-defined exceptions in Python refers to using "try-except"
blocks to catch and respond to the specific conditions that your custom exceptions represent. This
allows your program to handle errors gracefully and continue running or to take specific actions
based on the type of exception raised.
Example:
try:
result =process_data("hello")
except ValueError as e:
print(f"Error: (e}")
else:
print(f"Result: (result)")
Example:
class InvalidAgeError(Exception):
def init (self, age, message "Age must be between 18 and 100"):
self.age = age
self.message= message
super(). init (self.message) def
str (self):
return f" {self.message}provided age:{self.age}"
def set_age(age):
if age 18 or age > 100:
raise InvalidAgeError(age) print(f"Age
is set to {age}")

28
try:
set _age(150)
except InvalidAgeError as e:
print(f"Invalid age: (c.age) (e.message)")
Output Invalid age: 150. Age must be between 18 and 100
Q. Exceptions and the sys Module
The sys module in Python contains several methods and variables for manipulating various aspects
of the Python runtime environment. It helps you work with the interpreter since it gives you access
to variables and functions that work closely with it.
Important Variables In The SYS Module
Version: It helps you understand the version of Python being in use.
Example:
import sys
sys.version
Output :’3.9.6 (tags/v3.9.6:db3ff76, Jun 28 2021, 15:26:21)
sys.argv:
In Python, this includes a list of arguments (command prompt) supplied to the script. If you write
len(sys.argv), you'll get a count of how many arguments there are. sys.argv is used by people who
work with command-line arguments. The name of the script is referred to as sys.argv[0]
Example:
import sys
print(sys.argv[0])
print('Number of arguments present=', len(sys.argv))
print('Total argument list:', str(sys.argv))
Output: sys.py
Number of arguments present = 1 Total
argument list: ['sys.py']
sys.path:
This function displays the current system's python path. It's an environmental variable that
contains the search path for all of the python modules.
Example:
import sys
sys.path
Output: [", "C:\\Python39\\Lib\\idlelib']
sys.maxsize: This maxsize function returns the variable's greatest integer
29
Example:
import sys
sys.maxsize
Output: 9223372036854775807
Important Functions in the SYS Module:
1. sys.exit(): The program will exit the python console or the command prompt. It is usually
used to exit the application if an exception is thrown securely.
Example:
import sys
def is_even(list):
if any (i%21 for i in list):
print("ERROR. Odd one is present in the even list! ")
sys.exit()
else:
print("Pure Even List")
list= [2,4,5,6,8,10]
is_even(list)
is_ even(list)
Output: ERROR: Odd one is present in the even list!
2. sys.setdefaultencoding(): This method allows you to adjust the default encoding for strings
in the Python environment.
Example:
import sys
sys.setdefaultencoding('UTF8')
3. sys.getsizeof(): After using this function, the size of an object in bytes is returned. Any object
can be used as an object.
Example:
import sys i=3
print(sys.getsizeof(i))
Output: 28

Input and Output Using SYS


Variables in the sys modules provide for good control of input and output. We can even send input
and output to different devices using these variables. We can use two variables to do this, which
30
are listed below.

1. stdin: This stdin can be used to take input from the command line directly. This stdin method
is used for taking standard input. It uses the input() function internally. It also adds a \n that is
a new line at the end of each sentence. Let's understand this with an example given below
Example:

import sys
for words in sys.stdin:
if 'quit' words.rstrip():
break
print(f'Input (words)")
print("Exit!!")

Output:

Hello
Input: Hello
Bye
Input: Bye
quit
Exit

2. stdout: The interpreter's standard output stream in Python is analogous to this built-in file
object. The stdout command sends output to the screen console. The output that comes out
using the print statement, an expression statement, or even a prompt direct for input, might
take many different forms. Streams are set to text mode by default. Whenever a print function
is used in the code, it is written first to sys.stdout, then to the screen. Let's understand this in a
better way from the example that is given below:
Example:
import sys
sys.stdout.write('Learn_To_Code')
Output: Learn_ To_Code

Q. Modules and Files


In Python, modules are files containing Python definitions and statements, while files are used to
store data or code. Modules facilitate code organization and reusability, and files handle data
persistence.

31
Modules: According to the formal definition of Python modules, they are a Python file containing
statements, definitions, Python code, classes, functions, and variables. They are the files with the
py extension. A Python module can also include runnable code.
When we group related code into a module, it makes it easier to understand and use. Also, the
code is more logically organized. A common real-life example is a music store with many sections
containing different types of songs and music.
Features of Modules:
 Allows code reusability
 Provides flexibility in organizing code logically and segments a larger problem into small
manageable files.
Create a python Module
You can create a Python module by writing the desired code and saving the file using the py
extension.
Example: Creating a module named "mymath" #mymath.py
def add(a, b):
return a + b """Return the sum of two numbers."""
def subtract(a, b):
return a - b Return the difference between two numbers.""
Types of Modules in Python
There are two types of Python modules:
1. In-built modules in Python
2. User-Defined Modules in Python
1. In-built Modules in Python
The Python built-in modules come with a Python standard library, offering a range of
functionalities. So, you don't need to install these modules separately, as they are available in
Python by default. There are several in-built Python modules, such as sys, math, os, random, etc.
Built-In modules like:
math sys OS
random and many more.
2. User-defined Modules in Python
Users create these modules to make their code more organized, modular, and reusable. These are
defined in a different py file, so you must import and use them in your Python scripts.
There are a few other types of Python modules, such as package modules, third-party modules,
32
and extension modules.
Variables in Python Modules
We have already discussed that modules contain functions and classes. But apart from functions
and classes, modules in Python can also contain variables in them. Variables like tuples, lists,
dictionaries, objects, etc.
Example:
#This is variables module
## this is a function in module def factorial(n):
if n1||n=0:
return 1
else:
return n factorial(n-1)
## this is dictionary in module
power = { 1:1, 2:4, 3:9, 4:16, 5:25.}
1 ##This is a list in the module alphabets [a,b,c,d,e,f,g,h]
Q. Namespaces
In Python, a namespace is a collection of names, which can be variables, functions, classes, or
modules. Namespaces provide a way to organize and manage the names in a Python program,
ensuring that each name is unique and can be accessed correctly.
Types of Namespaces in Python
Global Namespace: This is the top-level namespace that contains all the names defined at the
module level.
Local Namespace: This is the namespace that contains the names defined within a function or a
class.
Built-in Namespace: This is the namespace that contains the built-in functions, types, and
constants provided by the Python interpreter.
Accessing Namespaces
In Python, you can access the names in a namespace using the dot notation. For example, to access
a variable x in the global namespace, you would use x, while to access a function my_function in a
module my_module, you would use my_module.my_function.
Example of accessing namespaces
x=10
def my_function():
33
y=20
print(x)
print(y)
my_function()

Namespace Hierarchy: Python's namespace hierarchy follows a specific structure, where the
built-in namespace is the top-level namespace, followed by the global namespace, and then the
local namespaces. This hierarchy determines how names are resolved when they are referenced in
a Python program.
By understanding the concept of namespaces and how they work in Python, you can write more
organized and maintainable code, and avoid naming conflicts that can lead to bugs and errors.
Working with Namespaces in Python
In Python, you can manipulate namespaces using various built-in functions and keywords, such
as:
a) globals(): Returns a dictionary of the names in the global namespace
b) locals(): Returns a dictionary of the names in the current local namespace.
c) dir(): Returns a list of names in the namespace of an object.
d) Import statement: Brings names from a module into the current namespace.
e) As keyword: Allows you to assign a different name to an imported object.
f) name_variable: Provides information about the current namespace
Example:
## Example of namespace manipulation
import math as m
print(globals()) ### Access global namespace
print(locals()) ## Access local namespace .
print(dir(m)) ## Access namespace of the math module
print(__name__) ## Access the current namespace name

Q. Importing Modules
A file is considered as a module in python. To use the module, you have to import it using the
import keyword. The function or variables present inside the file can be used in another file by
importing the module. This functionality is available in other languages, like typescript,
JavaScript, java, ruby, etc.

34
Importing a Module in Python
The most common way to use a module is by importing it with the import statement. This allows
access to all the functions and variables defined in the module.
Example:
import math as pie
print("The value of pi is:", pie.pi)
Output: The value of pi is: 3.141592653589793
Importing Specific Functions
Instead of importing the entire module, we can import only the functions or variables we need
using the “from” keyword. This makes the code cleaner and avoids unnecessary imports.
Example:
from math import pi
print(pi)
Output: 3.141592653589793
Importing Built-in Modules
Python provides many built-in modules that can be imported directly without installation. These
modules offer ready-to-use functions for various tasks, such as random number generation, math
operations and file handling.
Example:
import random
#Generate a random number between 1 and 10
res =random.randint(1, 10)
print("Random Number:", res)
Output: Random Number:7
Importing Modules with Aliases
To make code more readable and concise, we can assign an alias to a module using the as
keyword. This is especially useful when working with long module names.
Example:
import math as m
#Use the alias to call a function result
result=m.sqrt(25)
print("Square root of 25:", result)
Importing Everything from a Module (*)
Instead of importing specific functions, we can import all functions and variables from a module
35
using the symbol. This allows direct access to all module contents without prefixing them with the
module name.
Example:
from math import *
print(pi) #Accessing the constant 'pi'
print(factorial(6)) # Using the factorial function
Output: 3.141592653589793
720
Advantages:
 It becomes easy to trace back the modules for code check.
 Easy to use and very straight forward.
 If the project is moved to a different path, still the imports will remain the same

Q. Importing Module Attributes


Python module has its attributes that describes it. Attributes perform some tasks or contain some
information about the module. Some of the important attributes are explained below:
_name_ Attribute:
The name attribute returns the name of the module. By default, the name of the file (excluding the
extension .py) is the value of _name_attribute.
Example:_name_Attribute
import math
print(math.__name__) #’math’
Q. Module Built-in Functions
OS module:
This module has functions to perform many tasks of operating system.
mkdir(): We can create a new directory using mkdir() function from os module.
Example:
import os
os.mkdir("d:\\tempdir")
A new directory corresponding to path in string argument in the function will be created. If we
open D drive in Windows explorer we should notice tempdir folder created.
rmdir(): The rmdir() function in os module removes a specified directory either with absolute or
relative path. However it should not be the current working directory and it should be empty.

36
Example:
os.rmdir("d:\\temp")
listdir(): The os module has listdir() function which returns list of all files in specified directory.
os.listdir("c:\\Users")
['acer', 'All Users', 'Default', 'Default User', 'desktop.ini', 'Public']

Statistics module: This module provides following statistical functions:


mean(): mean() calculate arithmetic mean of numbers in a list.
Example:
import statistics
print(statistics.mean([2,5,6,9]))
Output 5.5
median(): median returns middle value of numeric data in a list. For odd items in list, it returns value at (n
+ 1) / 2 position. For even values, average of values at n/2 and (n / 2) + 1 positions is returned.
Example:
import statistics
print(statistics.median([1,2,3,8,9]) )
Output :3
mode(): mode() returns most repeated data point in the list.
Example:
import statistics
print(statistics.mode([2,5,3,2,8,3,9,4,2,5,6]))
Output: 2
stdev(): stdev() calculates standard deviation on given sample in the form of list.
Example:
import statistics
print(statistics.stdev([1,1.5,2,2.5,3,3,5,4,4.5,5]))
Output 1.3693063937629153

Time module:This module has many time related functions.


time(): This function returns current system time in ticks. The ticks is number of seconds elapsed after epoch
time i.e. 12.00 am, January 1, 1970.
Epoch (reference point in time)= 12:00 AM, January 1, 1970 (UTC)
The value returned is called ticks, representing the number of seconds elapsed since this date.

37
Example:
import time
print(time.time())
Output 1544348359.1183174
localtime(): This function translates time in ticks in a time tuple notation.
Example:
import time
tk = time.time()
time.localtime(tk)
print(tk)
Output :
asctime(): This functions readable format of local time
Example:
import time
tk = time.time() # get ticks (seconds since epoch)
tp = time.localtime(tk) # convert ticks to struct_time (local time)
print(time.asctime(tp))
Output: Mon Sep 8 10:48:03 2025
ctime(): This function returns string representation of system's current time
Example:
import time
print(time.ctime())
Output: Mon Sep 8 10:50:43 2025

sleep(): This function halts current program execution for a specified duration in seconds.
Example:
import time
time.sleep(10) # pause for 10 seconds
print(time.ctime())
Output 'Sun Dec 9 15:19:34 2018'

sys module:
This module provides functions and variables used to manipulate different parts of the Python runtime
environment.

sys.setdefaultencoding(): This method allows you to adjust the default encoding for strings in the
Python environment.
Example:
import sys
sys.setdefaultencoding("UTF8")

38
sys.getsizeof(): After using this function, the size of an object in bytes is returned. Any object can be used as
an object.
Example:
import sys
i=3
print(sys.getsizeof(i))
Output: 28
Q. Packages
A python package is a collection of modules. Modules that are related to each other are mainly put in the
same package. When a module from an external package is required in a program, that package can be
imported and its modules can be put to use.
A package is a directory of Python modules that contains an additional init py file, which distinguishes a
package from a directory that is supposed to contain multiple Python scripts. Packages can be nested to
multiple depths if each corresponding directory contains its own_ init_.py file.

Creating a Package in Python: Creating packages in Python allows you to organize your code into reusable
and manageable modules. Here's a brief overview of how to create packages:
Create a Directory: Start by creating a directory (folder) for your package. This directory will serve as the
root of your package structure.
Add Modules: Within the package directory, you can add Python files (modules) containing your code. Each
module should represent a distinct functionality or component of your package.
Init File: Include an init py file in the package directory. This file can be empty or can contain an
initialization code for your package. It signals to Python that the directory should be treated as a package.

39

You might also like