GE3151 PS and Python Programming - UNIT V
GE3151 PS and Python Programming - UNIT V
Indexed Sequential
Feature Sequential Access Direct/Random Access
Access
Access Data is accessed in a linear Data can be accessed directly Combination of sequential
Pattern order. at any position. and direct access.
Typically used in tape Used in devices like HDDs, Typically used in
Storage Type
drives or sequential files. SSDs, and RAM. databases or file systems.
Balanced, fast for both
Efficiency Slower for random access. Fast for direct/random access. sequential and random
access.
Reading log files, Retrieving elements from an Database search using an
Example
streaming data. array or database by key. index.
Faster than sequential, but
Performance Slower for random access. Fast access to any data. slower than pure random
access.
2. FILES IN PYTHON
2.1 File Opening Modes
Python’s open() function supports various modes for opening files:
Mode Description
'r' Opens the file for reading only (default). File must exist. File pointer starts at the beginning.
'r+' Opens the file for reading and writing. File must exist. Pointer starts at the beginning.
'w' Opens the file for writing only. Creates the file if it doesn’t exist; overwrites if it does.
'w+'
Opens the file for reading and writing. Creates the file if it doesn’t exist; overwrites if it does.
Pointer starts at the beginning.
'a' Opens the file for appending. Creates the file if it doesn’t exist. Pointer starts at the end.
'a+'
Opens the file for reading and appending. Creates the file if it doesn’t exist. Pointer starts at the
end.
Attribute Description
file.name Returns the name of the file.
file.mode Returns the mode in which the file was opened ('r', 'w', 'a', etc.).
file.closed Returns True if the file is closed, False otherwise.
file.newlines Returns the newline convention used in the file (None, \n, \r\n, or a tuple of these).
file.seekable() Returns True if the file supports random access using seek().
file.readable() Returns True if the file can be read from.
file.writable() Returns True if the file can be written to.
file.fileno() Returns the file descriptor (integer) used by the underlying OS.
Example
# Open the file manually
file = open("example.txt", "w+")
Output
File Name: example.txt
File Mode: w+
Is File Closed? False
Newlines Used: None
Is File Seekable? True
Is File Readable? True
Is File Writable? True
File Descriptor (OS Level): 3
Is File Closed After Closing? True
Example
# Open a file for demonstration
file = open("example.txt", "w+")
# Demonstrate file.read(size=-1)
print("\nRead entire file content:")
print(file.read()) # Read the entire file
# Demonstrate file.readlines(hint=-1)
file.seek(0)
print("\nRead all lines as a list:")
print(file.readlines()) # Read all lines and return as a list
# Demonstrate file.fileno()
print("\nFile descriptor (OS level):", file.fileno())
# Demonstrate file.readinto(buffer)
file.seek(0) # Reset file pointer
buffer = bytearray(10) # Create a buffer of size 10
file.readinto(buffer) # Read bytes directly into the buffer
print("\nBuffer after reading into it:", buffer.decode())
Expected Output
Read entire file content:
Hello, World!
This is a test file.
Line 1
Line 2
Line 3
Example
# Create a sample file for demonstration
file = open("sample.txt", "w")
file.write("Hello, World!\n")
file.write("This is a test file.\n")
file.write("Python makes file handling easy.\n")
file.write("Have a great day!\n")
file.close()
Output
Using read():
Using readlines():
['Hello, World!\n', 'This is a test file.\n', 'Python makes file handling easy.\n',
'Have a great day!\n']
Using readline():
Hello, World!
This is a test file.
# 'w' mode: Open for writing (creates a new file or overwrites if it exists)
file = open(filename, 'w')
file.write("This is the first line in the file.\n")
file.write("This is the second line in the file.\n")
file.close()
# 'r+' mode: Open for both reading and writing (file must exist)
print("\nOpening in 'r+' mode:")
file = open(filename, 'r+')
print("Original file content:", file.read()) # Reads the entire file
file.write("This is a new line added using r+ mode.\n") # Overwrites data at current
file position
file.close()
# 'w' mode: Open for writing (creates a new file or overwrites if it exists)
print("\nOpening in 'w' mode:")
file = open(filename, 'w')
file.write("This file is overwritten using 'w' mode.\n")
file.close()
# 'w+' mode: Open for reading and writing (creates a new file or overwrites if it
exists)
print("\nOpening in 'w+' mode:")
file = open(filename, 'w+')
file.write("This file is overwritten using 'w+' mode.\n")
file.seek(0) # Move pointer to the beginning of the file to read
print(file.read()) # Reads the content after writing
file.close()
# 'a+' mode: Open for reading and appending (creates a new file if it doesn't exist)
print("\nOpening in 'a+' mode:")
file = open(filename, 'a+')
file.write("This line is appended using 'a+' mode.\n")
file.seek(0) # Move pointer to the beginning of the file to read
print(file.read()) # Reads the entire content of the file
file.close()
Expected Output
Opening in 'r' mode:
This is the first line in the file.
This is the second line in the file.
3. FORMAT OPERATOR
The format operator (%) in Python is a way to format strings and insert values into a string, similar to how
it works in the C programming language. It allows you to embed variables into strings, creating dynamic and
readable output. The format operator can be used with placeholders in a string to insert values at specific
locations.
Basic Syntax:
<format expression> % (v1, v2, v3 …. vn ) or
<format expression> % values
Where v1 to vn are variables that are formateed using the expression, values is a tuple with exactly the
number of items specified by the format string, or a single mapping object.
All the parameters other than conversion type are optional. It has to be specified only when needed.
• key: Specifies the field name in the format string. If not provided, it uses the positional argument.
• flags: Adjusts the formatting of the output (e.g., +, -, 0).
• width: Specifies the minimum number of characters for the output.
• .precision: Sets the number of decimal places for numbers.
• length type: Specifies the size or data type of the argument (e.g., h, l).
• conversion type: Specifies the type of formatting to apply (s, d, f, e, etc.).
Allthe parameters, except for the conversion type, are optional. You can include them in the format
expression only when needed.
0
Pads the value with zeros (0) instead of spaces to fill the specified {:010d} with 0000000042
width. 42
Conversion
Description Example Output
Type
s Converts the value to a string. "{:s}".format(42) 42
d Converts the value to an integer (base 10). "{:d}".format(42) 42
i
Converts the value to an integer (base 10), "{:i}".format(42) 42
same as d.
f
Converts the value to a floating-point "{:f}".format(3.14159) 3.141590
number.
e
Converts the value to scientific notation "{:e}".format(1000000) 1.000000e+06
(exponential form).
E
Similar to e, but uses uppercase E for the "{:E}".format(1000000) 1.000000E+06
exponent.
g
Uses the most compact representation "{:g}".format(0.0000123) 1.23e-05
between f and e.
G
Similar to g, but uses uppercase E for the "{:G}".format(0.0000123) 1.23E-05
exponent.
x
Converts an integer to a lowercase "{:x}".format(255) ff
hexadecimal.
X
Converts an integer to an uppercase "{:X}".format(255) FF
hexadecimal.
o Converts an integer to an octal number. "{:o}".format(8) 10
b Converts an integer to a binary number. "{:b}".format(5) 101
c
Converts an integer to the corresponding "{:c}".format(97) a
Unicode character.
%
Converts the value to a percentage "{:%}".format(0.25) 25.000000%
(multiplies by 100 and adds %).
Output:
Name: Alice, Age: 30, Height: 5.6
Name: Alice, Age: 30, Height: 5.6
Name: Alice, Age: 30, Height: 5.6
Name: Alice, Age: 30, Height: 5.6
Name: Alice, Age: 30, Height: 5.6
Formatted number: 1234.57
Formatted number with leading zeros: 00001234.57
# 7. Rounding to an integer
rounded_number = f"Rounded to integer: {num:.0f}"
print(rounded_number)
Output:
Formatted number (%.2f): 1234.57
Formatted number ({:.2f}): 1234.57
Formatted number (f-string, .2f): 1234.57
Formatted number with leading zeros (010.2f): 00001234.57
Formatted number with thousands separator: 1,234.57
Formatted as percentage: 123457.89%
Rounded to integer: 1235
# Variables
name = "Alice"
age = 30
height = 5.6
# 1. Using the `%` operator (old-style formatting) for strings and numbers
formatted_str_percent = "Name: %s, Age: %d, Height: %.1f" % (name, age, height)
print(formatted_str_percent)
Output:
Name: Alice, Age: 30, Height: 5.6
Name: Alice, Age: 30, Height: 5.6
Name: Alice, Age: 30, Height: 5.6
Name: Alice, Age: 30, Height: 5.6
Name: Alice, Age: 30, Height: 5.6
Formatted number: 1234.57
Formatted number: 1234.57
Formatted number: 1234.57
Output in formatted_output.txt:
Using % operator:
Name: John, Age: 25, Height: 5.9, City: New York
Using f-strings:
Name: John, Age: 25, Height: 5.9, City: New York
# Data to be formatted
name = "Alice"
age = 30
height = 5.6
city = "London"
Output:
Name: Alice, Age: 30, Height: 5.6, City: London
City: London, Height: 5.6, Age: 30, Name: Alice
Name: Alice, Age: 30, Height: 5.6, City: London
Formatted height: 5.60
Left aligned: Alice , Right aligned: Alice, Center aligned: Alice
Zero-padded number: 00042
Name: Alice, Age: 30, Height: 5.6, City: London
Output
Arguments passed to the script: ['example.py', 'Hello', 'World', '123']
example.py
Hello
World
123
a. Syntax Errors
• Description: Syntax errors occur when the code does not follow the correct syntax of the Python
language. These errors are usually detected by the Python interpreter before the program runs.
• Example:
print("Hello, World!"
• Example:
x = 10 / 0 # This will raise a ZeroDivisionError
Error: ZeroDivisionError because dividing by zero is not allowed.
c. Logical Errors
• Description: Logical errors occur when the program runs without crashing but does not produce the
correct result. These errors are typically due to incorrect logic in the code, which can be difficult to
debug.
• Example:
def add_numbers(a, b):
return a - b # This is a logical error, it should be addition, not subtraction
result = add_numbers(3, 4)
print(result) # Output will be incorrect (it will print 1 instead of 7)
Error: The function does not perform the correct operation due to the wrong use of the subtraction
operator instead of addition.
c. Example
try:
# Trying to divide by zero
result = 10 / 0
except ZeroDivisionError:
# This block will run if a ZeroDivisionError occurs
print("Error: You can't divide by zero!")
try:
# Asking the user to input a number
number = int(input("Enter a number: "))
print(f"You entered: {number}")
except ValueError:
# This block will run if a ValueError occurs (non-numeric input)
print("Error: That's not a valid number!")
a. Exception Types
The following are the types of exceptions in Python.
Example Program:
# ZeroDivisionError
try:
print("ZeroDivisionError Example:")
x = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
print()
# IndexError
try:
print("IndexError Example:")
my_list = [1, 2, 3]
print(my_list[5])
except IndexError as e:
print(f"Error: {e}")
print()
# KeyError
try:
print("KeyError Example:")
my_dict = {"name": "Alice", "age": 25}
print(my_dict["address"])
except KeyError as e:
print(f"Error: {e}")
print()
# TypeError
try:
print("TypeError Example:")
x = "hello" + 5
except TypeError as e:
print(f"Error: {e}")
print()
# AttributeError
try:
print("AttributeError Example:")
class Person:
def __init__(self, name):
self.name = name
p = Person("Alice")
print(p.age) # Attribute does not exist
except AttributeError as e:
print(f"Error: {e}")
print()
# FileNotFoundError
try:
print("FileNotFoundError Example:")
with open("non_existent_file.txt", "r") as file:
content = file.read()
except FileNotFoundError as e:
print(f"Error: {e}")
print()
# ImportError
try:
print("ImportError Example:")
import non_existent_module
# OverflowError
try:
print("OverflowError Example:")
x = 1e1000 # A very large number
except OverflowError as e:
print(f"Error: {e}")
print()
# StopIteration
try:
print("StopIteration Example:")
my_list = [1, 2, 3]
it = iter(my_list)
while True:
print(next(it))
except StopIteration as e:
print(f"Error: {e}")
print()
# MemoryError
try:
print("MemoryError Example:")
large_list = [1] * (10**10) # Trying to allocate too much memory
except MemoryError as e:
print(f"Error: {e}")
print()
# NotImplementedError
try:
print("NotImplementedError Example:")
class Animal:
def make_sound(self):
raise NotImplementedError("Subclasses must implement this method")
animal = Animal()
animal.make_sound()
except NotImplementedError as e:
print(f"Error: {e}")
Example:
import random
2. Math Module
The math module provides mathematical functions such as calculating square roots, trigonometric
operations, and constants like π (pi).
Example:
import math
3. Calendar Module
Example:
import calendar
# Print the calendar for the month of December 2024
print(calendar.month(2024, 12))
# Check if a year is a leap year
is_leap = calendar.isleap(2024)
print(f"Is 2024 a leap year? {is_leap}")
4. Datetime Module
The datetime module supplies classes for manipulating dates and times, like obtaining the current date or
performing date arithmetic.
Example
import datetime
# Get the current date and time
now = datetime.datetime.now()
print(f"Current date and time: {now}")
# Extract specific parts of the current date
current_date = now.date()
current_time = now.time()
print(f"Current date: {current_date}")
print(f"Current time: {current_time}")
# Format the date in a specific format
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted date and time: {formatted_date}")
6. PYTHON PACKAGE
A Python package is a way of organizing related modules into a single directory hierarchy. It allows you to
structure your Python code in a more modular and reusable manner. A package is essentially a directory
containing multiple Python modules (files with .py extension) and a special file called __init__.py, which tells
Python that this directory should be treated as a package. In simpler terms, a package is a collection of
modules, and a module is a collection of functions, classes, and variables.
• __init__.py: This special file is used to mark the directory as a package. The file can be empty
or contain initialization code for the package.
• module1.py, module2.py: These are Python modules that contain the actual code for your
package.
• sub_package/: A package can contain sub-packages, which themselves are directories with their
own __init__.py files.
c. Importing a sub-package:
import my_package.sub_package.sub_module1
Package Structure:
my_math/
__init__.py
addition.py
subtraction.py
Content of addition.py:
# addition.py
def add(a, b):
return a + b
Content of subtraction.py:
# subtraction.py
def subtract(a, b):
return a - b
Content of __init__.py:
# __init__.py
print("My Math Package Initialized")
result_add = add.add(5, 3)
result_sub = sub.subtract(5, 3)
Output:
My Math Package Initialized
Addition Result: 8
Subtraction Result: 2
7. PICKLING
Pickling in Python refers to the process of converting a Python object (such as a list, dictionary, or class
instance) into a byte stream so that it can be saved to a file, transmitted over a network, or stored in a database.
The purpose of pickling is to enable easy storage and retrieval of Python objects. Pickling is essentially the
process of serializing Python objects, which means converting complex data structures into a format that can
be easily stored or transmitted. The opposite process of pickling is called unpickling, which refers to the
process of converting the byte stream back into the original Python object. In Python, pickling is done using
the pickle module, which provides methods to serialize (pickle) and deserialize (unpickle) Python objects.
8. ILLUSTRATIVE PROGRAMS
a. File Compare
# Ask the user for the paths of the two files to compare
file1_path = input("Enter the path of the first file: ")
file2_path = input("Enter the path of the second file: ")
b. File Copy
# Ask the user for the source and destination file paths
source_file = input("Enter the path of the source file: ")
destination_file = input("Enter the path of the destination file: ")
# Open the destination file in write mode (create a new file or overwrite if it exists)
destination = open(destination_file, 'wb')
# Read the content of the source file and write it to the destination file
content = source.read()
destination.write(content)
c. Words Count
# Ask the user for the path to the text file
file_path = input("Enter the path to the text file: ")
# Check if the age is within the valid voting age range (18-120)
if 18 <= age <= 120:
return age
else:
raise ValueError("Age must be between 18 and 120 to be eligible to vote.")
except ValueError as e:
# Catch invalid input or out-of-range age
print(f"Invalid input: {e}")
return None
# Function to get age from the user and validate it with I/O error handling
def get_age():
while True:
try:
age_input = input("Enter your age to check if you're eligible to vote: ")
Sample Output:
Enter marks (0-100): 105
Invalid input: Marks must be between 0 and 100.
Please try again with valid marks.
Enter marks (0-100): abc
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________