Scenario Based – Unit III
1. Student Data Management System
A university maintains student records in a file named students.txt. Each line in the file
contains student details in the format:
Name, Roll Number, Marks
Task:
1. Write a Python program to read the file and display student details.
2. Allow the user to add new student records by taking input and appending it to the file.
# Function to display student details
def display_students():
with open("students.txt", "r") as file:
print("Student Details:\n", file.read())
# Function to add a new student record
def add_student():
name = input("Enter Name: ")
roll_no = input("Enter Roll Number: ")
marks = input("Enter Marks: ")
with open("students.txt", "a") as file:
file.write(f"{name},{roll_no},{marks}\n")
print("Student record added successfully!")
# Example Usage
display_students()
add_student()
display_students()
Output:
Enter Name: Alice
Enter Roll Number: 101
Enter Marks: 85
Student Details:
Alice,101,85
Student record added successfully!
Student Details:
Alice,101,85
2. Log File Analyzer
A log file server.log stores error messages and system activity logs. Each line contains a
timestamp followed by a log message.
Task:
1. Write a Python program to count the number of times the word "ERROR" appears in
the log file.
2. Extract and display only the lines that contain "ERROR" and save them in a new file
error_logs.txt.
3.
def count_error_logs():
count = 0
with open("server.log", "r") as file, open("error_logs.txt", "w") as error_file:
for line in file:
if "ERROR" in line:
count += 1
error_file.write(line)
print(f"Total 'ERROR' occurrences: {count}")
# Example Usage
count_error_logs()
Output:
INFO: System started
ERROR: Connection failed
INFO: User logged in
ERROR: Disk space low
Total 'ERROR' occurrences: 2
3. File Backup System
A company stores daily reports in a text file named report.txt. They need an automated
backup system to ensure data safety.
Task:
1. Write a Python program that creates a backup of report.txt by copying its content into
a new file named backup_report.txt.
2. Implement exception handling to ensure that if the original file is missing, the
program prints an error message.
import shutil
def backup_file():
try:
shutil.copy("report.txt", "backup_report.txt")
print("Backup successful!")
except FileNotFoundError:
print("Error: report.txt not found!")
# Example Usage
backup_file()
Output:
Backup successful!
4. Cleaning a Data File
A file named data.txt contains a mix of text and empty lines. The company needs a cleaned
version of the file without blank lines.
Task:
1. Write a Python program that reads the file, removes all blank lines, and saves the
cleaned data back to data_cleaned.txt.
def clean_file():
with open("data.txt", "r") as file:
lines = file.readlines()
with open("data_cleaned.txt", "w") as file:
file.writelines([line for line in lines if line.strip()])
print("File cleaned successfully!")
# Example Usage
clean_file()
Output:
data.txt:
Hello World
Python is great
This is a test
End of file
data_cleaned.txt
Hello World
Python is great
This is a test
End of file
5. Config File Updater
A software application stores its settings in a file named config.txt. One of the settings is
"mode=debug", which needs to be changed to "mode=production".
Task:
1. Write a Python script to search for "mode=debug" in config.txt and replace it with
"mode=production".
2. Ensure that the changes are saved in the file.
def update_config():
with open("config.txt", "r") as file:
content = file.read()
content = content.replace("mode=debug", "mode=production")
with open("config.txt", "w") as file:
file.write(content)
print("Configuration updated!")
# Example Usage
update_config()
Output:
Configuration updated!
(The file will change "mode=debug" to "mode=production".)
6. File Merging Utility
Two files, file1.txt and file2.txt, contain text data. You need to merge both files into a single
file named merged.txt.
Task:
1. Write a Python program that reads the contents of file1.txt and file2.txt, merges them,
and writes the combined content to merged.txt.
def merge_files():
with open("file1.txt", "r") as f1, open("file2.txt", "r") as f2, open("merged.txt", "w") as mf:
mf.write(f1.read() + "\n" + f2.read())
print("Files merged successfully!")
# Example Usage
merge_files()
Output:
Files merged successfully!
(The merged.txt file will contain combined content.)
7. Secure File Reader with Exception Handling
A function needs to read and display the content of a file. However, the program should
handle situations where:
The file does not exist (FileNotFoundError)
The user lacks the required permissions (PermissionError)
Task:
1. Write a Python program to read and display the contents of important.txt while
handling the exceptions gracefully.
def read_secure_file():
try:
with open("important.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("Error: File not found.")
except PermissionError:
print("Error: Permission denied.")
# Example Usage
read_secure_file()
Output:
(Displays the file content)
If file exists
If file is missing
Error: File not found.
8. Analyzing Sales Data from a CSV File
A CSV file named sales.csv contains sales data with columns:
Product Name, Quantity Sold, Revenue
Task:
1. Write a Python program to read the file and calculate the total revenue for each
product.
2. Display the sales summary in a structured format.
import csv
def generate_sales_report():
sales_summary = {}
with open("sales.csv", "r") as file:
reader = csv.reader(file)
next(reader) # Skip header
for row in reader:
product, quantity, revenue = row[0], int(row[1]), float(row[2])
sales_summary[product] = sales_summary.get(product, 0) + revenue
for product, total_revenue in sales_summary.items():
print(f"Product: {product}, Total Revenue: ${total_revenue:.2f}")
# Example Usage
generate_sales_report()
Output:
sales.csv
Product,Quantity,Revenue
Laptop,2,1000
Phone,5,500
Laptop,1,500
Product: Laptop, Total Revenue: $1500.00
Product: Phone, Total Revenue: $500.00
9. Searching for a Word in a File
A text file named document.txt contains paragraphs of text. You need to find how many
times the word "Python" appears in the file.
Task:
1. Write a Python program to count the occurrences of the word "Python" in
document.txt.
2. Display the result to the user.
def count_word_occurrences(filename, word):
with open(filename, "r") as file:
content = file.read().lower()
return content.count(word.lower())
# Example Usage
print("Occurrences of 'Python':", count_word_occurrences("document.txt", "Python"))
Output:
document.txt
Python is a programming language. Many developers use Python for AI and ML.
Occurrences of 'Python': 2
10. Deleting Specific Lines from a File
A file named records.txt contains a list of employee records, one per line. You need to delete
a record if it contains the employee ID entered by the user.
Task:
1. Write a Python program that takes an Employee ID as input and deletes the
corresponding line from records.txt.
2. Save the updated data back to the file.
def delete_employee_record(emp_id):
with open("records.txt", "r") as file:
lines = file.readlines()
with open("records.txt", "w") as file:
for line in lines:
if emp_id not in line:
file.write(line)
print(f"Record with Employee ID {emp_id} deleted.")
# Example Usage
delete_employee_record("102")
Output:
records.txt
Alice,101,HR
Bob,102,Finance
Charlie,103,Engineering
(records.txt will no longer have the line with 102.)
Record with Employee ID 102 deleted.
11. Iterators: Creating a Custom Iterator
A company wants to implement a custom iterator to generate even numbers up to a given
limit.
class EvenNumbers:
def __init__(self, max_num):
self.max_num = max_num
self.num = 0
def __iter__(self):
return self
def __next__(self):
if self.num > self.max_num:
raise StopIteration
even = self.num
self.num += 2
return even
# Example Usage
evens = EvenNumbers(10)
for num in evens:
print(num, end=" ")
Output:
0 2 4 6 8 10
12. Exception Handling: Handling Multiple Exceptions
A user is prompted to enter two numbers, but they may enter invalid values.
def divide_numbers():
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
result = a / b
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Invalid input. Please enter numbers only.")
# Example Usage
divide_numbers()
Output:
Enter first number: 10
Enter second number: 0
Error: Division by zero is not allowed.
13. Regular Expressions: Extract Email Addresses
A company stores customer emails in a file and needs to extract them using regular
expressions.
import re
def extract_emails(text):
pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
return re.findall(pattern, text)
# Sample Input
sample_text = "Contact us at [email protected] or [email protected]."
# Example Usage
emails = extract_emails(sample_text)
print("Extracted Emails:", emails)
Output:
Extracted Emails: ['[email protected]', '[email protected]']
14. Functions and Modules: Math Operations Module
Create a Python module math_operations.py that contains functions for basic operations (add,
subtract, multiply, divide).
math_operations.py (Module)
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Error: Division by zero"
return a / b
Main Program:
import math_operations
a, b = 10, 5
print("Addition:", math_operations.add(a, b))
print("Subtraction:", math_operations.subtract(a, b))
print("Multiplication:", math_operations.multiply(a, b))
print("Division:", math_operations.divide(a, b))
Output:
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
15. Validate Password Strength
Ensure a password contains at least one uppercase letter, one lowercase letter, one digit, and
one special character, and is at least 8 characters long.
import re
passwords = ["Strong@123", "weakpass", "P@ssword1", "NoSpecialChar1", "12345678"]
pattern = r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$'
for pwd in passwords:
if re.match(pattern, pwd):
print(f"Strong Password: {pwd}")
else:
print(f"Weak Password: {pwd}")
Output:
Strong Password: Strong@123
Weak Password: weakpass
Strong Password: P@ssword1
Weak Password: NoSpecialChar1
Weak Password: 12345678
16. Extract Dates from a Text
Extract all dates in DD-MM-YYYY or DD/MM/YYYY format from a string.
import re
text = "John's birthday is on 12-05-1998, and Lisa's is on 23/09/2001. Another date is 01-01-
2020."
pattern = r'\b\d{2}[-/]\d{2}[-/]\d{4}\b'
dates = re.findall(pattern, text)
print("Extracted Dates:", dates)
Output:
Extracted Dates: ['12-05-1998', '23/09/2001', '01-01-2020']
17. Find All Hashtags in a Tweet
Extract all hashtags (#hashtag) from a tweet.
import re
tweet = "Loving the #Python programming! #Coding #DeveloperLife #Regex"
pattern = r'#\w+'
hashtags = re.findall(pattern, tweet)
print("Extracted Hashtags:", hashtags)
Output:
Extracted Hashtags: ['#Python', '#Coding', '#DeveloperLife', '#Regex']
18. Mask Credit Card Numbers
Replace all credit card numbers (16 digits) with XXXX-XXXX-XXXX-####, keeping only
the last 4 digits visible.
import re
text = "My old card number was 1234-5678-9876-5432 and new one is 4321-8765-6789-
1234."
pattern = r'\d{4}-\d{4}-\d{4}-(\d{4})'
masked_text = re.sub(pattern, r'XXXX-XXXX-XXXX-\1', text)
print("Masked Text:", masked_text)
Output:
Masked Text: My old card number was XXXX-XXXX-XXXX-5432 and new one is XXXX-
XXXX-XXXX-1234.
19. Extract URLs from a Webpage Content
Given an HTML text, extract all URLs.
import re
html = '<a href="https://example.com">Click here</a> and visit <a
href="http://testsite.com">this site</a>.'
pattern = r'https?://[a-zA-Z0-9./-]+'
urls = re.findall(pattern, html)
print("Extracted URLs:", urls)
Output:
Extracted URLs: ['https://example.com', 'http://testsite.com']
20. Validate Indian Vehicle Registration Numbers
Check if a given vehicle registration number is valid (e.g., KA-05-MD-1234).
import re
vehicles = ["KA-05-MD-1234", "MH-12-XY-9876", "123-ABC-9876", "TN-10-ZX-543"]
pattern = r'^[A-Z]{2}-\d{2}-[A-Z]{2}-\d{4}$'
for vehicle in vehicles:
if re.match(pattern, vehicle):
print(f"Valid Vehicle Number: {vehicle}")
else:
print(f"Invalid Vehicle Number: {vehicle}")
Output:
Valid Vehicle Number: KA-05-MD-1234
Valid Vehicle Number: MH-12-XY-9876
Invalid Vehicle Number: 123-ABC-9876
Invalid Vehicle Number: TN-10-ZX-543
21. Find Words Starting with Capital Letters
Extract all words that start with a capital letter from a sentence.
import re
text = "Alice and Bob went to New York for a Python Conference."
pattern = r'\b[A-Z][a-z]*\b'
capital_words = re.findall(pattern, text)
print("Words Starting with Capital Letters:", capital_words)
Output:
Words Starting with Capital Letters: ['Alice', 'Bob', 'New', 'York', 'Python', 'Conference']
22. Extract Domain Names from Email Addresses
Extract only the domain names from a list of emails.
import re
pattern = r'@([\w.-]+)'
domains = re.findall(pattern, ' '.join(emails))
print("Extracted Domains:", domains)
Output:
Extracted Domains: ['gmail.com', 'yahoo.com', 'mywebsite.org']
23. Custom Iterator for Even Numbers
Create an iterator that generates even numbers up to a given limit.
class EvenNumbers:
def __init__(self, max_value):
self.max_value = max_value
self.current = 0
def __iter__(self):
return self
def __next__(self):
if self.current > self.max_value:
raise StopIteration
else:
even = self.current
self.current += 2
return even
even_iter = EvenNumbers(10)
for num in even_iter:
print(num, end=" ")
Output:
0 2 4 6 8 10
24. Reverse String Iterator
Implement an iterator that iterates over a string in reverse order.
class ReverseString:
def __init__(self, string):
self.string = string
self.index = len(string)
def __iter__(self):
return self
def __next__(self):
if self.index == 0:
raise StopIteration
self.index -= 1
return self.string[self.index]
rev_iter = ReverseString("Python")
for char in rev_iter:
print(char, end=" ")
Output:
nohtyP
25. Fibonacci Sequence Iterator
Create an iterator that generates Fibonacci numbers up to a given limit.
class Fibonacci:
def __init__(self, max_terms):
self.max_terms = max_terms
self.a, self.b = 0, 1
self.count = 0
def __iter__(self):
return self
def __next__(self):
if self.count >= self.max_terms:
raise StopIteration
self.count += 1
fib = self.a
self.a, self.b = self.b, self.a + self.b
return fib
fib_iter = Fibonacci(7)
for num in fib_iter:
print(num, end=" ")
Output:
0112358
26. Custom Range Iterator
Create an iterator similar to Python’s built-in range() function.
class CustomRange:
def __init__(self, start, end, step=1):
self.current = start
self.end = end
self.step = step
def __iter__(self):
return self
def __next__(self):
if self.current >= self.end:
raise StopIteration
value = self.current
self.current += self.step
return value
for num in CustomRange(1, 10, 2):
print(num, end=" ")
Output:
13579
27. Cycle Through a List
Implement an iterator that infinitely cycles through a given list.
from itertools import cycle
colors = ["Red", "Green", "Blue"]
color_cycle = cycle(colors)
for i in range(6):
print(next(color_cycle), end=" ")
Output:
Red Green Blue Red Green Blue
28. Count Down Iterator
Implement an iterator that counts down from a given number to zero.
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current < 0:
raise StopIteration
value = self.current
self.current -= 1
return value
for num in Countdown(5):
print(num, end=" ")
Output:
543210
29. Square Number Iterator
Create an iterator that returns the squares of numbers from 1 to n.
class SquareNumbers:
def __init__(self, max_value):
self.current = 1
self.max_value = max_value
def __iter__(self):
return self
def __next__(self):
if self.current > self.max_value:
raise StopIteration
square = self.current ** 2
self.current += 1
return square
for num in SquareNumbers(5):
print(num, end=" ")
Output:
1 4 9 16 25
30. Iterate Over a File Line by Line
Read a file line by line using an iterator.
class FileIterator:
def __init__(self, filename):
self.file = open(filename, "r")
def __iter__(self):
return self
def __next__(self):
line = self.file.readline()
if not line:
self.file.close()
raise StopIteration
return line.strip()
# Assuming a file named "sample.txt" exists
for line in FileIterator("sample.txt"):
print(line)
Output (assuming sample.txt contains):
Hello, World!
Python is great.
Iterators are useful.
31. Custom Prime Number Iterator
A cybersecurity company is designing a simple encryption system that needs prime numbers
for key generation in cryptographic applications. Since prime numbers play a crucial role in
RSA encryption, the system should have an iterator that generates prime numbers up to a
given limit. Create an iterator that generates prime numbers up to a given limit.
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
class PrimeNumbers:
def __init__(self, max_value):
self.current = 1
self.max_value = max_value
def __iter__(self):
return self
def __next__(self):
self.current += 1
while self.current <= self.max_value and not is_prime(self.current):
self.current += 1
if self.current > self.max_value:
raise StopIteration
return self.current
for prime in PrimeNumbers(20):
print(prime, end=" ")
Output:
2 3 5 7 11 13 17 19
32. Alternating Upper and Lowercase Words
Imagine you are designing a text-banner generator for a digital advertisement. The banner
alternates between uppercase and lowercase words to grab attention in a stylish and engaging
way. Implement an iterator that alternates between uppercase and lowercase versions of
words from a list.
class AlternateCase:
def __init__(self, words):
self.words = words
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index >= len(self.words):
raise StopIteration
word = self.words[self.index]
if self.index % 2 == 0:
result = word.upper()
else:
result = word.lower()
self.index += 1
return result
words = ["hello", "world", "python", "iterators", "example"]
for word in AlternateCase(words):
print(word, end=" ")
Output:
HELLO world PYTHON iterators EXAMPLE