Python Notes_unit 4 (1)
Python Notes_unit 4 (1)
UNIT 4
FILES AND REGULAR EXPRESSIONS
Files, File Handling Operations, User Defined Exceptions, Regular Expression, Types using
Match function, Postfix, Infix, prefix conversion.
Practice Programs
1. A proctor of our university wants a student to write a program that calculates the average of
marks scored by her wards in CAT1. She has the details such as name, register number,
mark1, mark2 and mark3 of her proctees. The constraint given by the faculty is that any of the
details must not be altered by mistake. Help the student to develop a Python program.
2. Consider the following scenario for finding the number of students who secured centum in
mathematics in their examination. A total of 6 lakhs students appeared for the examinations
and their results are generated automatically and updates to the portal using file.
In Python, files are used to store and retrieve data persistently. Python provides built-in
functions and methods for working with files. Here's an overview of working with files in
Python:
Opening a File:
You can use the `open()` function to open a file. It takes two parameters: the file name (or
path) and the mode in which the file should be opened (`'r'` for read, `'w'` for write, `'a'` for
append, etc.).
# Opening a file for writing (creates a new file or truncates existing content)
file = open(file_path, 'w')
# Opening a file for appending (creates a new file or appends to existing content)
file = open(file_path, 'a')
content = file.read()
print(content)
lines = file.readlines()
print(lines)
Writing to a File:
1. Writing a String:
Appending to a File:
The `with` statement ensures proper resource management. It automatically closes the
file when the block is exited.
Seeking in a File:
The `seek()` method is used to change the file position to a specified byte.
Always remember to close the file after reading or writing to avoid resource leaks.
file.close()
Working with files in Python is essential for tasks like reading and writing data, handling
configuration files, logging, and more. Using the `with` statement ensures that the file is
closed properly, even if an exception occurs.
You can create custom exceptions specific to file handling scenarios in Python. Here's an
example of defining and using a custom file-related exception:
In this example:
- We define a custom exception class named `FileHandlingError`, inheriting from the built-
in `Exception` class.
- The `__init__` method initializes the exception with an optional custom error message.
- The `read_file` function attempts to read data from a file. If the file is not found or there's
no permission to read it, it raises a `FileHandlingError` exception with an appropriate error
message.
- In the main code block, we call the `read_file` function and handle the
`FileHandlingError` exception, printing out the error message if it occurs.
You can customize the `FileHandlingError` class and the `read_file` function further based
on your specific file handling requirements and error scenarios.
Regular expressions (regex or regexp) in Python are a powerful tool for pattern matching
and searching in strings. The `re` module provides functions for working with regular
expressions in Python. Here's a brief introduction to regular expressions in Python:
Basic Patterns:
import re
pattern = re.compile(r'apple')
result = pattern.match('apple pie')
print(result.group()) # Output: apple
- Character Classes (`[]`): Match any character within the specified set.
pattern = re.compile(r'[aeiou]')
result = pattern.findall('hello world')
print(result) # Output: ['e', 'o', 'o']
pattern = re.compile(r'gr.y')
result = pattern.match('grey')
print(result.group()) # Output: grey
Quantifiers:
pattern = re.compile(r'ab*c')
result = pattern.match('ac')
print(result.group()) # Output: ac
pattern = re.compile(r'ab?c')
result = pattern.match('ac')
print(result.group()) # Output: ac
Anchors:
pattern = re.compile(r'^hello')
result = pattern.match('hello world')
print(result.group()) # Output: hello
pattern = re.compile(r'world$')
result = pattern.search('hello world')
print(result.group()) # Output: world
pattern = re.compile(r'(\d+)-(\d+)-(\d+)')
result = pattern.match('2022-01-01')
print(result.groups()) # Output: ('2022', '01', '01')
Character Escapes:
pattern = re.compile(r'\d+')
result = pattern.match('123')
print(result.group()) # Output: 123
This is just a basic overview of regular expressions in Python. Regular expressions
provide a wide range of features for more complex pattern matching, including character
classes, quantifiers, anchors, groups, and more. The `re` module in Python offers various
functions such as `match()`, `search()`, `findall()`, and `sub()` to work with regular
expressions.
The `match()` function in the `re` module is used to determine if the regular expression
pattern matches the beginning of a string. If a match is found at the start of the string, a
match object is returned; otherwise, it returns `None`. Here's an overview of using the
`match()` function with different types of patterns:
import re
pattern = re.compile(r'apple')
result = pattern.match('apple pie')
if result:
print(result.group()) # Output: apple
else:
print("No match")
Using Groups:
pattern = re.compile(r'(\d+)-(\d+)-(\d+)')
result = pattern.match('2022-01-01')
if result:
print(result.groups()) # Output: ('2022', '01', '01')
else:
print("No match")
Anchors:
pattern = re.compile(r'^hello')
result = pattern.match('hello world')
if result:
print(result.group()) # Output: hello
else:
print("No match")
Using Quantifiers:
pattern = re.compile(r'\d{3}-\d{2}-\d{4}')
result = pattern.match('123-45-6789')
if result:
print(result.group()) # Output: 123-45-6789
else:
print("No match")
Character Classes:
pattern = re.compile(r'[aeiou]')
result = pattern.match('apple')
if result:
print(result.group()) # Output: a
else:
print("No match")
def check_username(username):
pattern = re.compile(r'^[a-zA-Z][a-zA-Z0-9_]*$')
result = pattern.match(username)
if result:
print("Valid username")
else:
print("Invalid username")
These examples illustrate how to use the `match()` function with various types of regular
expression patterns. It's important to check if the result is not `None` before attempting to
access the matched content to avoid `AttributeError` exceptions.
Postfix, Infix, prefix conversion:
Postfix expressions (also known as Reverse Polish Notation) are expressions where the
operators come after their operands. Converting a postfix expression to infix involves
processing the expression from left to right and using a stack to keep track of operands
and operators.
def postfix_to_infix(postfix_expr):
stack = []
return stack[0]
Infix expressions are the standard mathematical expressions with operators between
operands. Converting an infix expression to postfix involves using a stack to maintain
operators and ensuring proper precedence and associativity.
def infix_to_postfix(infix_expr):
stack = []
postfix_expr = []
precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}
while stack:
postfix_expr.append(stack.pop())
return postfix_expr
Converting a prefix expression to infix involves processing the expression from right to left
and using a stack to keep track of operands and operators.
def prefix_to_infix(prefix_expr):
stack = []
return stack[0]
These examples provide a basic understanding of the conversion between postfix, infix,
and prefix expressions. Regular expressions in Python usually involve patterns for
matching strings rather than arithmetic expressions, but the concepts of expression
evaluation and conversion can be adapted to various contexts.
Practice Programs:
1. A proctor of our university wants a student to write a program that calculates the average
of marks scored by her wards in CAT1. She has the details such as name, register number,
mark1, mark2 and mark3 of her proctees. The constraint given by the faculty is that any of
the details must not be altered by mistake. Help the student to develop a Python program.
Below is a simple Python program that takes the details of students (name, register number, mark1,
mark2, mark3) as input, calculates the average marks, and ensures that none of the details is
altered. The program utilizes a class to encapsulate the student details and provides methods for
calculating the average and displaying the details.
Python program:
class Student:
def __init__(self, name, register_number, mark1, mark2, mark3):
self.name = name
self.register_number = register_number
self.mark1 = mark1
self.mark2 = mark2
self.mark3 = mark3
def calculate_average(self):
return (self.mark1 + self.mark2 + self.mark3) / 3
def display_details(self):
print("Student Details:")
print("Name:", self.name)
print("Register Number:", self.register_number)
print("Mark 1:", self.mark1)
print("Mark 2:", self.mark2)
print("Mark 3:", self.mark3)
print("Average Marks:", self.calculate_average())
def main():
# Input student details
name = input("Enter student's name: ")
register_number = input("Enter register number: ")
mark1 = float(input("Enter mark 1: "))
mark2 = float(input("Enter mark 2: "))
mark3 = float(input("Enter mark 3: "))
if __name__ == "__main__":
main()
This program defines a `Student` class with an initializer (`__init__`) to set the student details and
two methods: `calculate_average` for calculating the average marks and `display_details` for
displaying the student details.
In the `main` function, the program takes input for a student's details, creates a `Student` object,
and then displays the details and average marks. The use of a class helps encapsulate the details
and ensures that they are not altered accidentally.
2. Consider the following scenario for finding the number of students who secured centum
in mathematics in their examination. A total of 6 lakhs students appeared for the
examinations and their results are generated automatically and updates to the portal using
file.
Certainly! To find the number of students who secured centum in mathematics, you can
create a Python program that reads the examination results from a file and counts the
number of students with a perfect score in mathematics. Here's a basic example:
Assuming the file format is CSV (Comma-Separated Values) where each line represents
a student with details like name, register number, mathematics marks, and so on. For
simplicity, I'll demonstrate the program with a hypothetical CSV file.
Python program:
import csv
def count_centum_students(file_path):
centum_count = 0
try:
with open(file_path, 'r') as file:
reader = csv.reader(file)
# Assuming the column index for mathematics marks is 2 (adjust as per your file)
math_index = headers.index('Mathematics')
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
except Exception as e:
print(f"Error: {e}")
return centum_count
def main():
file_path = 'examination_results.csv' # Change this to your file path
centum_count = count_centum_students(file_path)
if __name__ == "__main__":
main()
In this example:
- The `count_centum_students` function takes a file path as input, reads the CSV file, and
counts the number of students who secured centum in mathematics.
- The program uses the `csv` module to read the CSV file.
- You need to adjust the file path and column index based on your actual file structure.
Ensure that your CSV file has appropriate headers, and you may need to modify the code
based on the actual structure of your examination results file.