UNIT-II
In Python, a module is a file containing Python definitions and
statements. Modules provide a way to organize code into reusable
blocks. Predefined modules, also known as built-in modules or standard library
modules, are readily available for use without requiring external installation. They
come bundled with the Python interpreter and offer a wide range of functionalities.
Common Predefined Modules
• os: Interacting with the operating system (e.g., file system navigation, environment
variables).
• sys: System-specific parameters and functions (e.g., command-line arguments, interpreter
information).
• math: Mathematical operations (e.g., trigonometric functions, logarithms, square roots).
• datetime: Working with dates and times (e.g., formatting, parsing, calculations).
• random: Generating random numbers and sequences.
• json: Encoding and decoding JSON data.
• csv: Reading and writing CSV files.
• urllib: Working with URLs.
• collections: Specialized container datatypes (e.g., named tuples, ordered dictionaries).
• re: Regular expressions for pattern matching in strings.
• time: Time-related functions.
Using Modules
To use a module, it must first be imported using the import statement. After importing, the
module's functions, classes, and variables can be accessed using the dot notation
(e.g., module_name.function_name()).
import math
print(math.pi) # Accessing the value of pi from the math module
Specific names can be imported directly from a module using the from ... import statement.
from math import sqrt
print(sqrt(25)) # Accessing the sqrt function directly
Creating Modules
users can create their own modules by saving Python code in a .py file. These modules can then
be imported and used in other Python programs.
example
# my_module.py
def greet(name):
print(f"Hello, {name}!")
# main.py
import my_module
my_module.greet("Alice")
# Output:
Hello, Alice!
Packages
Packages are a way to organize modules into a hierarchical structure using directories. A package
is a directory containing an __init__.py file (which can be empty) and one or more modules or
subpackages. This allows for better code management and reusability, especially in larger
projects.
Advantages
1. Reduced Development Time
Built-in modules in Python are made to perform various tasks that are used without installing
external module or writing the lengthy code to perform that specific task
2. Reliability
These modules have been tested and have been in use by the Python community for
years. As a result, they are typically stable and have fewer bugs compared to
new modules.
3. Consistency
Developers familiar with these modules can easily understand and collaborate on
codebases across different projects.
4. Documentation
Includes detailed explanations and examples for Python built-in modules. This makes it
easier to learn and utilize them.
Built-in Modules in Python
1.Tkinter module in Python
"tkinter" is the standard GUI (Graphical User Interface) library in
Python. "tkinter" module is used to create windows, buttons, text boxes, and other UI
elements for desktop applications.
2.Random module in Python
The “random” module in Python is used to generates random numbers and provides the
functionality of various random operations such as ‘random.randint()’,
‘random.choice()’, ‘random.random()’, ‘random.shuffle()’ and many more.
Example:
import random
languages= ["Java", "C", "C++", "Python"]
fruit = random.choice(languages)
print(fruit)
output:
python
3.Math Module in Python
The math module offers mathematical functions used for advanced arithmetic operations.
This includes trigonometric functions, logarithmic functions, and constants like pi in
program.
using math.sqrt() method and the value of PI using math.
Example:
import math
val1 = math.sqrt(64)
val2 = math.pi
print(val1)
print(val2)
Output
8.0
3.141592653589793
4.Datetime module in Python
module allows for manipulation and reading of date and time values
we have print the today' date and current time by using datetime.date.today() method .
import datetime
date = datetime.date.today()
time = datetime.datetime().time()
print(date)
print(time)
5.calendar Module in Python
The calendar module allows operations and manipulations related to calendars.
import calendar
april = calendar.month(2023,4 )
print(april)
Output
april 2023
Mo Tu We Th Fr Sa Su
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
Importing of modules
There are two ways to importing of modules
1. Import math
The most common way to use a module is by importing it with the import
statement. This allows access to all the functions
2. Importing Specific Functions
Instead of importing the entire module, we can import only the functions or
variables we need using the from keywords
from math import pi
Python Exception
Exception and Error
• Error: Errors are serious issues that a program should not try to handle.
They are usually problems in the code's logic or configuration and need to
be fixed by the programmer. Examples include syntax errors and memory
errors.
• Exception: Exceptions are less severe than errors and can be handled by the
program. They occur due to situations like invalid input, missing files or
network issues.
• An exception in Python is an event that occurs during the execution of
a program, disrupting the normal flow of instructions. It signals that
an error or unusual condition has been encountered.
• Python uses exceptions to handle various types of errors, such
as ZeroDivisionError, TypeError, FileNotFoundError.
HOW DO WE HANDLE EXCEPTIONS
try, except, else and finally Blocks
• try Block: If we expect a block of code with exceptions that block of code
will be executed within try block . If an exception occurs, execution will
immediately jump to the except block.
• except Block: It enables us to handle the exception. If the code inside the try
block throws an error, it jumps to the except block and executes it. We can
handle specific exceptions .
• else Block: It is optional and if included, must follow all except blocks. The
else block runs only if no exceptions are raised in the try block.
• finally Block: This block always runs, regardless of whether an
exception occurred or not. It is typically used for closing files,
releasing resources.
Example:
try:
n=0
res = 100 / n
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Enter a valid number!")
else:
print("Result is", res)
finally:
print("Execution complete.")
Output
You can't divide by zero!
Execution complete.
Common Exceptions in Python
Exception Name Description
Base class for all errors related to arithmetic
ArithmeticError operations.
Raised when a division or modulo operation is
ZeroDivisionError performed with zero as the divisor.
KeyError Raised when a dictionary key is not found
NameError Raised when a local or global name is not found.
Raised when a function receives an argument of
ValueError the right type but inappropriate value.
Raised when an operation or function is applied
TypeError to an object of inappropriate type.
Advantages of Exception Handling:
• Improved program reliability: programs without exception handling may
crash.
With exception handling, The program won’t crash suddenly You can catch
such errors and decide how to handle them and It can continue running or
exit gracefully with a helpful message.
Simplified Error Handling: You would need many if-else statements to
check for errors in each step. You group risky code in a try block. All error-
handling code goes into except blocks.
Easier Debugging: It shows the exact line where the error happened. It
includes the error type and message. This helps you quickly identify and
fix bugs.
File Handling in Python
File handling in Python allows you to work with files on your
computer—reading data from files, writing data to files, or modifying
existing files. It is an essential skill for data processing, logging, and
many other applications.
• File handling refers to the process of performing operations on a file
such as creating, opening, reading, writing and closing it, through a
programming interface.
• It handles the flow of data in the files in a program .it ensures the
safety and efficiency of the data in the storage device.
Operations of a file
Opening Files
To work with a file, you first need to open it using the open() function:
file = open('filename.txt', 'mode')
• 'filename.txt' is the file name.
• 'mode' specifies what you want to do:
o 'r' — Read (default). Opens a file for reading.
o 'w' — Write. Creates a new file or overwrites an existing one.
o 'a' — Append. Adds data to the end of the file.
o 'b' — Binary mode (used with 'r' or 'w'), for images, audio, etc.
o '+' — Read and write.
Reading Files
Reading a file means retrieving its content.
Example: Reading the entire content
with open('example.txt', 'r') as file:
content = file.read()
print(content)
Example: Reading line by line
with open('example.txt', 'r') as file:
for line in file:
print(line.strip()) # Remove the newline characters
Writing to Files
Writing means creating or modifying files.
Example: Writing data (overwrites existing content)
with open('example.txt', 'w') as file:
file.write("Hello, students!\n")
Example: Appending data (adds to the existing content)
with open('example.txt', 'a') as file:
file.write("Welcome to Python programming.\n")
Closing Files
It's important to close files to free resources, but when using the with statement,
this is handled automatically.
file.close()
• Always use with open() because it automatically closes the file.
• File modes are essential: 'r' for reading, 'w' for writing, 'a' for appending.
• Be cautious with 'w': it overwrites existing files without warning.
• When working with binary data (like images), include 'b' in the
mode('rb', 'wb').
Handling exceptions is important in file operations because files may not exist,
permissions might be restricted, or other I/O errors can occur. In Python, this is
typically done using try-except blocks to catch and manage potential errors
gracefully.
Exception Handling in File Operations
Common exceptions:
• FileNotFoundError: Raised when trying to open a file that does not exist in
read mode.
• PermissionError: Raised when the program doesn't have permission to
access the file.
• IOError / OSError: General errors related to input/output operations (more
common in older Python versions).
Basic Example of Exception Handling
try:
with open('nonexistent_file.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("The file does not exist.")
except PermissionError:
print("You do not have permission to access this file.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Explanation:
• The try block contains the code that might raise an exception.
• Specific exceptions like FileNotFoundError are caught and handled
separately.
• The general except Exception as e catches any other unexpected errors and
displays the message.
Tips:
• Always handle exceptions to make your program more robust.
• You can use multiple except blocks to handle different errors distinctly.
• You can also use a finally block to execute code regardless of whether an
exception occurred (e.g., closing a file manually if not using with).
Example with finally
try:
file = open('example.txt', 'r')
content = file.read()
except FileNotFoundError:
print("File not found.")
finally:
file.close()