PYTHON LAB MANUAL
1a) Write a python program to find the best of two test average marks out of three
test’s marks accepted from the user.
print("Enter the three internals marks:")
m1 = int(input("Enter marks1:"))
m2 = int(input("Enter marks2:"))
m3 = int(input("Enter marks3:"))
print("Marks1:", m1)
print("Marks2:", m2)
print("Marks3:", m3)
small=m1
if small > m2:
small = m2
if small > m3:
small = m3
avg=(m1+m2+m3-small)/2;
print("Average of best two test out of three test is",avg)
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.
rev = 0
num = int(input("Enter the number:"))
temp = num
n=str(temp)
while num > 0:
digit = num%10
rev = rev*10+digit
num //= 10
print("Given Number is", temp)
print("Reversed Number is", rev)
if temp == rev:
print(temp, "is a Palindrome")
else:
print(temp, "is not a Palindrome")
# Finding Number of Digits using built-in function
print("Number of Digits using Built-in Function: ", len(str(n)))
#Finding the occurrences of each digit
s={}
for i in n:
if i in s:
s[i]+=1
else:
s[i]=1
print("Number of occurrences of each digit in the input number are:")
print(s)
2a) Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program which accepts
a value for N (where N >0) as input and pass this value to the function. Display suitable
error message if the condition for input value is not followed.
def fibonacci(n):
if n <= 0:
print("Error: N must be greater than 0.")
return None
elif n == 1:
return 0
elif n == 2:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
n = int(input("Enter a value for N: "))
result = fibonacci(n)
if result is not None:
print("The", n, "th term of the Fibonacci sequence is", result)
2b) Develop a python program to convert binary to decimal, octal to hexadecimal using
functions.
def binary_to_decimal(binary_str):
decimal_num = int(binary_str, 2)
return decimal_num
def octal_to_hexadecimal(octal_str):
decimal_num = int(octal_str, 8)
hexadecimal_str = hex(decimal_num).upper()
return hexadecimal_str
# Input binary and octal numbers
binary_input = input("Enter a binary number: ")
octal_input = input("Enter an octal number: ")
# Convert and display the results
decimal_result = binary_to_decimal(binary_input)
hexadecimal_result = octal_to_hexadecimal(octal_input)
print(f"Decimal: {decimal_result}")
print(f"Hexadecimal: {hexadecimal_result}")
3a) Write a Python program that accepts a sentence and find the number of words,
digits, uppercase letters and lowercase letters.
sentence = input("Enter a sentence: ")
word_count = len(sentence.split())
digit_count = 0
upper_count = 0
lower_count = 0
for char in sentence:
if char.isdigit():
digit_count += 1
elif char.isupper():
upper_count += 1
elif char.islower():
lower_count += 1
print("Number of words:", word_count)
print("Number of digits:", digit_count)
print("Number of uppercase letters:", upper_count)
print("Number of lowercase letters:", lower_count)
3b) Write a Python program to find the string similarity between two given strings
import difflib
def string_similarity(str1, str2):
result = difflib.SequenceMatcher(a=str1.lower(), b=str2.lower())
return result.ratio()
str1 = 'Python Exercises' or str1 = input("Enter a sentence: ")
str2 = 'Python Exercises' or str2 = input("Enter a sentence: ")
print("Original string:")
print(str1)
print(str2)
print("Similarity between two said strings:")
print(string_similarity(str1,str2))
str1 = 'Python Exercises' or str1 = input("Enter a sentence: ")
str2 = 'Python Exercise' or str2 = input("Enter a sentence: ")
print("\nOriginal string:")
print(str1)
print(str2)
print("Similarity between two said strings:")
print(string_similarity(str1,str2))
4a) Write a python program to implement insertion sort and merge sort using lists.
def insertion_sort(arr):
for i in range(1, len(arr)):
key, j = arr[i], i - 1
while j >= 0 and key < arr[j]:
arr[j + 1], j = arr[j], j - 1
arr[j + 1] = key
my_list = [5, 2, 8, 3, 9, 1]
print("Given Elements for Insertion Sort:", my_list)
insertion_sort(my_list)
print("Sorted Elements using Insertion Sort:", my_list)
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left_half, right_half = arr[:mid], arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
i=j=k=0
while i < len(left_half) and j < len(right_half):
arr[k], i, j, k = (left_half[i], i + 1, j, k + 1) if left_half[i] < right_half[j] else (right_half[j], i,
j + 1, k + 1)
while i < len(left_half): arr[k], i, k = left_half[i], i + 1, k + 1
while j < len(right_half): arr[k], j, k = right_half[j], j + 1, k + 1
my_list = [8, 5, 7, 2, 9, 1]
print("Given Elements for Merge Sort:", my_list)
merge_sort(my_list)
print("Sorted Elements using Merge Sort:", my_list)
4b) Write a program to convert roman numbers in to integer values using dictionaries.
def roman_to_integer(roman):
roman_numerals = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
total, prev_value = 0, 0
for letter in roman[::-1]:
value = roman_numerals[letter]
total, prev_value = total - value if value < prev_value else total + value, value
return total
roman_numeral = input("Enter a Roman numeral: ")
integer_value = roman_to_integer(roman_numeral)
print("Integer value:", integer_value)
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 is_valid_phone_number(number):
pattern = r'^\d{3}-\d{3}-\d{4}$'
return bool(re.match(pattern, number))
phone_number = input("Enter a phone number (e.g., 415-555-4242): ")
print("Entered Phone Number is", phone_number)
if is_valid_phone_number(phone_number):
print(phone_number, "is a Valid phone number")
else:
print(phone_number, "is an Invalid phone number")
5b) Develop a python program that could search the text in a file for phone numbers
(+919900889977) and email addresses ([email protected])
import re
def find_patterns(text, pattern):
return re.findall(pattern, text)
def search_file(file_path):
with open(file_path, 'r') as file:
file_content = file.read()
phone_numbers = find_patterns(file_content, r"\+\d{12}")
email_addresses = find_patterns(file_content, r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-
]+\.[A-Z|a-z]{2,}\b")
return phone_numbers, email_addresses
file_path = 'sample.txt' # Replace with the path to your text file
phone_numbers, email_addresses = search_file(file_path)
print("Phone Numbers:")
print(*phone_numbers, sep='\n')
print("\nEmail Addresses:")
print(*email_addresses, sep='\n')
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
import os.path
import sys
fname = input("Enter the filename : ")
if not os.path.isfile(fname):
print("File", fname, "doesn't exists")
sys.exit(0)
infile = open(fname, "r")
lineList = infile.readlines()
for i in range(20):
print(i+1, ":", lineList[i])
word = input("Enter a word : ")
cnt = 0
for line in lineList:
cnt += line.count(word)
print("The word", word, "appears", cnt, "times in the file")
6b) Write a python program to create a ZIP file of a particular folder which contains
several files inside it.
import zipfile
import os
def create_zip(folder_path, zip_name):
try:
with zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) as zipf:
# Iterate over all the files in the folder
for foldername, subfolders, filenames in os.walk(folder_path):
for filename in filenames:
# Get the absolute path of the file
file_path = os.path.join(foldername, filename)
# Add the file to the ZIP archive
zipf.write(file_path, arcname=os.path.relpath(file_path, folder_path))
print(f"ZIP file '{zip_name}' created successfully!")
except FileNotFoundError:
print("Folder not found!")
# Accepting user input
folder_path = input("Enter the folder path: ")
zip_name = input("Enter the name of the ZIP file to create: ")
# Creating the ZIP file
create_zip(folder_path, zip_name)
7a) By using the concept of inheritance write a python program to find the area of
triangle, circle and rectangle.
import math
class Shape:
def area(self):
pass
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius**2
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
# Creating instances of the shapes
triangle = Triangle(6, 4)
circle = Circle(3)
rectangle = Rectangle(5, 8)
# Displaying the areas
print("Area of the triangle:", triangle.area())
print("Area of the circle:", circle.area())
print("Area of the rectangle:", rectangle.area())
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, employee_id, department, salary):
self.name, self.employee_id, self.department, self.salary = name, employee_id,
department, salary
def update_salary_department(self, department, new_salary):
if self.department == department: self.salary = new_salary
def display_details(self):
print("Name:", self.name, "\nEmployee ID:", self.employee_id, "\nDepartment:",
self.department, "\nSalary:", self.salary)
employee1, employee2, employee3 = Employee("Rajath AN", "E21", "HR", 50000),
Employee("Cherika R", "E22", "Sales", 60000), Employee("Rakshitha Gowda", "E23", "IT",
70000)
print("Initial Employee Details:")
employee1.display_details()
employee2.display_details()
employee3.display_details()
department, new_salary = input("Enter the department to update salary: "),
float(input("Enter the new salary: "))
for employee in [employee1, employee2, employee3]:
employee.update_salary_department(department, new_salary)
print("\nUpdated Employee Details:")
employee1.display_details()
employee2.display_details()
employee3.display_details()
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.
class IntegerPalindrome(Palindrome):
def is_palindrome(self):
string_value = str(self.value)
reversed_value = string_value[::-1]
return string_value == reversed_value
# Function to check if input is a palindrome
def check_palindrome(palindrome_obj):
if palindrome_obj.is_palindrome():
print(input_value, "is a palindrome.")
else:
print(input_value, "is not a palindrome.")
# Accepting user input
input_value = input("Enter a string or integer: ")
print("Entered Data is", input_value)
# Checking if it is a palindrome
if input_value.isdigit():
palindrome = IntegerPalindrome(int(input_value))
else:
palindrome = StringPalindrome(input_value)
check_palindrome(palindrome)
9a) Write a python program to download the all XKCD comics.
import requests
import os
def download_xkcd_comics():
folder_path = "xkcd_comics"
os.makedirs(folder_path, exist_ok=True)
comic_number = 1
while True:
url = f"https://xkcd.com/{comic_number}/info.0.json"
response = requests.get(url)
if response.status_code != 200:
break
comic_data = response.json()
image_url = comic_data["img"]
image_response = requests.get(image_url)
if image_response.status_code == 200:
image_path = os.path.join(folder_path, f"{comic_number}.png")
with open(image_path, "wb") as image_file:
image_file.write(image_response.content)
print(f"Downloaded comic {comic_number}")
comic_number += 1
download_xkcd_comics()
9b) Demonstrate python program to read the data from the spreadsheet and write the
data in to the spreadsheet
import openpyxl
def read_data(file_path, sheet_name):
workbook = openpyxl.load_workbook(file_path)
sheet = workbook[sheet_name]
return [list(row) for row in sheet.iter_rows(values_only=True)]
def write_data(file_path, sheet_name, data):
workbook = openpyxl.load_workbook(file_path)
sheet = workbook[sheet_name]
for row_idx, row_data in enumerate(data, start=1):
for col_idx, value in enumerate(row_data, start=1):
sheet.cell(row=row_idx, column=col_idx).value = value
workbook.save(file_path)
# Define file path and sheet name
file_path = 'sample.xlsx' # Replace with your file path
sheet_name = 'Sheet1' # Replace with your sheet name
# Read data from spreadsheet
data = read_data(file_path, sheet_name)
print("Read data:")
for row in data:
print(row)
# Modify the data (e.g., add a new row)
new_row = ['4GWXXCS000', 'Cherika', 'CSE']
data.append(new_row)
# Write data back to spreadsheet
write_data(file_path, sheet_name, data)
print("\nData written to spreadsheet successfully.")
10a) Write a python program to combine select pages from many PDFs.
import PyPDF2
def PDFmerge(pdfs, output):
# creating pdf file merger object
pdfMerger = PyPDF2.PdfMerger()
# appending pdfs one by one
for pdf in pdfs:
pdfMerger.append(pdf)
# writing combined pdf to output pdf file
with open(output, 'wb') as f:
pdfMerger.write(f)
def main():
# pdf files to merge
pdfs = ['file1.pdf', 'file2.pdf']
# output pdf file name
output = 'combined_example.pdf'
# calling pdf merge function
PDFmerge(pdfs, output)
if __name__ == "__main__":
# calling the main function
main()
10b) Write a python program to fetch current weather data from the JSON file.
Aim: Demonstration of working with PDF, word and JSON files
import requests, json
api_key = "Your_API_Key"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
city_name = input("Enter city name : ")
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
response = requests.get(complete_url)
x = response.json()
if x["cod"] != "404":
y = x["main"]
current_temperature = y["temp"]
current_pressure = y["pressure"]
current_humidity = y["humidity"]
z = x["weather"]
weather_description = z[0]["description"]
print(" Temperature (in kelvin unit) = " + str(current_temperature) +
"\n atmospheric pressure (in hPa unit) = " + str(current_pressure) +
"\n humidity (in percentage) = " + str(current_humidity) +
"\n description = " + str(weather_description))
else:
print(" City Not Found ")