1a) Write a python program to find the best of two test average marks out of three
test’s marks accepted from the user.
# Program to find the best of two test average marks out of three tests
# Accept marks from the user
mark1 = float(input("Enter marks for Test 1: "))
mark2 = float(input("Enter marks for Test 2: "))
mark3 = float(input("Enter marks for Test 3: "))
# Put marks in a list
marks = [mark1, mark2, mark3]
# Sort marks in descending order to get the two highest
[Link](reverse=True)
# Compute average of best two marks
best_two_average = (marks[0] + marks[1]) / 2
# Display result
print(f"\nThe best two test marks are: {marks[0]} and {marks[1]}")
print(f"The best two test average is: {best_two_average:.2f}")
Output:
Enter marks for Test 1: 78
Enter marks for Test 2: 85
Enter marks for Test 3: 69
The best two test marks are: 85.0 and 78.0
The best two test average is: 81.50
1b) Develop a Python program to check whether a given number is palindrome or not
and also count the number of occurrences of each digit in the input number.
# Program to check if a number is palindrome and count occurrences of each digit
# Accept number from user
num = input("Enter a number: ")
# Check if the number is palindrome
if num == num[::-1]:
print(f"\n {num} is a Palindrome number.")
else:
print(f"\n {num} is not a Palindrome number.")
# Count occurrences of each digit
print("\nDigit occurrences:")
for digit in sorted(set(num)): # sorted for neat output
print(f"Digit {digit} occurs {[Link](digit)} time(s).")
Output:
Enter a number: 1221
1221 is a Palindrome number.
Digit occurrences:
Digit 1 occurs 2 time(s).
Digit 2 occurs 2 time(s).
2a) Write a function called root that is given a number x and an integer n and returns
x1/n. In the function definition, set the default value of n to 2.
def root(x, n=2):
return x ** (1 / n)
# Example usage:
print(root(9)) # Default: square root of 9 → 3.0
print(root(27, 3)) # Cube root of 27 → 3.0
print(root(16, 4))
output
3.0
3.0
2.0
2b) Write a function called merge that takes two already sorted lists of possibly different lengths,
and merges them into a single sorted list. (a) Do this using the sort method. (b) Do this without using
the sort method.
(a) Using the sort() Method
def merge_with_sort(list1, list2):
merged = list1 + list2 # Combine both lists
[Link]() # Sort the combined list
return merged
# Example usage:
list1 = [1, 3, 5]
list2 = [2, 4, 6]
print(merge_with_sort(list1, list2))
Output: [1, 2, 3, 4, 5, 6]
(b) Without Using the sort() Method (Manual Merge)
def merge_without_sort(list1, list2):
merged = []
i=j=0
# Traverse both lists and append the smaller element to merged
while i < len(list1) and j < len(list2):
if list1[i] < list2[j]:
[Link](list1[i])
i += 1
else:
[Link](list2[j])
j += 1
# Append remaining elements (only one of these will execute)
[Link](list1[i:])
[Link](list2[j:])
return merged
# Example usage:
list1 = [1, 3, 5]
list2 = [2, 4, 6]
print(merge_without_sort(list1, list2))
Output: [1, 2, 3, 4, 5, 6]
3a) Write a Python program that accepts a sentence and find the number of words, digits, uppercase
letters and lowercase letters.
# Program to count words, digits, uppercase and lowercase letters in a sentence
# Accept a sentence from the user
sentence = input("Enter a sentence: ")
# Initialize counters
word_count = len([Link]())
digit_count = 0
uppercase_count = 0
lowercase_count = 0
# Loop through each character in the sentence
for ch in sentence:
if [Link]():
digit_count += 1
elif [Link]():
uppercase_count += 1
elif [Link]():
lowercase_count += 1
# Display the results
print("\nResults:")
print(f"Number of words: {word_count}")
print(f"Number of digits: {digit_count}")
print(f"Number of uppercase letters: {uppercase_count}")
print(f"Number of lowercase letters: {lowercase_count}")
Output:
Enter a sentence: Hello World 2025
Results:
Number of words: 3
Number of digits: 4
Number of uppercase letters: 2
Number of lowercase letters: 8
3b) Write a Python program to find the string similarity between two given strings
Sample Output 1: Sample Output 2:
Python Exercises Python Exercises
Python Exercises Python Exercise
Similarity between two said strings: 1.0 Similarity between two said strings: 0. 967741935483871
from difflib import SequenceMatcher
str1 = input("Enter first string: ")
str2 = input("Enter second string: ")
similarity = SequenceMatcher(None, str1, str2).ratio()
print("\nOriginal strings:")
print(str1)
print(str2)
print(f"Similarity between two said strings: {similarity}")
Output 1
Enter first string: Python Exercises
Enter second string: Python Exercises
Original strings:
Python Exercises
Python Exercises
Similarity between two said strings: 1.0
Output2
Enter first string: Python Exercises
Enter second string: Python Exercise
Original strings:
Python Exercises
Python Exercise
Similarity between two said strings: 0.967741935483871
4a) Write a Python program to Merge Similar Dictionaries in List
from collections import defaultdict
def merge_similar_dicts(dict_list):
merged = defaultdict(int) # Use int for summing numeric values
for d in dict_list:
for key, value in [Link]():
merged[key] += value
return dict(merged)
# Example usage
dicts = [
{'a': 10, 'b': 20},
{'a': 5, 'c': 15},
{'b': 25, 'd': 30}
result = merge_similar_dicts(dicts)
print(result)
output
{'a': 15, 'b': 45, 'c': 15, 'd': 30}
4b) Write a python program to Find All Pairs Combination of Two Tuples
# Program to find all pairs combination of two tuples
# Example tuples
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
# Using list comprehension
result = [(a, b) for a in tuple1 for b in tuple2]
print("All pairs combinations:")
print(result)
output
All pairs combinations:
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
5a) Write a function called isphonenumber() to recognize a pattern 415-555-4242 without using regular
expression and also write the code to recognize the same pattern using regular expression.
import re
def isPhoneNumber(text):
pattern = [Link](r'^\d{3}-\d{3}-\d{4}$')
return bool([Link](text))
# Example usage:
print(isPhoneNumber("415-555-4242")) # ✅ True
print(isPhoneNumber("415-55A-4242")) # ❌ False
print(isPhoneNumber("4155554242")) # ❌ False
output
True
False
False
5b) Develop a python program that could search the text in a file for phone numbers (+919900889977) and
email addresses (sample@[Link])
import re
# Open the file
f = open("[Link]", "r")
text = [Link]()
[Link]()
# Search patterns
phones = [Link](r"\+91\d{10}", text)
emails = [Link](r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", text)
# Print results
print("Phone numbers:", phones)
print("Email addresses:", emails)
Suppose [Link] contains:
Contact me at +919900889977 or email sample@[Link].
Another mail: test123@[Link]
My alternate number is +918888554433
Output
Phone numbers: ['+919900889977', '+918888554433']
Email addresses: ['sample@[Link]', 'test123@[Link]']
6a) Write a python program to accept a file name from the user and perform the following operations 1.
Display the first N line of the file 2. Find the frequency of occurrence of the word accepted from the user in
the file
# Accept file name
filename = input("Enter file name: ")
# Accept N
N = int(input("Enter number of lines to display: "))
# Accept word to search
word = input("Enter a word to find its frequency: ")
# Read the file
with open(filename, "r") as f:
lines = [Link]()
# --- 1. Display first N lines ---
print("\nFirst", N, "lines of the file:")
for line in lines[:N]:
print(line, end="")
# --- 2. Count frequency of the word ---
text = "".join(lines).lower()
count = [Link]([Link]())
print("\n\nFrequency of the word '{}' : {}".format(word, count))
Suppose the file [Link] contains:
Python is easy to learn.
Python supports object oriented programming.
Many students learn Python.
Learning Python is fun.
Output
Enter file name: [Link]
Enter number of lines to display: 2
Enter a word to find its frequency: Python
First 2 lines of the file:
Python is easy to learn.
Python supports object oriented programming.
Frequency of the word 'Python' : 3
6b) Write a python program to create a ZIP file of a particular folder which contains several files inside it.
import zipfile
import os
folder = input("Enter folder name: ")
zipname = input("Enter zip file name: ")
zipf = [Link](zipname, 'w')
for file in [Link](folder):
[Link]([Link](folder, file))
[Link]()
print("ZIP file created!")
Suppose your folder contains:
Folder name: myfiles
Files inside:
[Link]
[Link]
[Link]
output
Enter folder name: myfiles
Enter zip file name: [Link]
ZIP file created!
A file named [Link] will be created, containing:
[Link]
[Link]
[Link]
7a) By using the concept of inheritance write a python program to find the area of triangle, circle and
rectangle.
import math
# Base class
class Shape:
def area(self):
pass # This will be overridden in child classes
# Derived class for Rectangle
class Rectangle(Shape):
def area(self, length, breadth):
return length * breadth
# Derived class for Triangle
class Triangle(Shape):
def area(self, base, height):
return 0.5 * base * height
# Derived class for Circle
class Circle(Shape):
def area(self, radius):
return [Link] * radius * radius
# --- Main Program ---
rect = Rectangle()
tri = Triangle()
cir = Circle()
print("Area of Rectangle:", [Link](5, 3))
print("Area of Triangle:", [Link](4, 6))
print("Area of Circle:", round([Link](3), 2))
output
Area of Rectangle: 15
Area of Triangle: 12.0
Area of Circle: 28.27
7b) Write a python program by creating a class called Employee to store the details of Name, Employee_ID,
Department and Salary, and implement a method to update salary of employees belonging to a given
department.
class Employee:
def __init__(self, name, emp_id, dept, salary):
[Link] = name
self.emp_id = emp_id
[Link] = dept
[Link] = salary
def update(self, amount):
[Link] += amount
# Creating employee objects
e1 = Employee("Mohammed", 101, "IT", 30000)
e2 = Employee("Aisha", 102, "HR", 25000)
e3 = Employee("Rahul", 103, "IT", 28000)
employees = [e1, e2, e3]
# Taking input
d = input("Enter department: ")
inc = int(input("Enter increment amount: "))
# Updating salary
for e in employees:
if [Link] == d:
[Link](inc)
# Displaying results
for e in employees:
print([Link], e.emp_id, [Link], [Link])
output
Enter department: IT
Enter increment amount: 2000
Mohammed 101 IT 32000
Aisha 102 HR 25000
Rahul 103 IT 30000
8) Write a python program to find the whether the given input is palindrome or not (for both string and
integer) using the concept of polymorphism and inheritance.
# Base class
class Palindrome:
def check(self, value):
pass # Method will be overridden in child classes
# Derived class for String palindrome
class StringPalindrome(Palindrome):
def check(self, value):
value = [Link]()
if value == value[::-1]:
print("✅ The given string is a palindrome.")
else:
print("❌ The given string is not a palindrome.")
# Derived class for Integer palindrome
class NumberPalindrome(Palindrome):
def check(self, value):
num_str = str(value)
if num_str == num_str[::-1]:
print("✅ The given number is a palindrome.")
else:
print("❌ The given number is not a palindrome.")
# --- Main Program ---
inp = input("Enter a string or number: ")
if [Link]():
obj = NumberPalindrome() # object of child class (number)
[Link](int(inp))
else:
obj = StringPalindrome() # object of child class (string)
[Link](inp)
Output1
Enter a string or number: madam
✅ The given string is a palindrome.
Output2
Enter a string or number: 12321
✅ The given number is a palindrome.
Output3
Enter a string or number: hello
❌ The given string is not a palindrome.
9a) Write a python program to download the all XKCD comics
import requests, os
[Link]("xkcd", exist_ok=True)
i=1
while True:
try:
j = [Link](f"[Link]
open(f"xkcd/{i}.png","wb").write([Link](j["img"]).content)
print("Downloaded:", i)
i += 1
except:
break
print("Done!")
Output
Downloaded: 1
Downloaded: 2
Downloaded: 3
Downloaded: 4
Downloaded: 5
Downloaded: 6
Downloaded: 7
Downloaded: 8
Downloaded: 9
Downloaded: 10
...
Downloaded: 2789
Downloaded: 2790
Done!
9b) Demonstrate python program to read the data from the spreadsheet and write the data in to the
spreadsheet
from openpyxl import load_workbook, Workbook
# --- Read from Excel ---
wb1 = load_workbook("[Link]")
sheet1 = [Link]
print("Reading data:")
for row in sheet1.iter_rows(values_only=True):
print(row)
# --- Write to Excel ---
wb2 = Workbook()
sheet2 = [Link]
sheet2["A1"] = "Hello"
sheet2["B1"] = "World"
[Link]("[Link]")
print("Data written to [Link]")
output
Suppose [Link] contains:
Name Marks
John 78
Sara 88
🖥 Program Output
Reading data:
('Name', 'Marks')
('John', 78)
('Sara', 88)
Data written to [Link]
10a) Write a python program to combine select pages from many PDFs
from PyPDF2 import PdfReader, PdfWriter
writer = PdfWriter()
# Read first PDF and take page 1 (0 index)
pdf1 = PdfReader("[Link]")
writer.add_page([Link][0])
# Read second PDF and take page 2 (1 index)
pdf2 = PdfReader("[Link]")
writer.add_page([Link][1])
# Save output
with open("[Link]", "wb") as f:
[Link](f)
print("Done!")
output
Done!
10b) Write a python program to fetch current weather data from the JSON file
import json
# --- Step 1: Read data from JSON file ---
with open("[Link]", "r") as file:
data = [Link](file)
# --- Step 2: Extract weather information ---
city = data["name"]
temperature = data["main"]["temp"]
humidity = data["main"]["humidity"]
description = data["weather"][0]["description"]
# --- Step 3: Display the data ---
print("City:", city)
print("Temperature:", temperature, "°C")
print(" Humidity:", humidity, "%")
print(" Weather Description:", description)
[Link] File
"coord": {"lon": 77.6, "lat": 12.97},
"weather": [
{"id": 800, "main": "Clear", "description": "clear sky", "icon": "01d"}
],
"main": {
"temp": 29.5,
"feels_like": 30.0,
"pressure": 1012,
"humidity": 45
},
"name": "Bangalore"
Output
City: Bangalore
Temperature: 29.5 °C
Humidity: 45 %
Weather Description: clear sky