0% found this document useful (0 votes)
8 views8 pages

ue228120

This document contains an assignment for a Python programming course, detailing tasks such as searching for a book using a unique code, reading and customizing email content for multiple recipients, and explaining exception handling and regular expressions in Python. It includes code snippets for each task and examples of exception types and regular expression usage. The document serves as a practical guide for students to apply Python programming concepts.

Uploaded by

pranav1256kam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views8 pages

ue228120

This document contains an assignment for a Python programming course, detailing tasks such as searching for a book using a unique code, reading and customizing email content for multiple recipients, and explaining exception handling and regular expressions in Python. It includes code snippets for each task and examples of exception types and regular expression usage. The document serves as a practical guide for students to apply Python programming concepts.

Uploaded by

pranav1256kam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Assignment - 1

Python Programming
B.E. (IT) 5th Semester
Session: 2024-25

Submitted By:
PRANAV KUMAR
UEM228120
IT- Section (2)

DEPARTMENT OF INFORMATION TECHNOLOGY


University Institute of Engineering & Technology Panjab
University, Chandigarh

Q1. Write a python program for a shop to search a book using a unique number/code.
Ans. CODE:
# Sample book database
books = {
"B001": "The Great Gatsby",
"B002": "1984",
"B003": "To Kill a Mockingbird",
"B004": "The Catcher in the Rye",
"B005": "Pride and Prejudice"
}

# Function to search for a book by code


def search_book(code):
return books.get(code, "Book not found")

# User input for book code code =


input("Enter the book code to search: ")
print(f"Book found: {search_book(code)}")

OUTPUT:

Q2. Write a program using python to:

i. open a file having a list of names (min five names). ii.


open a file having content of the mail (a paragraph). iii.
read all the content of the body of the email (paragraph).
iv. iterate over a list of names and merge with the content of the mail (Hello + Name; +
Content).
v. write the mails to individual files.
Ans. CODE:
import os

# Step 1: Read list of names from


names.txt try: with
open("names.txt", "r") as file:
names = [line.strip() for line in file if line.strip()]
except FileNotFoundError:
print("Error: 'names.txt' file not found.")
exit(1)

# Step 2: Read email content from


content.txt try: with
open("content.txt", "r") as file:
content = file.read().strip()
except FileNotFoundError:
print("Error: 'content.txt' file not found.")
exit(1)

# Step 3: Ensure output directory exists


output_dir = "emails"
os.makedirs(output_dir, exist_ok=True)

# Step 4: Generate and save customized


emails for name in names:
customized_content = f"Hello {name},\n\n{content}"
filename = os.path.join(output_dir, f"{name}_email.txt")
try: with open(filename, "w") as
email_file:
email_file.write(customized_content)
print(f"Email created for {name}: {filename}")
except Exception as e:
print(f"Error writing email for {name}: {e}")

OUTPUT:
Q3. What are exceptions? How is exception handling done in Python?
Ans. In Python, exceptions are errors that occur during the execution of a program, disrupting its
normal flow. Unlike syntax errors, which occur when the code is being parsed, exceptions arise
when the code is running. For example, trying to divide by zero, access an undefined variable, or
open a file that doesn’t exist will all raise exceptions. Without handling, exceptions stop the
program and display an error message.
How is Exception Handling Done in Python?
To handle exceptions gracefully, Python provides the try-except block. By enclosing code in a try
block, you instruct Python to attempt execution and catch any exceptions in the corresponding
except block.
This way, the program can recover or handle issues without crashing.
Here is the structure of exception handling: try:

# Code that may raise an exception


except ExceptionType1: # Handle
ExceptionType1 except ExceptionType2:
# Handle ExceptionType2 else:
# Code to execute if no exception occurs finally:
# Code that will execute no matter what

• try: Contains code that may raise an exception.


• except: Catches and handles specific exceptions. Multiple except blocks can handle different
types of exceptions.
• else: Executes if no exception occurs in the try block.
• finally: Executes regardless of whether an exception was raised. Useful for cleanup
operations, like closing files or releasing resources.
Example:
try:
num = int(input("Enter a number:
")) print("Result:", 10 / num)
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Invalid input! Please enter a number.")
else:
print("No errors encountered.")
finally:
print("Execution
complete.")
OUTPUT-

Types of Exceptions in Python:


Python has many built-in exceptions. Here are some common types:

1. ArithmeticError:
o Raised for numeric errors.
o Example: ZeroDivisionError, OverflowError, FloatingPointError.

2. IndexError:
o Raised when attempting to access an index that is out of range in a sequence (like
lists or tuples).

3. KeyError: o Raised when trying to access a non-existent key in a dictionary.

4. NameError:
o Raised when referencing a variable that hasn’t been defined.
5. ValueError:
o Raised when a function receives an argument of the correct type but inappropriate
value.

6. TypeError:
o Raised when an operation is performed on incompatible types.

7. FileNotFoundError:
o Raised when a file or directory is requested but cannot be found.

8. IOError:
o Raised when an I/O operation fails, like file reading or writing issues.

9. AttributeError: o Raised when an invalid attribute reference or assignment occurs.

10. ImportError: o Raised when an imported module or attribute isn’t found.


11. RuntimeError:
o Raised for a generic error that doesn’t fall into any other category. Often used for
custom errors.

12. StopIteration: o Raised when an iterator has no further items.


Custom Exceptions
You can also define custom exceptions by subclassing Python’s built-in Exception class:
class CustomError(Exception): def __init__(self, message):
self.message = message
try:
raise CustomError("This is a custom error message.") except
CustomError as e: print(e.message)
Custom exceptions make error handling more precise, especially in large applications with specific
requirements.

Q4. What are regular expressions? How regular expressions are used for extracting data.
Ans. Regular Expressions (regex) are sequences of characters that define search patterns. These patterns are
powerful tools for matching and manipulating strings based on specific sequences of characters or rules.
Regular expressions allow users to search for and identify patterns within text, making them invaluable for
data extraction, validation, and formatting.

In Python, the re module provides support for regular expressions, making it possible to apply
complex text matching and extraction operations with ease.

Components of Regular Expressions


Regular expressions consist of literal characters (like letters or digits) and special characters (also
called metacharacters) that form complex patterns. Here are some essential components:
Literal Characters:

• Simple characters that match exactly themselves, like "a", "1", or "cat".
Metacharacters:
Special symbols that modify the meaning of characters or patterns:

• .: Matches any character except a newline.


• ^: Matches the start of a line.
• $: Matches the end of a line.
• *: Matches zero or more repetitions of the preceding character.
• +: Matches one or more repetitions of the preceding character.
• ?: Matches zero or one occurrence of the preceding character.
• {n,m}: Matches between n and m occurrences of the preceding character.
Character Classes:
Groups of characters to match any one of several options:

• [abc]: Matches either "a", "b", or "c".


• [0-9]: Matches any digit from 0 to 9.
• \d: Matches any digit (equivalent to [0-9]).
• \w: Matches any alphanumeric character (equivalent to [a-zA-Z0-9_]).
• \s: Matches any whitespace character (space, tab, newline).
Anchors:
Used to define boundaries within the text:

• ^: Start of the string.


• $: End of the string. • \b: Word boundary.
Grouping and Capturing:
Parentheses ( ) are used to group parts of the pattern and capture the matched subtext for later
use.
How Regular Expressions are Used for Extracting Data
Regular expressions are commonly used in data extraction to locate patterns in text. This could
include finding specific phrases, extracting email addresses, phone numbers, or other structured
data within unstructured text.
1. Importing the re Module
To use regular expressions in Python, import the re module:
2. Basic Functions for Data Extraction
Python’s re module provides several functions for working with regular expressions, especially for
data extraction.

• re.search(pattern, string): Searches for the first match of the pattern in the string and returns
a Match object.
• re.findall(pattern, string): Finds all non-overlapping occurrences of the pattern in the string
and returns them as a list.
• re.finditer(pattern, string): Finds all matches and returns them as an iterator of Match
objects.
• re.sub(pattern, replacement, string): Replaces occurrences of the pattern in the string with a
specified replacement.
3. Examples of Data Extraction Using Regular Expressions
Example 1: Extracting Email Addresses
Suppose we want to extract all email addresses from a block of text.
Code:
import re

text = "Contact us at [email protected] or [email protected] for more


information."
emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b',
text)
print("Extracted Emails:",
emails)

You might also like