0% found this document useful (0 votes)
11 views18 pages

Python Lab Manual

The document outlines various Python programming exercises, including finding the best test scores, checking for palindromes, calculating Fibonacci numbers, converting number systems, analyzing sentences, and implementing sorting algorithms. It also covers file operations, regular expressions for validating phone numbers and emails, and creating classes for geometric shapes and employee management. Each exercise includes code snippets and explanations for implementation.

Uploaded by

juturuj.21.beis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
11 views18 pages

Python Lab Manual

The document outlines various Python programming exercises, including finding the best test scores, checking for palindromes, calculating Fibonacci numbers, converting number systems, analyzing sentences, and implementing sorting algorithms. It also covers file operations, regular expressions for validating phone numbers and emails, and creating classes for geometric shapes and employee management. Each exercise includes code snippets and explanations for implementation.

Uploaded by

juturuj.21.beis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 18

Python Programming Laboratory (21CSL46)

1a. Write a python program to find the best of two test average marks out of three test's marks
accepted from the user.

mark1=float(input("Entar First Test Mark:"))


mark2=float(input("Entar Second Test Mark:"))
mark3=float(input("Entar Third Test Mark:"))
if(mark1 >= mark2) and (mark1>= mark2):
if(mark2>=mark3):
print ("The best two test marks are",mark1,mark2)
print ("The average of best of two test marks out of three marks is", (mark1+mark2)/2)
else:
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)

elif(mark2 >= mark1) and (mark2>= mark3):


if(mark1>=mark3):
print ("The best two test marks are",mark2,mark1)
print ("The average of best of two test marks out of three marks is", (mark2+mark1)/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)

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.")

# Base cases for Fibonacci sequence


if n == 1:
return 0
elif n == 2:
return 1

# Calculate the Fibonacci number


fib_n_minus_2 = 0
fib_n_minus_1 = 1
fib_n = 0
for i in range(3, n+1):
fib_n = fib_n_minus_1 + fib_n_minus_2
fib_n_minus_2 = fib_n_minus_1
fib_n_minus_1 = fib_n

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

# Test the functions


binary_input = input("Enter a binary number: ")
decimal_result = binary_to_decimal(int(binary_input))
print(f"Decimal equivalent: {decimal_result}")

octal_input = input("Enter an octal number: ")


hexadecimal_result = octal_to_hexadecimal(int(octal_input))
print(f"Hexadecimal equivalent: {hexadecimal_result}")

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)

return word_count, digit_count, uppercase_count, lowercase_count

user_input = input("Enter a sentence: ")


word_count, digit_count, uppercase_count, lowercase_count =
analyze_sentence(user_input)

print("Number of words:", word_count)


print("Number of digits:", digit_count)
print("Number of uppercase letters:", uppercase_count)
print("Number of lowercase letters:", lowercase_count)

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

def string_similarity(string1, string2):


similarity_ratio = SequenceMatcher(None, string1, string2).ratio()
return similarity_ratio

# Sample Input
string1=input("Enter string 1")
string2=input("Enter string 2")

# Find string similarity


#similarity = string_similarity(string1, string2)

print("Original string 1:", string1)


print("Original string 2:", string2)
print("Similarity between two strings:")
print(string_similarity(string1, string2))

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

# Accept input from the user


user_input = input("Enter a list of numbers separated by spaces: ")
my_list = [int(num) for num in user_input.split()]

# Sort the list using insertion sort


insertion_sort(my_list)
print("Sorted list using Insertion Sort:", my_list)

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

while i < len(left_half) and j < len(right_half):


if left_half[i] < right_half[j]:
arr[k] = left_half[i]
i += 1
else:
arr[k] = right_half[j]
j += 1
k += 1

while i < len(left_half):


arr[k] = left_half[i]
i += 1
k += 1

while j < len(right_half):


arr[k] = right_half[j]
j += 1
k += 1

Dept.of.CSE Page 15
Python Programming Laboratory (21CSL46)

# Accept input from the user


user_input = input("Enter a list of numbers separated by spaces: ")
my_list = [int(num) for num in user_input.split()]

# Sort the list using merge sort


merge_sort(my_list)
print("Sorted list using Merge Sort:", my_list)

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

for symbol in roman[::-1]:


value = roman_dict[symbol]
if value >= prev_value:
result += value
else:
result -= value
prev_value = value

return result

# Accept input from the user


roman_numeral = input("Enter a Roman numeral: ")

# Convert Roman numeral to integer


integer_value = roman_to_integer(roman_numeral)

# Display the result


print("Integer value:", integer_value)

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

# Test the function


phone_number = '415-555-442'
if isphonenumber(phone_number):
print('The phone number is valid.')
else:
print('Invalid phone number.')

import re

# Test the regular expression pattern


phone_number = '415-555-4242'
pattern = r'^\d{3}-\d{3}-\d{4}$'

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

with open(filename, 'r') as file:


text = file.read()

# Search for phone numbers


phone_numbers = re.findall(phone_pattern, text)
print("Phone numbers:")
for number in phone_numbers:
print(number)

# Search for email addresses


email_addresses = re.findall(email_pattern, text)
print("\nEmail addresses:")
for email in email_addresses:
print(email)

# 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

def display_first_n_lines(filename, n):


with open(filename, 'r') as file:
for i in range(n):
line = file.readline().strip()
if line:
print(line)

def find_word_frequency(filename, word):


with open(filename, 'r') as file:
text = file.read()
word_frequency = text.lower().count(word.lower())
return word_frequency

# Accept input from the user


file_name = input("Enter the name of the file: ")
n_lines = int(input("Enter the number of lines to display: "))
search_word = input("Enter the word to find its frequency: ")

# Display the first N lines of the file


print("\nFirst", n_lines, "lines of the file:")
display_first_n_lines(file_name, n_lines)

# Find the frequency of the word in the file


frequency = find_word_frequency(file_name, search_word)
print("\nFrequency of the word '" + search_word + "' in the file:", frequency)

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

def create_zip(folder_path, zip_name):


with zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, dirs, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)
zipf.write(file_path, os.path.relpath(file_path, folder_path))

# 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)

print("Area of Triangle:", triangle.area())


print("Area of Circle:", circle.area())
print("Area of Rectangle:", rectangle.area())

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

def update_salary_by_department(self, department, new_salary):


if self.department == department:
self.salary = new_salary

# Create a list to store employee objects


employees = []

# Accept input for creating employee objects


num_employees = int(input("Enter the number of employees: "))

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: "))

# Create employee object and add it to the list


employee = Employee(name, employee_id, department, salary)
employees.append(employee)

# Display employee details before salary update


print("\nBefore salary update:")
for i, employee in enumerate(employees):
print(f"Employee {i+1}: {employee.name}, {employee.employee_id},
{employee.department}, {employee.salary}")

# Update salary of employees in a given department


department = input("\nEnter the department to update salary: ")
new_salary = float(input("Enter the new salary: "))

for employee in employees:


employee.update_salary_by_department(department, new_salary)

# Display updated employee details


print("\nAfter salary update:")
for i, employee in enumerate(employees):
print(f"Employee {i+1}: {employee.name}, {employee.employee_id},
{employee.department}, {employee.salary}")
Dept.of.CSE Page 23
Python Programming Laboratory (21CSL46)

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)

9a. Write a python program to download the all XKCD comics

import requests
import os
from bs4 import BeautifulSoup

# Create a folder to store the comics


folder_name = "xkcd_comics"
if not os.path.exists(folder_name):
os.makedirs(folder_name)

# Start downloading comics


comic_number = 1
while True:
# Make a request to the XKCD website
url = f"https://xkcd.com/{comic_number}/"
response = requests.get(url)
response.raise_for_status()

# Parse the HTML content


soup = BeautifulSoup(response.text, 'html.parser')

# Find the comic image element


image_element = soup.find(id='comic').find('img')
if not image_element:
break

# Get the image URL


image_url = 'https:' + image_element['src']

# Download the image


response = requests.get(image_url)
response.raise_for_status()

# Save the image to a file


image_path = os.path.join(folder_name, os.path.basename(image_url))
with open(image_path, 'wb') as file:
file.write(response.content)

print(f"Downloaded comic {comic_number}")


comic_number += 1

print("All comics downloaded successfully!")

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

# Read data from a spreadsheet


workbook = openpyxl.load_workbook('data.xlsx')
worksheet = workbook.active

# Read values from cells


value1 = worksheet['A1'].value
value2 = worksheet.cell(row=2, column=1).value

# Display the read values


print("Read values from the spreadsheet:")
print("Value 1:", value1)
print("Value 2:", value2)

# Write data to the spreadsheet


worksheet['B1'] = "Hello"
worksheet.cell(row=2, column=2, value="World")

# Save the modified spreadsheet


workbook.save('data.xlsx')

print("Data written to the spreadsheet successfully!")

Dept.of.CSE Page 26

You might also like