Here are the Python programs for the questions provided in your document.
Program Solutions
Q1: Menu-Driven Calculator
This program uses specific functions for each operation and handles potential ValueError or
ZeroDivisionError.
Python
def add(a, b): return a + b
def sub(a, b): return a - b
def mul(a, b): return a * b
def div(a, b): return a / b
def f_div(a, b): return a // b
while True:
print("\n1. Add 2. Sub 3. Mul 4. Div 5. Floor Div 6. Exit")
choice = input("Enter choice: ")
if choice == '6': break
try:
n1 = float(input("Enter first number: "))
n2 = float(input("Enter second number: "))
if choice == '1': print("Result:", add(n1, n2))
elif choice == '2': print("Result:", sub(n1, n2))
elif choice == '3': print("Result:", mul(n1, n2))
elif choice == '4': print("Result:", div(n1, n2))
elif choice == '5': print("Result:", f_div(n1, n2))
else: print("Invalid Choice")
except ValueError:
print("Error: Please enter numeric values.")
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
Q2: Number Analysis (Logical Operators)
Checks if numbers are positive/negative, odd/even, and compares them.
Python
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
for n in [num1, num2]:
status = "Positive" if n > 0 else "Negative" if n < 0 else "Zero"
parity = "Even" if n % 2 == 0 else "Odd"
print(f"Number {n}: {status} and {parity}")
if num1 > num2:
print(f"{num1} is greater than {num2}")
elif num1 < num2:
print(f"{num1} is smaller than {num2}")
else:
print("Both numbers are equal")
Q3: Factorial and Leap Year Check
Calculates factorial and treats the result as a year to check for leap year status.
Python
def get_factorial(n):
res = 1
for i in range(1, n + 1):
res *= i
return res
num = int(input("Enter a positive integer: "))
fact = get_factorial(num)
print("Factorial:", fact)
if (fact % 4 == 0 and fact % 100 != 0) or (fact % 400 == 0):
print(fact, "is a leap year")
else:
print(fact, "is not a leap year")
Q4: Password Strength Analyzer
Uses string methods to categorize password strength.
Python
import string
pwd = input("Enter password: ")
l = len(pwd)
u = sum(1 for c in pwd if [Link]())
low = sum(1 for c in pwd if [Link]())
d = sum(1 for c in pwd if [Link]())
s = sum(1 for c in pwd if c in [Link])
strength = "Weak"
if l >= 8 and u > 0 and low > 0 and d > 0 and s > 0:
strength = "Strong"
elif l >= 6:
strength = "Medium"
print(f"Length: {l}, Upper: {u}, Lower: {low}, Digits: {d}, Special: {s}")
print(f"Strength: {strength}")
Q5: String Slicing and Methods
Performs various operations only if the string length is between 20 and 30.
Python
txt = input("Enter a string (20-30 chars): ")
if 20 <= len(txt) <= 30:
print("First 5:", txt[:5])
print("Reversed:", txt[::-1])
print("From 7th:", txt[6:])
print("Up to index 9:", txt[:10])
print("Every 2nd char:", txt[::2])
print("Upper:", [Link]())
print("Lower:", [Link]())
print("Replace 'a' with '@':", [Link]('a', '@'))
print("Count 'e':", [Link]('e'))
print("Split:", [Link]())
print("Length:", len(txt))
else:
print("Error: String length must be between 20 and 30.")
Q6 & Q11: File Handling & Word Frequency
This handles reading/writing with exceptions and counts word frequency.
+1
Python
file_name = "[Link]"
content = "Python is simple, Python is powerful, Python is everywhere..."
try:
# Writing to file
with open(file_name, "w") as f:
[Link](content)
# Reading and Counting Frequency
with open(file_name, "r") as f:
data = [Link]().lower().replace(',', '').split()
freq = {}
for word in data:
freq[word] = [Link](word, 0) + 1
print("Word Frequency:", freq)
except FileNotFoundError:
print("Error: File not found.")
except Exception as e:
print(f"An error occurred: {e}")
Q7 & Q12: Regular Expressions
Extracts emails/phones and performs cleaning/masking.
+1
Python
import re
text = "Contact me at user@[Link] or +91-9876543210. Also admin@[Link]."
# Q7: Extraction
emails = [Link](r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', text)
phones = [Link](r'\+?\d{1,3}[-.\s]?\d{10}', text)
print("Emails:", emails)
print("Phones:", phones)
# Q12: Cleaning/Masking
cleaned = [Link](r'\+?\d{1,3}[-.\s]?\d{10}', "[PHONE MASKED]", text)
cleaned = [Link](r'[a-zA-Z0-9._%+-]+(?=@)', "XXXX", cleaned) # Mask email username
print("Cleaned Data:", cleaned)
Q9: Sales Data Processing
Filters a mixed list for positive integers and performs statistics.
Python
raw_data = [100, -20, "abc", 50, 300, None, 150, 50]
valid_sales = []
invalid_count = 0
for item in raw_data:
if isinstance(item, int) and item > 0:
valid_sales.append(item)
else:
invalid_count += 1
if valid_sales:
print("Sum:", sum(valid_sales))
print("Average:", sum(valid_sales)/len(valid_sales))
print("Sorted:", sorted(valid_sales))
print("Unique:", list(set(valid_sales)))
print("Min:", min(valid_sales), "Max:", max(valid_sales))
print("Invalid entries ignored:", invalid_count)
Q10: Employee Report (Tuples)
Processes employee data using tuple unpacking and a tax function.
Python
employees = (
("Alice", "E001", 50000),
("Bob", "E002", 60000),
("Charlie", "E003", 45000)
)
def calc_net(basic):
tax = basic * 0.10
ins = basic * 0.05
net = basic - tax - ins
return tax, ins, net
print(f"{'Name':<10} {'ID':<10} {'Basic':<10} {'Tax':<10} {'Ins':<10} {'Net':<10}")
for emp in employees:
name, eid, basic = emp # Unpacking
t, i, n = calc_net(basic)
print(f"{name:<10} {eid:<10} {basic:<10} {t:<10} {i:<10} {n:<10}")
Q13: CSV Processing
Reads a CSV and extracts data.
Python
import csv
# Create a dummy CSV for demonstration
with open('[Link]', 'w', newline='') as f:
writer = [Link](f)
[Link](["ID", "Item", "Price"])
[Link](["1", "Laptop", "1000"])
# Extracting information
with open('[Link]', 'r') as f:
reader = [Link](f)
for row in reader:
print(f"Item: {row['Item']}, Price: {row['Price']}")
Would you like me to explain the logic behind any specific program or provide the answers to
the Viva questions?