Python Lab Manual
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.
else:
if(mark1>=mark2):
print ("The best two test marks are",mark1,mark3)
print ("The average of best of two test marks out of three marks is", (mark1+mark3)/2)
else:
print ("The best two test marks are",mark2,mark3)
print ("The average of best of two test marks out of three marks is", (mark2+mark3)/2)
Dept.of.CSE Page 9
Python Programming Laboratory (21CSL46)
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
n=int(input("Enter n value"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
number_str = str(temp)
occurrences = {}
for digit in number_str:
if digit in occurrences:
occurrences[digit]+= 1
else:
occurrences[digit]= 1
print("Digit occurrences:",occurrences)
Dept.of.CSE Page 10
Python Programming Laboratory (21CSL46)
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):
# Check if input value is valid
if n <= 0:
raise ValueError("Invalid input. N must be greater than 0.")
return fib_n
try:
N = int(input("Enter a value for N (N > 0): "))
result = fibonacci(N)
print("Fibonacci number at position", N, "is", result)
except ValueError as e:
print(str(e))
Dept.of.CSE Page 11
Python Programming Laboratory (21CSL46)
2b. Develop a python program to convert binary to decimal, octal to hexadecimal using functions
def binary_to_decimal(binary):
decimal = 0
power = 0
while binary > 0:
last_digit = binary % 10
decimal += last_digit * (2 ** power)
binary //= 10
power += 1
return decimal
def octal_to_hexadecimal(octal):
decimal = 0
power = 0
while octal > 0:
last_digit = octal % 10
decimal += last_digit * (8 ** power)
octal //= 10
power += 1
hexadecimal = ""
hex_digits = "0123456789ABCDEF"
while decimal > 0:
remainder = decimal % 16
hexadecimal = hex_digits[remainder] + hexadecimal
decimal //= 16
return hexadecimal
Dept.of.CSE Page 12
Python Programming Laboratory (21CSL46)
3a. Write a Python program that accepts a sentence and find the number of words, digits,
uppercase letters and lowercase letters.
def analyze_sentence(sentence):
word_count = len(sentence.split())
digit_count = sum(char.isdigit() for char in sentence)
uppercase_count = sum(char.isupper() for char in sentence)
lowercase_count = sum(char.islower() for char in sentence)
Dept.of.CSE Page 13
Python Programming Laboratory (21CSL46)
3b. Write a Python program to find the string similarity between two given strings
Sample Output: Sample Output:
Original string: Original string:
Python Exercises Python Exercises
Python Exercises Python Exercise
Similarity between two said strings: Similarity between two said strings: 1.0
0.967741935483871
from difflib import SequenceMatcher
# Sample Input
string1=input("Enter string 1")
string2=input("Enter string 2")
Dept.of.CSE Page 14
Python Programming Laboratory (21CSL46)
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 = arr[i]
j=i-1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
i=j=k=0
Dept.of.CSE Page 15
Python Programming Laboratory (21CSL46)
Dept.of.CSE Page 16
Python Programming Laboratory (21CSL46)
4b. Write a program to convert roman numbers in to integer values using dictionaries.
def roman_to_integer(roman):
roman_dict = {
'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000
}
result = 0
prev_value = 0
return result
Dept.of.CSE Page 17
Python Programming Laboratory (21CSL46)
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.
def isphonenumber(number):
if len(number) != 12:
return False
for i in range(0, 3):
if not number[i].isdecimal():
return False
if number[3] != '-':
return False
for i in range(4, 7):
if not number[i].isdecimal():
return False
if number[7] != '-':
return False
for i in range(8, 12):
if not number[i].isdecimal():
return False
return True
import re
if re.match(pattern, phone_number):
print('The phone number is valid.')
else:
print('Invalid phone number.')
Dept.of.CSE Page 18
Python Programming Laboratory (21CSL46)
5b. Develop a python program that could search the text in a file for phone numbers
(+919900889977) and email addresses (sample@gmail.com).
import re
def search_file(filename):
phone_pattern = r'\+\d{11}' # Pattern for phone numbers
email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b' # Pattern for
email addresses
# Example usage
file_name = input("Enter the name of the text file: ")
search_file(file_name)
Dept.of.CSE Page 19
Python Programming Laboratory (21CSL46)
6a. Write a python program to accept a file name from the user and perform the following
operations.
i) Display the first N line of the file
ii) Find the frequency of occurrence of the word accepted from the user in the file
Dept.of.CSE Page 20
Python Programming Laboratory (21CSL46)
6b. Write a python program to create a ZIP file of a particular folder which contains several
files inside it.
import zipfile
import os
# Example usage
folder_path = input("Enter the folder path: ")
zip_name = input("Enter the ZIP file name: ")
create_zip
Dept.of.CSE Page 21
Python Programming Laboratory (21CSL46)
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, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
# Example usage
triangle = Triangle(5, 8)
circle = Circle(3)
rectangle = Rectangle(4, 6)
Dept.of.CSE Page 22
Python Programming Laboratory (21CSL46)
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 = name
self.employee_id = employee_id
self.department = department
self.salary = salary
for i in range(num_employees):
print(f"\nEmployee {i+1}:")
name = input("Enter the name: ")
employee_id = int(input("Enter the employee ID: "))
department = input("Enter the department: ")
salary = float(input("Enter the salary: "))
8a. 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 Palindrome:
def __init__(self, input_data):
self.input_data = input_data
def is_palindrome(self):
pass
class StringPalindrome(Palindrome):
def __init__(self, input_data):
super().__init__(input_data)
def is_palindrome(self):
# Remove spaces and convert to lowercase
input_data = self.input_data.replace(" ", "").lower()
return input_data == input_data[::-1]
class IntegerPalindrome(Palindrome):
def __init__(self, input_data):
super().__init__(input_data)
def is_palindrome(self):
# Convert integer to string
input_data = str(self.input_data)
return input_data == input_data[::-1]
# Example usage
data = input("Enter a string or an integer: ")
# Check if it is a palindrome
if data.isdigit():
palindrome = IntegerPalindrome(int(data))
else:
palindrome = StringPalindrome(data)
if palindrome.is_palindrome():
print("Palindrome")
else:
print("Not a Palindrome")
Dept.of.CSE Page 24
Python Programming Laboratory (21CSL46)
import requests
import os
from bs4 import BeautifulSoup
Dept.of.CSE Page 25
Python Programming Laboratory (21CSL46)
9b. Demonstrate python program to read the data from the spreadsheet and write the data in to
the spreadsheet.
import openpyxl
Dept.of.CSE Page 26