Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
17 views

Python Notes_unit 4 (1)

This document covers Python programming concepts related to file handling, user-defined exceptions, and regular expressions. It includes practical examples of file operations, custom exception handling, and regex pattern matching, as well as conversion between postfix, infix, and prefix expressions. Additionally, it presents practice programs for calculating average marks and counting students with perfect scores in mathematics from a file.

Uploaded by

kichanandu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Python Notes_unit 4 (1)

This document covers Python programming concepts related to file handling, user-defined exceptions, and regular expressions. It includes practical examples of file operations, custom exception handling, and regex pattern matching, as well as conversion between postfix, infix, and prefix expressions. Additionally, it presents practice programs for calculating average marks and counting students with perfect scores in mathematics from a file.

Uploaded by

kichanandu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

S11BLH22 PYTHON PROGRAMMING

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.

Files and File Handling Operations in Python:

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 reading


file_path = 'example.txt'
file = open(file_path, 'r')

# 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')

Reading from a File:

1. Reading the Entire File:

content = file.read()
print(content)

2. Reading Line by Line:


for line in file:
print(line)

3. Reading Lines into a List:

lines = file.readlines()
print(lines)

Writing to a File:

1. Writing a String:

file.write('Hello, this is a sample text.')

2. Writing Multiple Lines:

lines_to_write = ['Line 1\n', 'Line 2\n', 'Line 3\n']


file.writelines(lines_to_write)

Appending to a File:

file = open(file_path, 'a')


file.write('\nAdditional text appended.')
file.close()

Using the `with` Statement:

The `with` statement ensures proper resource management. It automatically closes the
file when the block is exited.

with open(file_path, 'r') as file:


content = file.read()
print(content)
# File is automatically closed after the 'with' block

Seeking in a File:

The `seek()` method is used to change the file position to a specified byte.

file.seek(0) # Move to the beginning of the file


Closing a File:

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.

User Defined Exceptions in Python:

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:

# Define a custom exception class for file handling errors


class FileHandlingError(Exception):
def __init__(self, message="File handling error occurred."):
self.message = message
super().__init__(self.message)

# Example of a function that reads data from a file


def read_file(file_name):
try:
with open(file_name, 'r') as file:
data = file.read()
return data
except FileNotFoundError:
raise FileHandlingError(f"File '{file_name}' not found.")
except PermissionError:
raise FileHandlingError(f"No permission to read file '{file_name}'.")

# Example of using the custom file handling exception


try:
file_content = read_file('example.txt')
print(file_content)
except FileHandlingError as e:
print(f"File handling error: {e}")

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) in Python:

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:

- Literal Characters: Match the exact characters specified.

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']

- Dot (`.`): Match any character except a newline.

pattern = re.compile(r'gr.y')
result = pattern.match('grey')
print(result.group()) # Output: grey

Quantifiers:

- `*`: Match 0 or more occurrences of the preceding character.

pattern = re.compile(r'ab*c')
result = pattern.match('ac')
print(result.group()) # Output: ac

- `+`: Match 1 or more occurrences of the preceding character.


pattern = re.compile(r'ab+c')
result = pattern.match('abc')
print(result.group()) # Output: abc

- `?`: Match 0 or 1 occurrence of the preceding character.

pattern = re.compile(r'ab?c')
result = pattern.match('ac')
print(result.group()) # Output: ac

Anchors:

- `^`: Match the start of the string.

pattern = re.compile(r'^hello')
result = pattern.match('hello world')
print(result.group()) # Output: hello

- `$`: Match the end of the string.

pattern = re.compile(r'world$')
result = pattern.search('hello world')
print(result.group()) # Output: world

Groups and Capturing:

- Use parentheses `()` to create groups and capture matched portions.

pattern = re.compile(r'(\d+)-(\d+)-(\d+)')
result = pattern.match('2022-01-01')
print(result.groups()) # Output: ('2022', '01', '01')

Character Escapes:

- Use backslashes `\` to escape special characters.

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.

Types using Match function:

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:

Basic Match Example:

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")

Using `match()` with Conditions:

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")

check_username('john_doe') # Output: Valid username


check_username('123user') # Output: 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 to Infix 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.

Here's a simple example in Python:

def postfix_to_infix(postfix_expr):
stack = []

for token in postfix_expr:


if token.isalnum(): # Operand
stack.append(token)
else: # Operator
operand2 = stack.pop()
operand1 = stack.pop()
stack.append(f'({operand1} {token} {operand2})')

return stack[0]

postfix_expr = ['2', '3', '+', '4', '*']


infix_expr = postfix_to_infix(postfix_expr)
print("Postfix Expression:", ''.join(postfix_expr))
print("Infix Expression:", infix_expr)

Infix to Postfix Conversion:

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}

for token in infix_expr:


if token.isalnum(): # Operand
postfix_expr.append(token)
elif token == '(': # Left parenthesis
stack.append(token)
elif token == ')': # Right parenthesis
while stack and stack[-1] != '(':
postfix_expr.append(stack.pop())
stack.pop() # Discard the '('
else: # Operator
while stack and precedence.get(stack[-1], 0) >= precedence.get(token, 0):
postfix_expr.append(stack.pop())
stack.append(token)

while stack:
postfix_expr.append(stack.pop())

return postfix_expr

infix_expr = ['(', '2', '+', '3', ')', '*', '4']


postfix_expr = infix_to_postfix(infix_expr)
print("Infix Expression:", ''.join(infix_expr))
print("Postfix Expression:", ''.join(postfix_expr))

Prefix to Infix Conversion:

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 = []

for token in reversed(prefix_expr):


if token.isalnum(): # Operand
stack.append(token)
else: # Operator
operand1 = stack.pop()
operand2 = stack.pop()
stack.append(f'({operand1} {token} {operand2})')

return stack[0]

prefix_expr = ['*', '+', '2', '3', '4']


infix_expr = prefix_to_infix(prefix_expr)
print("Prefix Expression:", ''.join(prefix_expr))
print("Infix Expression:", infix_expr)

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: "))

# Create a Student object


student = Student(name, register_number, mark1, mark2, mark3)

# Display student details and average marks


student.display_details()

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 first row contains headers


headers = next(reader)

# Assuming the column index for mathematics marks is 2 (adjust as per your file)
math_index = headers.index('Mathematics')

for row in reader:


# Assuming the mathematics marks are integers
math_marks = int(row[math_index])

# Check if the student secured centum in mathematics (marks = 100)


if math_marks == 100:
centum_count += 1

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)

print(f"Number of students who secured centum in mathematics: {centum_count}")

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.

You might also like