#Write a code in python to accept a set of integer numbers in a list.
Sort the
elements in ascending order by insertion sort technique. Display the
elements of the sorted list.
L1=eval(input("Enter the list elements:"))
print("List elements:",L1)
p=len(L1)
for i in range(1,p):
temp = L1[i]
ptr = i-1
while(L1[ptr]>temp and ptr >= 0):
ptr=ptr-1
else:
L1[ptr+1]=temp
print("List elements in ascending order:")
for i in range(1,p):
print(L1[i])
#armstrong number
def check_armstrong():
number=int(input("Enter your desired number: "))
digits=str(number)
n=len(digits)
arm_sum=sum(int(digit) ** n for digit in digits)
if arm_sum==number:
print(f"{number} is an Armstrong number.")
else:
print(f"{number} is not an Armstrong number.")
#main
check_armstrong()
#magic square
def check_magic_square():
print("Enter the elements of the first row (3 numbers separated by spaces):")
l1 = list(map(int, input().split()))
print("Enter the elements of the second row (3 numbers separated by spaces):")
l2 = list(map(int, input().split()))
print("Enter the elements of the third row (3 numbers separated by spaces):")
l3 = list(map(int, input().split()))
row_sum1 = sum(l1)
row_sum2 = sum(l2)
row_sum3 = sum(l3)
col_sum1 = l1[0] + l2[0] + l3[0]
col_sum2 = l1[1] + l2[1] + l3[1]
col_sum3 = l1[2] + l2[2] + l3[2]
diag1_sum = l1[0] + l2[1] + l3[2]
diag2_sum = l1[2] + l2[1] + l3[0]
if (row_sum1 == row_sum2 == row_sum3 ==
col_sum1 == col_sum2 == col_sum3 ==
diag1_sum == diag2_sum):
print("This is a magic square!")
else:
print("This is NOT a magic square.")
check_magic_square()
#check palindrome
def check_palin():
string=input("Enter the string: ").lower()
if string==string[::-1]:
print(f'"{string}" is a palindrome.')
else:
print(f'"{string}" is not a palindrome.')
#main
check_palin()
# to check prime number
def check_prime():
number=int(input("Enter a number: "))
if number<2:
print(f"{number} is neither prime nor composite.")
return
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
print(f"{number} is a composite number.")
return
print(f"{number} is a prime number.")
#main
check_prime()
#
import massconversion
ch='Y'
while ch=='Y'or ch=='y':
print("1. kg to tonne")
print("2. kg to pound")
print("3. tonne to kg")
print("4. pound to kg")
x=int(input("Enter your choice:"))
if x==1:
print([Link]())
if x==2:
print([Link]())
if x==3:
print([Link]())
if x==4:
print([Link]())
ch=input("do you want to perform another function?(Y/N)")
//Library//
def kgtotonne():
m=float(input("enter the mass in kg:"))
t=m*0.001
return t
def kgtopound():
m=float(input("enter the mass in kg:"))
t=m*2.20462
return t
def tonnetokg():
m=float(input("enter the mass in tonne:"))
t=m/0.001
return t
def poundtokg():
m=float(input("enter the mass in pound:"))
t=m/2.20462
return t
#write a function Lines() and create a file [Link] in read mode to
retrieve all the lines. Count the no. of lines available in the file and display all
the lines with line numbers
Sol:-
def Lines():
f1=open("[Link]")
print("Display lines and line nos.")
countlines=0
line=True
while line:
line=[Link]()
if line=="":
continue
countlines=countlines+1
print(countlines,' ',line,end='')
[Link]()
Lines()
Output:-
#Write a function Paragraph() in python to create a txt file [Link] to
write a few lines into it. If you don’t want to write more lines enter 0 to quit
the function.
Sol:-
def Paragraph():
f1=open("[Link]",'w')
a=int(input("press any character to continue and 0 to quit:"))
while a!=0:
line=input("Write a paragraph: ")
[Link](line+'\n')
a=int(input("press any character to continue and 0 to quit:"))
[Link]()
Paragraph()
Output:-
#A) Write a function to read all the lines from a text file ‘[Link]’
display all those records for which the highest price of an exhibit is less than
200000.
B) Write a function to count the number of lines in the file and display the
same.
A)
def gallery_read():
f1=open('[Link]','r')
for i in f1:
L=[Link](',')
if int(L[3])<200000:
print(i)
[Link]()
B)
def gallery_count():
f1=open('[Link]','r')
str=[Link]()
L=len(str)
gallery_read()
gallery_count()
#Write a program to store some integer numbers as a list element in the
binary file ‘[Link]’ till the user wants. Finally open the file in
appropriate mode to retrieve and display the elements
Sol:-
import pickle
f=open("[Link]","wb")
Number=[]
ch='Y'
while ch=='Y' or ch=='y':
n=eval(input("Enter an integer number:"))
data=[n]
[Link](data)
ch=input("Do you want to make more entries?(Y/N):")
[Link](Number,f)
[Link]()
print("Input Saved!")
f=open("[Link]","rb")
print("Content of the file [Link]:")
try:
while True:
rec=[Link](f)
print(rec)
except:
[Link]()
print("Execution complete!")
#Write a function def Display() in Python which reads the integer elements
form the previously created binary file ‘[Link]’. Display only those
numbers which are either divisible by 7 or ends with digit 7
Sol:-
import pickle
def display():
f1= open("[Link]","rb")
print("content of the file [Link]:")
try:
while 1:
rec=[Link](f1)
print(rec)
print("number divisible by 7 or ends with 7 are:")
for a in rec:
if((a[0]%7==0)or(a[0]%10==7)):
print(a[0])
except:
[Link]()
print("program ends!")
display()
# Write a function ‘def Prize’ in python to record all the prize winners of class
12 students and store all the names along with class and rank in a binary file
‘[Link]’
Sol:-
import pickle
def Prize_update():
f=open("[Link]","rb+")
x=int(input("Enter the number of entries you want to make:"))
for i in range(x):
print("Enter the....")
a=str(input("=NAME=:"))
b=str(input("=CLASS=:"))
c=int(input("=RANK=:"))
L=[a,b,c]
[Link](L,f)
print("Input saved!")
[Link]()
def Prize_display():
f=open("[Link]","rb")
num=int(input("Enter the no of entries you want to view:"))
print("[=NAME=,=CLASS=,=RANK=]")
for i in range(num):
a=[Link](f)
print(a)
[Link]()
print("Press 'W' to update information")
print("Press 'R' to display information")
a=input(":")
if a=='W':
Prize_update()
else:
Prize_display()
#Write a program to create a file ‘[Link]’ to keep the records of Hotel
Bookings with their tariffs.
import csv
f1=open('[Link]','w',newline='\r\n')
writer=[Link](f1)
[Link](["Room Type","Days","Total cost"])
record=[]
ch='Y'
while ch=='Y' or ch=='y':
tp=input("Enter the Room Type:")
ds=input("Enter the Number of Days:")
tc=input("Enter the Total Cost:")
MyList=[tp,ds,tc]
[Link](MyList)
ch=input("Do you want to enter more records...?(Y/N):")
for i in record:
[Link](i)
[Link]()
#Write a function def Display () to read all records from the file
‘[Link]’ to display the details of all laptops of various companies.
import csv
def display():
f1=open("[Link]","r")
reader=[Link](f1)
next(reader)
print("record of the files are:")
for a in reader:
if(a[1]=="Laptop"):
print(a)
[Link]()
#main
display()
#
import csv
def participate():
fw=open("[Link]","a")
writer=[Link](fw)
[Link](["school name","name1","class","name2","class"])
record=[]
ch='Y'
while ch=='Y' or ch=='y':
nm=input("enter school name: ")
name1=input("enter the name of first participant:")
cs1=input("enter the class of first participant:")
name2=input("enter the name of second participant:")
cs2=input("enter the class of second participant:")
mylist=[nm,name1,cs1,name2,cs2]
[Link](mylist)
ch=input("do you want to enter more records...?(Y/N):")
for i in record:
[Link](i)
[Link]()
participate()
#You have a stack named CountryStack that contains records of different
countries. Each country record is represented as a list containing the name,
capital, and population of that country. Write the following user-defined
functions in python to perform that specific operations on the stack
countryStack.
(a)PUSH_COUNTRY (Countrystack, country_rec): The function takes the stack
countrystack and new country record country_rec as arguments and pushes
the new country record onto the stack.
(b) POP_COUNTRY (countrystack): this function pops the topmost country
record from the stack and returns it. If the stack is empty then function
should return the message “underflow”.
(c) PEEP (countrystack) : this function displays the topmost element of the
stack without deleting it. If the stack is empty the function displays ‘none’.
def push(countrystack,country_rec):
[Link](country_rec)
print("Information uploaded:")
def isEmpty(countrystack):
if countrystack == []:
return True
else:
return False
def pop(countrystack):
if isEmpty(countrystack):
print("countrystack is empty...underflow")
else:
print("The last element of countrystack is",countrystack[-1])
[Link]()
def peep(countrystack):
if isEmpty(countrystack):
print("countrystack is empty...none")
else:
print(countrystack[::-1])
#main
countrystack=[]
choice='Y'
while choice=='Y' or choice=='y':
print("countrystack OPERATION")
print("1. PUSH_COUNTRY")
print("2. POP_COUNTRY")
print("3. PEEP")
ch=int(input("Enter your choice:"))
if ch==1:
Name=input("Enter name of country:")
capital=input("Enter capital of country:")
popu=int(input("Enter the population:"))
country_rec=[Name,capital,popu]
push(countrystack,country_rec)
if ch==2:
pop(countrystack)
if ch==3:
peep(countrystack)
choice=input("Do you want to enter more records...?(Y/N):")
SQL
#
import [Link] as mycon
mydb=[Link](host='localhost',database='PERFORMANCE',user='root',
password='12345')
mycursor=[Link]()
[Link]("SELECT * FROM STUDENT")
record=[Link]()
for i in record:
print(i)
2) Display the details of the students having ‘I’ in their name.
import [Link] as mycon
mydb=[Link](host='localhost',database='PERFORMANCE',user='root',
password='12345')
mycursor=[Link]()
[Link]("SELECT * FROM STUDENT WHERE NAME LIKE'%I%'")
record=[Link]()
for i in record:
print(i)
3) Display the student details who’s grade is ‘A’.
import [Link] as mycon
mydb=[Link](host='localhost',database='PERFORMANCE',user='root',
password='12345')
mycursor=[Link]()
[Link]("SELECT * FROM STUDENT WHERE GRADE = 'A'")
record=[Link]()
for i in record:
print(i)
4) Display the average performance of the student table.
import [Link] as mycon
mydb=[Link](host='localhost',database='PERFORMANCE',user='root',
password='12345')
mycursor=[Link]()
[Link]("SELECT AVG(TOTAL) AS AVERAGE FROM STUDENT")
record=[Link]()
for i in record:
print(i)
# Creating a table in python interfaced MySql database.
import [Link] as mycon
mydb=[Link](host='localhost',database='HOSPITAL',user='root',passw
ord='12345')
mycursor=[Link]()
[Link]("CREATE TABLE DOCTOR(D_ID CHAR(5)NOT NULL PRIMARY
KEY,D_NAME VARCHAR(30),DEPT VARCHAR(25),CATEGORY VARCHAR(25))")
[Link]
2) Inserting data into table DOCTOR.
import [Link] as mycon
mydb=[Link](host='localhost',database='HOSPITAL',user='root',passw
ord='12345')
mycursor=[Link]()
[Link]("INSERT INTO DOCTOR VALUES('D01','SUDIR
SINGH','ENT','MBBS')")
[Link]("INSERT INTO DOCTOR VALUES('D02','ASHISH
SEN','HEART','SURGEON')")
[Link]("INSERT INTO DOCTOR VALUES('D03','SHILPA
DUTTA','ENT','SURGEON')")
[Link]("INSERT INTO DOCTOR VALUES('D04','DEBARUN
BOSE','NEUROLOGIST','MBBS')")
[Link]("INSERT INTO DOCTOR VALUES('D05','ABIR
BISWAS','PSYCHOLOGY','MBBS')")
[Link]()
3) Display the count of doctors based on ‘CATEGORY’.
import [Link] as mycon
mydb=[Link](host='localhost',database='HOSPITAL',user='root',passw
ord='12345')
mycursor=[Link]()
[Link]("SELECT CATEGORY,COUNT(D_ID) FROM DOCTOR GROUP
BY CATEGORY")
record=[Link]()
for i in record:
print(i)
4) Display the details of the doctors in ‘ENT’.
import [Link] as mycon
mydb=[Link](host='localhost',database='HOSPITAL',user='root',passw
ord='12345')
mycursor=[Link]()
[Link]("SELECT * FROM DOCTOR WHERE DEPT = 'ENT'")
record=[Link]()
for i in record:
print(i)
5) Display the details of the doctors whose name start with ‘S’.
import [Link] as mycon
mydb=[Link](host='localhost',database='HOSPITAL',user='root',passw
ord='12345')
mycursor=[Link]()
[Link]("SELECT * FROM DOCTOR WHERE D_NAME LIKE'S%'")
record=[Link]()
for i in record:
print(i)
6) Update the name of the doctor whose ‘ID’ is ‘D05’ as ‘ABIR BANERJEE’.
import [Link] as mycon
mydb=[Link](host='localhost',database='HOSPITAL',user='root',passw
ord='12345')
mycursor=[Link]()
[Link]("UPDATE DOCTOR SET D_NAME='ABIR BANERJEE' WHERE
D_NAME='ABIR BISWAS'")
[Link]()
7) Delete the details of the doctor whose ‘ID’ is ‘D03’.
import [Link] as mycon
mydb=[Link](host='localhost',database='HOSPITAL',user='root',passw
ord='12345')
mycursor=[Link]()
[Link]("DELETE FROM DOCTOR WHERE D_ID = 'D03'")
[Link]()