Updated_ISE_Python_Lab_21CSL46[1]
Updated_ISE_Python_Lab_21CSL46[1]
PROGRAM-1
1a) Write a Python program to find the best of two test average marks out of three test marks
accepted by the user.
OUTPUT:
2a) Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program that accepts a value for
N (where N >0) as input and pass this value to the function. Display a suitable error message if the
condition for input value is not followed.
def fn(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
return fn(n-1) + fn(n-2)
num = int(input("Enter a number : "))
if num > 0:
print("fn(", num, ") = ",fn(num) , sep ="")
else:
print("Error in input")
OUTPUT:
1. Enter a number : 5
fn(5) = 3
2. Enter a number : -4
Error in input
def BinToDec(x):
dec = 0
i=0
while x>0:
r = x%10
if r!=0 and r!=1:
print("Enter a valid Binary number")
return 0
else:
dec = dec + r*2**i
x = x // 10
i += 1
return dec
def OctaToHexa(n):
num = n
dec = 0
base = 1
temp = num
while temp:
r = temp % 10
temp = temp // 10
dec += r * base
base = base * 8
result = ' '
while dec != 0:
temp = 0
temp = dec % 16
if temp < 10:
result = str(temp) + result
else:
result = chr(temp + 55) + result
dec = dec // 16
return result
OUTPUT:
3a) Write a Python program that accepts a sentence and find the number of words, digits,
uppercase letters, and lowercase letters.
x = input("Enter a sentence")
y=x
print("There are",len(x.split())," words in the sentence")
digits,upper,lower=0,0,0
for i in x:
if i.isdigit():
digits+=1
elif i.isupper():
upper+=1
elif i.islower():
lower+=1
print("There are {0} digits, {1} upper case characters and {2} lower case characters in the
sentence".format(digits,upper,lower))
OUTPUT:
OUTPUT:
4a) Write a python program to implement insertion sort and merge sort using lists.
def InsertionSort(lst):
i=0
while i<len(lst):
small = lst[i]
for j in range(i+1,len(lst)):
nxt =lst[j]
if small>nxt:
small = lst[j]
index = lst.index(small)
if i==index :
pass
else:
lst.remove(small)
lst.insert(i,small)
i=i+1
return lst
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr)//2
sub_array1 = arr[:mid]
sub_array2 = arr[mid:]
mergeSort(sub_array1)
mergeSort(sub_array2)
i=j=k=0
while i < len(sub_array1) and j < len(sub_array2):
if sub_array1[i] < sub_array2[j]:
arr[k] = sub_array1[i]
i += 1
else:
arr[k] = sub_array2[j]
j += 1
k += 1
while i < len(sub_array1):
arr[k] = sub_array1[i]
i+=1
k += 1
while j < len(sub_array2):
lst = []
n = int(input("Enter the size of the list"))
print("Enter ",n," numbers of the list")
for i in range(1,n+1):
lst.append(int(input()))
print(lst)
print("Enter 1: Insertion Sort, 2: Merge Sort ")
ch = int(input())
if ch==1:
lst = InsertionSort(lst)
print("The sorted array is ",lst)
elif ch==2:
lst = mergeSort(lst)
print("The sorted array is ",lst)
else:
print("Invalid Choice")
def roman_to_int(s):
rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
int_val = 0
for i in range(len(s)):
if i > 0 and rom_val[s[i]] > rom_val[s[i - 1]]:
int_val += rom_val[s[i]] - 2 * rom_val[s[i - 1]]
else:
int_val += rom_val[s[i]]
return int_val
x = input("Enter the Roman Number")
print(roman_to_int(x.upper()))
OUTPUT:
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(x):
l = len(x)
if l!=12:
return 0
else:
for i in range(0,l):
if i==0 or i==1 or i==2 :
if x[i].isdigit() == False:
return 0
if i==4 or i==5 or i==6 :
if x[i].isdigit() == False:
return 0
if i==8 or i==9 or i==10 :
if x[i].isdigit() == False:
return 0
if i==3 or i==7:
if x[i] != '-':
return 0
return 1
def REisphonenumber(x):
pno = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
if pno.match(x):
return 1
else:
return 0
phoneNo = input("Enter a phone number of ddd-ddd-dddd format to validate")
ch = int(input("Enter 1.To validate without RE. 2. To validate using RE"))
if ch==1:
if isphonenumber(phoneNo)==1:
elif ch==2:
if REisphonenumber(phoneNo)==1:
print("You have entered a valid phone number")
else:
print("You have entered an invalid phone number")
OUTPUT:
import re
try:
file = open("data.txt")
for line in file:
line = line.strip()
match = re.findall(r"(\d{10})", line)
if(len(match)>0):
print(match)
emails = re.findall("[0-9a-zA-z]+@[0-9a-zA-z]+\.[0-9a-zA-z]+", line)
if(len(emails) > 0):
print(emails)
except FileNotFoundError as e:
print(e)
Note: Create a text file with a name data.txt in Jupyter Notebook that txt file should contains phone
numbers and mail address
OUTPUT:
['[email protected]']
['1800103421']
['1800103002']
['1800419002']
['8046122000']
['9161464700']
['[email protected]']
6a) Write a python program to accept a file name from the user and perform the following
operations.
B. Find the frequency of occurrence of the word accepted by the user in the file
inputFile=open("data.txt")
N=int(input("enter N Value"))
i=0
while i<=N:
for line in inputFile:
print(line)
i=i+1
count=0
key=input("Enter the word to be searched")
file1=open("data.txt")
for line in file1:
words=line.split()
for word in words:
if word==key:
count+=1
print("Keyword:",key, "occurs",count, "times")
Enter N value: 16
The following are the first 16 lines of a text file:
Queries related to AIS, TIS, SFT Preliminary response, Response to e-campaigns or e-Verification
Email: [email protected]
Phone2
18001034215
e-Filing of Income Tax Return or Forms and other value added services & Intimation, Rectification,
Refund and other Income Tax Processing Related Queries.
Phone2
Enter word to be searched: 18:00
Occurrences of the word:
2
OUTPUT:
F:\SampleDir ['Sample_1', 'Sample_2'] Demo_3.docx
F:\SampleDir\Sample_1\Demo [] Demo_1.docx
F:\SampleDir\Sample_1\Demo [] ~$Demo_1.docx
F:\SampleDir\Sample_2 [] Demo_2.txt
Created
7a) By using the concept of inheritance write a python program to find the area of a triangle,
circle, and rectangle.
class Shape:
area,radius,length,breadth,a,b,c=0,0,0,0,0,0,0
def __init__(self, r):
self.radius = r
def __init__(self, l,b):
self.length = l
self.breadth = b
def __init__(self, a,b,c):
self.a = a
self.b = b
self.c = c
class Circle(Shape):
def __init__(self,r):
super().__init__(r,0,0)
def area(self,r):
print("The area of circle is ",3.14*r*r)
class Rectangle(Shape):
def __init__(self,l,b):
super().__init__(0,l,b)
def area(self,l,b):
print("The area of rectangle is ",l*b)
class Triangle(Shape):
def __init__(self,a,b,c):
super().__init__(a,b,c)
def area(self,a,b,c):
s = (a+b+c)/2
import math
print("The area of triangle is ",math.sqrt(s*(s-a)*(s-b)*(s-c)))
OUTPUT:
1. Enter your choice to compute area of 1.Circle, 2.Rectangle, 3.Triangle
1
Enter radius of circle8
The area of circle is 200.96
class Employee:
def __init__(self,name,eid,dept,sal):
self.name = name
self.eid = eid
self.dept = dept
self.sal = sal
def salUpdate(self,eid,dept,updsal):
self.sal = updsal
if __name__ == "__main__":
emp=[]
while True:
ch = int(input("\n Enter 1.Create Employee\n 2.To display all employees\n 3.To Update an employee
salary\n 4.To exit\n"))
if ch==1:
n = input("Employee Name: ")
i = int(input("Employee ID: "))
d = input("Employee Department: ")
s = int(input("Employee Salary: "))
emp.append(Employee(n,i,d,s))
print("Employee details created",len(emp))
elif ch==2:
for i in emp:
print("\n Employee Name:{0}\n Employee ID:{1}\n Employee Department:{2}\n Employee
Salary:{3}".format(i.name, i.eid, i.dept, i.sal) )
elif ch==3:
upd=0
print("\n Enter the Department and ID of the employee to update salary")
empid = int(input("Employee ID: "))
dept = input("Employee Department: ")
for i in emp:
if empid == i.eid and dept == i.dept:
upsal = int(input("\n Enter the updated salary"))
i.salUpdate(empid,dept,upsal)
print("\n Salary updated")
upd=1
BIT, DEPT. OF ISE 21
PYTHON PROGRAMMING LABORTORY (21CSL46)
if upd==0:
print("\n Employee does not exist")
elif ch==4:
break;
else:
print("Invalid choice")
OUTPUT:
Enter 1. Create Employee
2. To display all employees
3. To Update an employee salary
4. To exit
1
Employee Name: Anjan
Employee ID: 001
Employee Department: CSE
Employee Salary: 65000
Employee details created 1
Employee Name:Anjan
Employee ID:1
Employee Department:CSE
Employee Salary:65000
Employee Name:Anoop
Employee ID:2
Employee Department:ECE
Employee Salary:68000
Employee Name:Arun
Employee ID:3
Employee Department:ISE
Employee Salary:58000
Salary updated
4. To exit
2
BIT, DEPT. OF ISE 23
PYTHON PROGRAMMING LABORTORY (21CSL46)
Employee Name:Anjan
Employee ID:1
Employee Department:CSE
Employee Salary:65000
Employee Name:Anoop
Employee ID:2
Employee Department:ECE
Employee Salary:68000
Employee Name:Arun
Employee ID:3
Employee Department:ISE
Employee Salary:62000
8. Write a Python program to find whether the given input is palindrome or not (for both stringand
integer) using the concept of polymorphism and inheritance.
class strPalindrome:
def __init__(self):
self.word=""
self.ll=""
def check(self,s):
self.word = list(s)
ll=self.word.copy()
self.word.reverse()
if (ll==self.word):
print("\nIt is Palindrome")
else:
print("\nIt is Not Palindrome")
class noPalindrome(strPalindrome):
def __init__(self):
super().__init__
def check(self,no):
super().check(str(no))
if __name__=='__main__':
while True:
ch = int(input("Enter 1.For String palindrome 2.For Integer Palindrome 3.To Exit : "))
if ch==1:
text = input("Enter a string to check : ")
s = strPalindrome()
s.check(text)
elif ch==2:
text = int(input("Enter a number to check : "))
s = noPalindrome()
s.check(text)
elif ch==3:
break
else:
print("Invalid choice")
It is Palindrome
Enter 1.For String palindrome 2.For Integer Palindrome 3.To Exit: 1
Enter a string to check: HELLO
It is Not Palindrome
Enter 1.For String palindrome 2.For Integer Palindrome 3.To Exit: 2
Enter a number to check: 121
It is Palindrome
Enter 1.For String palindrome 2.For Integer Palindrome 3.To Exit: 2
Enter a number to check: 123
It is Not Palindrome
Enter 1.For String palindrome 2.For Integer Palindrome 3.To Exit: 3
prev_link = soup.select('a[rel="prev"]')[0]
url = 'http://xkcd.com' + prev_link.get('href')
print("Done")
wb = Workbook()
sheet = wb.active
sheet.title = "Language"
wb.create_sheet(title = "Capital")
ft = Font(bold=True)
for row in sheet["A1:C1"]:
for cell in row:
cell.font = ft
for i in range(2,5):
sheet.cell(row = i, column = 1).value = state[i-2]
sheet.cell(row = i, column = 2).value = lang[i-2]
sheet.cell(row = i, column = 3).value = code[i-2]
wb.save("F:\demo.xlsx")
sheet = wb["Capital"]
ft = Font(bold=True)
for row in sheet["A1:C1"]:
for cell in row:
cell.font = ft
for i in range(2,5):
sheet.cell(row = i, column = 1).value = state[i-2]
sheet.cell(row = i, column = 2).value = capital[i-2]
sheet.cell(row = i, column = 3).value = code[i-2]
wb.save("demo.xlsx")
srchCode = input("Enter state code for finding capital ")
for i in range(2,5):
data = sheet.cell(row = i, column = 3).value
if data == srchCode:
print("Corresponding capital for code", srchCode, "is", sheet.cell(row = i, column = 2).value)
sheet = wb["Language"]
srchCode = input("Enter state code for finding language ")
for i in range(2,5):
data = sheet.cell(row = i, column = 3).value
if data == srchCode:
print("Corresponding language for code", srchCode, "is", sheet.cell(row = i, column = 2).value)
wb.close()
10a) Write a Python program to combine select pages from many PDFs.
import PyPDF2
def merge_pdf_files(file1, file2, output_file,file1_pages,file2_pages):
with open(file1, 'rb') as file1_obj, open(file2, 'rb') as file2_obj:
pdf1 = PyPDF2.PdfReader(file1_obj)
pdf2 = PyPDF2.PdfReader(file2_obj)
pdf_writer = PyPDF2.PdfWriter()
for page_num in range(file1_pages):
page = pdf1.pages[page_num]
pdf_writer.add_page(page)
for page_num in range(file2_pages):
page = pdf2.pages[page_num]
pdf_writer.add_page(page)
with open(output_file, 'wb') as output:
pdf_writer.write(output)
print(f"The PDF files '{file1}' and '{file2}' have been merged into '{output_file}'.")
pdf_file1 = 'F:\Python\sample3.pdf'
pdf_file2 = 'F:\Python\sample4.pdf'
output_pdf = 'F:\Python\merged.pdf'
file1_pages=int(input("Enter the number of file 1 pages"))
file2_pages=int(input("Enter the number of file 2 pages"))
import requests
res = requests.get('https://ipinfo.io/')
data = res.json()
citydata = data['city']
print(citydata)
url = 'https://wttr.in/{}'.format(citydata)
res = requests.get(url)
print(res.text)
OUTPUT:
Bengaluru
Weather report: Bengaluru
\ / Partly cloudy
_ /"".-. +25(26) °C
\_( ). → 19 km/h
/(___(__) 6 km
0.0 mm
┌─────────────┐
┌──────────────────────────────┬───────────────────────┤ Wed 12 Jul
├───────────────────────┬──────────────────────────────┐
│ Morning │ Noon └──────┬──────┘ Evening
│ Night │
├──────────────────────────────┼──────────────────────────────┼────────────────────
──────────┼──────────────────────────────┤
│ \ / Partly cloudy │ _`/"".-. Patchy rain po…│ .-.
Patchy light r…│ _`/"".-. Moderate or he…│
│ _ /"".-. +24(26) °C │ ,\_( ). +28(29) °C │ ( ).
+24(25) °C │ ,\_( ). +22(25) °C │
│ \_( ). → 20-23 km/h │ /(___(__) → 21-26 km/h │ (___(__) → 22-
33 km/h │ /(___(__) → 13-19 km/h │
│ /(___(__) 10 km │ ‘ ‘ ‘ ‘ 9 km │ ‘ ‘ ‘ ‘ 9 km
│ ‚‘‚‘‚‘‚‘ 7 km │
│ 0.0 mm | 0% │ ‘ ‘ ‘ ‘ 0.4 mm | 85% │ ‘ ‘ ‘ ‘ 0.9
mm | 87% │ ‚’‚’‚’‚’ 2.6 mm | 74% │
└──────────────────────────────┴──────────────────────────────┴────────────────────
──────────┴──────────────────────────────┘
┌─────────────┐
┌──────────────────────────────┬───────────────────────┤ Thu 13 Jul
├───────────────────────┬──────────────────────────────┐
│ Morning │ Noon └──────┬──────┘ Evening
│ Night │
├──────────────────────────────┼──────────────────────────────┼────────────────────
──────────┼──────────────────────────────┤
What are the benefits of using Python language as a tool in the present scenario?
The following are the benefits of using Python language:
Object-Oriented Language, High-Level Language, Dynamically Typed language, Extensive support
Libraries, Presence of third-party modules, Open source and community development, Portable and
Interactive, Portable across Operating systems.
PIP is an acronym for Python Installer Package which provides a seamless interface to install
various Python modules. It is a command-line tool that can search for packages over the internet and
install them without any user interaction.
5. Python program to find the sum and average of natural numbers up to n where n is provided
by user.
n=int(input("Enter upto which number you want sum and average"))
sum=0
for i in range(0,n+1):
sum=sum+i
avg=sum/n
print("Result of sum is",sum)
print("Result of Average",avg)
I=1
while i<=10:
14. WAP to print grades obtained by the students and print the appropriate message.
marks=input()
type(marks)
x=int(marks)
if x>=90 and x<100:
print('distinction')
elif x>=80 and x<=90:
print("first")
else :
print("fail")