Scenario Based - Unit 3
Scenario Based - Unit 3
# 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
# 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!
# 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
def update_config():
with open("config.txt", "r") as file:
content = file.read()
print("Configuration updated!")
# Example Usage
update_config()
Output:
Configuration updated!
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!
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 = {}
# Example Usage
generate_sales_report()
Output:
sales.csv
Product,Quantity,Revenue
Laptop,2,1000
Phone,5,500
Laptop,1,500
# 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
def delete_employee_record(emp_id):
with open("records.txt", "r") as file:
lines = file.readlines()
# Example Usage
delete_employee_record("102")
Output:
records.txt
Alice,101,HR
Bob,102,Finance
Charlie,103,Engineering
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
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
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]']
math_operations.py (Module)
def add(a, b):
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
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
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'
Output:
Extracted Dates: ['12-05-1998', '23/09/2001', '01-01-2020']
import re
tweet = "Loving the #Python programming! #Coding #DeveloperLife #Regex"
pattern = r'#\w+'
Output:
Extracted Hashtags: ['#Python', '#Coding', '#DeveloperLife', '#Regex']
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})'
Output:
Masked Text: My old card number was XXXX-XXXX-XXXX-5432 and new one is XXXX-
XXXX-XXXX-1234.
Output:
Extracted URLs: ['https://example.com', 'http://testsite.com']
import re
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'
Output:
Words Starting with Capital Letters: ['Alice', 'Bob', 'New', 'York', 'Python', 'Conference']
import re
Output:
Extracted Domains: ['gmail.com', 'yahoo.com', 'mywebsite.org']
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
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
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
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
Output:
13579
27. Cycle Through a List
Implement an iterator that infinitely cycles through a given list.
for i in range(6):
print(next(color_cycle), end=" ")
Output:
Red Green Blue Red Green Blue
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
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
Output:
1 4 9 16 25
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()
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
Output:
2 3 5 7 11 13 17 19
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
Output:
HELLO world PYTHON iterators EXAMPLE