All Programs Merged Edited
All Programs Merged Edited
Created By:
Hanumanthu
Dept. CSE
Dedicated To..
My Dear All Friends and Supported YouTube Friends
Subject Code:21CS46
Program-01
Aim: Introduce the Python fundamentals, data types, operators, flow control
and exception handling in Python
A) Write A Python Program To Find The Best Of Two Test Average Marks
Out Of Three Test’s Marks Accepted From The User.
PROGRAM
minimum=min(marks1,marks2,marks3)
sumofbest2=marks1+marks2+marks3-minimum
avgofbest2=sumofbest2/2
OUTPUT
Subject Code:21CS46
Program-02
PROGRAM
def fn(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
if num > 0:
else:
print("Error in input")
OUTPUT
PROGRAM
print(bin(decimal),"in Binary")
print(oct(decimal),"in Octal")
OUTPUT
Subject Code:21CSL46
Program-03
a) Write a Python program that accepts a sentence and find the number of
words, digits, uppercase letters and lowercase letters.
PROGRAM
w, d, u, l = 0, 0, 0, 0
#lenth word
l_w = s.split()
w = len(l_w)
for c in s:
#character is digits
if c.isdigit():
d=d+1
#upper CASE
elif c.isupper():
u=u+1
#lowerCase
elif c.islower():
l=l+1
OUTPUT
b) Write a Python program to find the string similarity between two given
strings
PROGRAM
short = len(str2)
long = len(str1)
else:
short = len(str1)
long = len(str2)
matchCnt = 0
for i in range(short):
if str1[i] == str2[i]:
matchCnt += 1
print(matchCnt/ long)
OUTPUT
Subject Code:21CSL46
Program-04
PROGRAM
#Function Definition
def insertion_sort(alist):
temp = alist[i]
j=i-1
alist[j + 1] = alist[j]
j=j-1
alist[j + 1] = temp
#function call
insertion_sort(alist)
print(alist)
OUTPUT
def mergesort(list1):
if len(list1) > 1:
mid = len(list1) // 2
left = list1[:mid]
right = list1[mid:]
mergesort(left)
mergesort(right)
i=0
j=0
k=0
list1[k] = left[i]
i=i+1
k=k+1
else:
list1[k] = right[j]
j=j+1
k=k+1
while i < len(left): # if there is element left out in the left list
list1[k] = left[i]
i=i+1
k=k+1
while j < len(right): # if there is element left out in the right list
list1[k] = right[j]
j=j+1
k=k+1
list1 = [int(x) for x in list1] # for every element in list1 we will call merge sort
mergesort(list1)
print(list1)
OUTPUT
PROGRAM
class sol_Roman:
#Function Definition
roman_no = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
integer_no = 0
for i in range(len(s)):
else:
integer_no += roman_no[s[i]]
return integer_no
#this is the A single One Line No Break Points here Mind Your Program Line
OUTPUT
Subject Code:21CSL46
Program-05
PROGRAM
"""
@author: Hanumanthu
"""
import re
def isphonenumber(numStr):
if len(numStr) != 12:
return False
for i in range(len(numStr)):
if i==3 or i==7:
if numStr[i] != "-":
return False
else:
if numStr[i].isdigit() == False:
return False
return True
def chkphonenumber(numStr):
ph_no_pattern = re.compile(r'^\d{3}-\d{3}-\d{4}$')
if ph_no_pattern.match(numStr):
return True
else:
return False
if isphonenumber(ph_num):
else:
if chkphonenumber(ph_num):
else:
OUTPUT
b) Develop a python program that could search the text in a file for phone
numbers (+919900889977) and email addresses ([email protected])
PROGRAM
"""
@author: Hanumanthu
"""
import re
phone_regex = re.compile(r'\+\d{12}')
email_regex = re.compile(r'[A-Za-z0-9._]+@[A-Za-z0-9]+\.[A-Z|a-z]{2,}')
for line in f:
matches = phone_regex.findall(line)
print(match)
matches = email_regex.findall(line)
print(match)
example.txt(Text File)
+917348878215
+919812569090
+916567976156
+917543679809
OUTPUT
Subject Code:21CSL46
Program-06
a) 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
"""
@author: Hanumanthu
"""
import os.path
import sys
if not os.path.isfile(fname):
sys.exit(0)
lineList = infile.readlines()
for i in range(20):
cnt = 0
cnt += line.count(word)
Sample.txt(Text File)
Better hope the life-inspector doesn't come around while you have your
You can create your own opportunities this week. Blackmail a senior
executive.
Be different: conform.
to deprive the poor of darkness, and one to win a Pulitzer prize for
OUTPUT
Program
"""
Created on Wed May 24, 2023
@author: Hanumanthu
"""
import os
import sys
import pathlib
import zipfile
if not os.path.isdir(dirName):
print("Directory", dirName, "doesn't exists")
sys.exit(0)
curDirectory = pathlib.Path(dirName)
if os.path.isfile("myZip.zip"):
print("Archive", "myZip.zip", "created successfully")
else:
print("Error in creating zip archive")
Output
Subject Code:21CSL46
Program-07
PROGRAM
"""
@author: Hanumanthu
"""
import math
class Shape:
self.area = 0
self.name = ""
def showArea(self):
class Circle(Shape):
self.area = 0
self.name = "Circle"
self.radius = radius
def calcArea(self):
class Rectangle(Shape):
self.area = 0
self.name = "Rectangle"
self.length = length
self.breadth = breadth
def calcArea(self):
class Triangle(Shape):
self.area = 0
self.name = "Triangle"
self.base = base
self.height = height
def calcArea(self):
c1 = Circle(5)
c1.calcArea()
c1.showArea()
r1 = Rectangle(5, 4)
r1.calcArea()
r1.showArea()
t1 = Triangle(3, 4)
t1.calcArea()
t1.showArea()
OUTPUT
Program
"""
@author: Hanumanthu
"""
class Employee:
self.name = ""
self.empId = ""
self.dept = ""
self.salary = 0
def getEmpDetails(self):
def showEmpDetails(self):
print("Employee Details")
def updtSalary(self):
e1 = Employee()
e1.getEmpDetails()
e1.showEmpDetails()
e1.updtSalary()
Output
Subject Code:21CSL46
Program-08
PROGRAM
"""
@author: Hanumanthu
"""
class PaliStr:
self.isPali = False
if myStr == myStr[::-1]:
VTU 4TH SEM Page 1
21CSL46 | PYTHON PROGRAMMING LABORATORY |
self.isPali = True
else:
self.isPali = False
return self.isPali
class PaliInt(PaliStr):
self.isPali = False
temp = val
rev = 0
while temp != 0:
dig = temp % 10
temp = temp // 10
if val == rev:
self.isPali = True
else:
self.isPali = False
return self.isPali
stObj = PaliStr()
if stObj.chkPalindrome(st):
else:
intObj = PaliInt()
if intObj.chkPalindrome(val):
else:
OUTPUT
Subject Code:21CSL46
Program-09
PROGRAM
"""
@author: Hanumanthu
"""
import requests
import os
url = 'https://xkcd.com/1/'
if not os.path.exists('xkcd_comics'):
os.makedirs('xkcd_comics')
while True:
res = requests.get(url)
res.raise_for_status()
if comic_elem == []:
else:
print(f'Downloading {comic_url}...')
res = requests.get(comic_url)
res.raise_for_status()
image_file = open(os.path.join('xkcd_comics',
os.path.basename(comic_url)), 'wb')
image_file.write(chunk)
image_file.close()
prev_link = soup.select('a[rel="prev"]')[0]
if not prev_link:
break
OUTPUT
Program
"""
Created on Wed May 24, 2023
@author: Hanumanthu
"""
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
wb.save("demo.xlsx")
sheet = wb["Capital"]
ft = Font(bold=True)
for row in sheet["A1:C1"]:
for cell in row:
cell.font = ft
wb.save("demo.xlsx")
sheet = wb["Language"]
wb.close()
OUTPUT
Subject Code:21CSL46
Program-10
PROGRAM
"""
@author: Hanumanthu
"""
pdf_writer = PdfWriter()
pdf1_reader = PdfReader(pdf1)
page = pdf1_reader.pages[num - 1]
VTU 4TH SEM Page 1
21CSL46 | PYTHON PROGRAMMING LABORATORY |
pdf_writer.add_page(page)
pdf2_reader = PdfReader(pdf2)
page = pdf2_reader.pages[num - 1]
pdf_writer.add_page(page)
pdf_writer.write(output)
OUTPUT
b) Write a python program to fetch current weather data from the JSON file
Program
"""
Created on Wed May 24, 2023
@author: Hanumanthu
"""
import json
{
"coord": {
"lon": -73.99,
"lat": 40.73
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}
],
"base": "stations",
"main": {
"temp": 10.45,
"feels_like": 12.74,
"temp_min": 14.44,
"temp_max": 16.11,
"pressure": 1017,
"humidity": 64
},
"visibility": 10000,
"wind": {
"speed": 8.63,
"deg": 180
},
"clouds": {
"all": 1
},
"dt": 1617979985,
"sys": {
VTU 4TH SEM Page 5
21CSL46 | PYTHON PROGRAMMING LABORATORY |
"type": 1,
"id": 5141,
"country": "INDI",
"sunrise": 1617951158,
"sunset": 1618000213
},
"timezone": -14400,
"id": 5128581,
"name": "New York",
"cod": 200
}
OUTPUT
THANKING YOU
Visit our Official Website: http://searchcreators.org/