Q 11 a) Demonstrate the different ways of creating dictionary objects
with suitable example programs.
dict1 = dict()
dict2 = {}
dict3 = {'a': 1, 'b': 2}
print(dict1)
print(dict2)
print(dict3)
output
b) Demonstrate the following functions/methods which operate on
dictionary in Python with suitable examples:
• dict()
• len()
• clear()
• get()
• pop()
• popitem()
• keys()
• values()
• items()
• copy()
• update()
dict1 = dict()
dict2 = {}
dict3 = {'a': 1, 'b': 2}
print("Length of dict3:", len(dict3))
dict3.clear()
print("Cleared dict3:", dict3)
dict3 = {'a': 1, 'b': 2}
print("Value for key 'a':", dict3.get('a'))
popped_value = dict3.pop('a')
print("Popped value:", popped_value)
print("dict3 after pop:", dict3)
item = dict3.popitem() # Returns the last inserted key-value pair
print("Popped item:", item)
keys = dict3.keys()
print("Keys in dict3:", keys)
values = dict3.values()
print("Values in dict3:", values)
items = dict3.items()
print("Items in dict3:", items)
copy_dict = dict3.copy()
print("Copy of dict3:", copy_dict)
dict3.update({'c': 3})
print("dict3 after update:", dict3)
output
Q 12. a) Repeatedly ask the user to enter a team name and how many
games the team has won and how many they lost. Store this
information in a dictionary where the keys are the team names and the
values are lists of the form [wins, losses].
(i) Using the dictionary created above, allow the user to enter a team
name and print out the team’s winning percentage.
(ii) Using the dictionary, create a list whose entries are the number of
wins of each team.
(iii) Using the dictionary, create a list of all those teams that have
winning records.
# a) Dictionary to store team records
team_records = {}
# Input teams and their records
while True:
team = input("Enter team name (or 'exit' to stop): ")
if team.lower() == 'exit':
break
wins = int(input(f"Enter number of wins for {team}: "))
losses = int(input(f"Enter number of losses for {team}: "))
team_records[team] = [wins, losses]
# i) Calculate winning percentage
team_name = input("Enter a team name to calculate winning percentage: ")
if team_name in team_records:
wins, losses = team_records[team_name]
winning_percentage = wins / (wins + losses) * 100
print(f"{team_name} Winning Percentage: {winning_percentage:.2f}%")
# ii) List of wins for each team
wins_list = {team: record[0] for team, record in team_records.items()}
print("Wins by each team:", wins_list)
# iii) List of teams with winning records
winning_teams = [team for team, record in team_records.items() if record[0] > record[1]]
print("Teams with winning records:", winning_teams)
output
b) Write a program that repeatedly asks the user to enter product
names and prices. Store all of these in a dictionary whose keys are the
product names and whose values are the prices. When the user is done
entering products and prices, allow them to repeatedly enter a product
name and print the corresponding price or a message if the product is
not in the dictionary.
products = {}
while True:
product = input("Enter product name (or 'exit' to stop): ")
if product.lower() == 'exit':
break
price = float(input(f"Enter price for {product}: "))
products[product] = price
while True:
search_product = input("Enter a product to get its price (or 'exit' to stop): ")
if search_product.lower() == 'exit':
break
if search_product in products:
print(f"Price for {search_product}: {products[search_product]}")
else:
print("Product not found.")
output
c) Create a dictionary whose keys are month names and whose values
are the number of days in the corresponding months.
(i) Ask the user to enter a month name and use the dictionary to tell
how many days are in the month.
(ii) Print out all of the keys in alphabetical order.
months = {
'January': 31,
'February': 28,
'March': 31,
'April': 30,
'May': 31,
'June': 30,
'July': 31,
'August': 31,
'September': 30,
'October': 31,
'November': 30,
'December': 31
month_name = input("Enter a month name: ")
days = months.get(month_name)
if days:
print(f"Number of days in {month_name}: {days}")
else:
print("Month not found.")
sorted_months = sorted(months.keys())
print("Months in alphabetical order:", sorted_months)
output
Q 13. a) Demonstrate the different ways of creating set objects with
suitable example programs.
set1 = {1, 2, 3}
set2 = set([3, 4, 5])
set3 = set((5, 6, 7))
print("Set1:", set1)
print("Set2:", set2)
print("Set3:", set3)
output
b) Demonstrate the following functions/methods which operate on sets
in Python with suitable examples:
• i) add()
• ii) update()
• iii) copy()
• iv) pop()
• v) remove()
• vi) discard()
• vii) clear()
• viii) union()
• ix) intersection()
• x) difference()
my_set = {1, 2, 3}
my_set.add(4)
my_set.update([5, 6])
popped_value = my_set.pop()
my_set.remove(5)
my_set.discard(10)
my_set.clear()
set_a = {1, 2}
set_b = {3, 4}
union_set = set_a.union(set_b)
difference_set = set_a.difference(set_b)
print("Modified Set:", my_set)
print("Popped Value:", popped_value)
print("Union of Set A and Set B:", union_set)
print("Difference of Set A from Set B:", difference_set)
output
Q 14. a) Python program to perform read and write operations on
a file.
with open('example.txt', 'w') as f:
f.write("Hello, World!\n")
with open('example.txt', 'r') as f:
content = f.read()
print(content)
output
b) Python program to copy the contents of a file to another file.
import shutil
shutil.copy('example.txt', 'copy_example.txt')
output
c) Python program to count the frequency of characters in a given
file.
from collections import Counter
with open('example.txt', 'r') as f:
content = f.read()
frequency = Counter(content)
print(frequency)
output
d) Python program to print each line of a file in reverse order.
with open('example.txt', 'r') as f:
lines = f.readlines()
for line in reversed(lines):
print(line.strip())
output
e) Python program to compute the number of characters, words,
and lines in a file.
with open('example.txt', 'r') as f:
content = f.read()
num_chars = len(content)
num_words = len(content.split())
num_lines = len(content.splitlines())
print(f"Characters: {num_chars}, Words: {num_words}, Lines: {num_lines}")
output
Q 15. a) Write a Python program that takes two integer inputs from
the user and divides them. Handle division by zero and invalid
input exceptions.
try:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Invalid input. Please enter integers.")
output
b) Create a program that reads from a file specified by the user. If
the file does not exist, catch the FileNotFoundError and display a
message. Also, handle any other potential I/O errors.
try:
with open('nonexistent_file.txt', 'r') as f:
content = f.read()
except FileNotFoundError:
print("Error: The file does not exist.")
except Exception as e:
print("An error occurred:", e)
output
c) Write a Python program where you define a custom exception
that raises an error when the user enters an invalid age (negative
age). Catch this exception and print a message if the age is
invalid.
class NegativeAgeError(Exception):
pass
try:
age = int(input("Enter your age: "))
if age < 0:
raise NegativeAgeError("Age cannot be negative.")
except NegativeAgeError as e:
print(e)
output
d) Implement a Python program that asks the user for two
numbers and attempts to divide them. Use try, except, and else
blocks to handle exceptions and print a message if there are no
errors.
try:
try:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Inner Error: Division by zero is not allowed.")
except ValueError:
print("Outer Error: Invalid input.")
output
e) Write a Python program that contains nested try-except blocks.
Inside the inner block, you perform arithmetic operations and
handle potential errors like division by zero. The outer block
handles invalid input errors.
try:
try:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Inner Error: Division by zero is not allowed.")
except ValueError:
print("Outer Error: Invalid input.")
output
f) Create a program where you attempt to open a file and perform
a mathematical operation. The program should catch exceptions
for both file errors and mathematical errors (e.g., dividing by
zero).
try:
with open('example.txt', 'r') as f:
num = int(f.read().strip())
result = num / 0 # This will cause an error
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except FileNotFoundError:
print("Error: File not found.")
except Exception as e:
print("An error occurred:", e)
output
g) Write a program that attempts to perform addition between a
number and a string. Handle the TypeError and print an
appropriate message to the user.
try:
num = int(input("Enter a number: "))
result = num + "a" # This will cause a TypeError
except TypeError:
print("Error: Cannot add a number and a string.")
output
h) Write a program that opens a file and reads its contents. Use
the finally block to ensure that the file is closed properly, even if
an exception occurs while reading.
try:
with open('example.txt', 'r') as f:
content = f.read()
print(content)
except Exception as e:
print("An error occurred:", e)
finally:
print("File operation is complete.")
output