Professional Documents
Culture Documents
Practical File 2024
Practical File 2024
Q1. Write a menu driven program to input a number and check the following
a. check the number is special number
b. Check the number is Armstrong number
c. check the number is Automorphic number
sol
import math
def special():
n=int(input("Enter a number to check special number:"))
n1=n
rem=sum=0
while(n1>0):
rem=n1%10
n1=n1//10
f=1
for i in range(1,rem+1):
f=f*i
sum=sum+f
if n==sum:
print("It is special number ")
else:
print("It is not special number ")
def armstrong():
n=int(input("Enter no to check armstrong no :"))
n1=n
rem=sum=0
while(n1>0):
rem=n1%10
n1=n1//10
sum=sum+math.pow(rem,3)
if n==sum:
print("It is called armstrong no ")
else:
print("It is not an armstrong no ")
def auto():
n=int(input("Enter a numeber to check automorphic number :"))
n1=n
ctr=rem=sum=0
while(n1>0):
rem=n1%10
n1=n1//10
ctr=ctr+1
sqrnum=n*n
lastdigit=count=0
for i in range(1,ctr+1):
rem=sqrnum%10
lastdigit=lastdigit*10+rem
sqrnum=sqrnum//10
count=count+1
ctr=rem=ld=0
for i in range(1,count+1):
rem=lastdigit%10
ld=ld*10+rem
lastdigit=lastdigit//10
if n==ld:
print("It is an automorphic number ")
else:
print("It is not an automorphic number ")
while True:
print("1. Check Special Number ")
print("2. Check armstrong number ")
print("3. Check special number ")
print("4. Exit ")
choice=int(input("Enter choice <1-4>:"))
if choice==1:
special()
elif choice==2:
armstrong()
elif choice==3:
auto()
elif choice==4:
break
else : print("Wrong choice ")
output :
Q2: Write a program using function to check the number is prime number or not
def prime():
opt=0
n=int(input("Enter the number to check prime number :"))
for i in range(2,n):
if n%i==0:
opt=1
break
i=i+1
if opt==1:
print("It is not a prime number ")
else:
print("It is prime number ")
prime()
output :
Q3: Write a menu driven program to accept a number from the user and check whether the number
is palindrome or perfect number
Sol :
import math
def palindrome(n):
s=""
nlen=len(n)
tnum=int(n)
while (tnum!=0):
rdigit=tnum%10
s=s+str(rdigit)
tnum=tnum//10
if n==s:
print("It is palindrome ")
else:
print("It is not palindrome ")
def perfect_no(n):
s=0
for i in range(1,n):
if (n%i==0):
s=s+i
if s==n:
print("It is perfect no ")
else:
print("It is not perfect no ")
while True :
print("1. Check the perfect number ")
print("2. Check the palindrome number ")
print("3. exit from program ")
choice=int(input("Enter choice :"))
if choice==1:
no=int(input("Enter no to check perfect :"))
perfect_no(no)
elif choice==2:
no=input("Enter no :")
palindrome(no)
elif choice==3:
break
else :
print("Exit from program ")
output:-
Q4: Write a program to input a string using function and count total number of vowel characters in
an input string
def vowel_string(s):
count=0
vowel='aeiouAEIOU'
for i in s:
if i in vowel:
count=count+1
if count>0:
print("Total no of vowels are ",count)
else:
print("There is no vowel")
string=input("Enter string :")
vowel_string(string)
output :
Q5. Write a program to enter a string and perform the following operation on the string using
function
• Total number of characters
• Total number of alphabets
• Total number of digits
• Total number of spaces
Sol:
def test():
alphas=digits=spaces=vchar=0
s=input("Enter string :")
vowel='aeiouAEIOU'
ls=s.lower()
slen=len(ls)
for k in range(slen):
if ls[k].isalpha():
alphas=alphas+1
if ls[k].isdigit():
digits=digits+1
if ls[k].isspace():
spaces=spaces+1
if ls[k] in vowel:
vchar=vchar+1
return slen,alphas,digits,spaces,vchar
l,a,d,s,v=test()
print("Total number of characters :",l)
print("Total no of alphabetic characters :",a)
print("Total no of digits :",d)
print("Total number of spaces:",s)
print("Total number of vowels :",v)
output :
Q6. Write a program using function that checks the string is palindrome or not . A palindrome is a
string that reads the same from left to right and from right to left ex. MALAYALAM ( Do not use
slicing)
Sol :
ef reverse(s,n):
size=len(s)
i=0
while(i<n):
temp=s[size-1-i]
s[size-1-i]=s[i]
s[i]=temp
i=i+1
str1=input("Enter String :")
slist=list(str1)
n=len(slist)//2
reverse(slist,n)
if list(str1)==slist:
print("It is palindrome ")
else:
print("It is not palindrome")
output :
Q7. Write a program to input ‘N’ number of students in a tuple and print the tuple in ascending
order or name
Sol :
name=()
n=int(input("How many names :"))
ctr=1
if n>0:
while ctr<=n:
mname=input("Enter name :")
name=name+(mname,)
ctr=ctr+1
oname=sorted(name)
print("Original name :",name)
print("Sorted name :",oname)
output :-
Q8 Write a program to create a jumble game where computer pick random word from a sequence
tuple . The user guess the word from tuple if it is correct print the appropriate message .
Sol :
words=('python','cobol','c++','java','visual studio ','mysql','fortran')
import random
word=random.choice(words)
correct=word
correct=correct.lower()
jumble=""
while word:
pos=random.randrange(len(word))
jumble+=word[pos]
word=word[:pos]+word[(pos+1):]
print("The jumble word is ",jumble)
guess=input("enter guess:")
while(guess!=correct) and (guess!=""):
print("sorry it is not a word ")
guess=input("Enter guess:")
guess=guess.lower()
if guess==correct:
print("well done . A correct guess")
output-
Q9.Write a program using user defined function to read the contents of file magic.txt and display the
number of alphabet, digits, spaces and total no of lines
Sol :
import os
def count():
tfile="magic.txt"
if os.path.isfile(tfile):
with open (tfile) as f:
alpha=digit=space=lctr=0
while True:
line=f.readline()
if not line:
break
else:
lctr=lctr+1
for k in line:
if k.isalpha():
alpha=alpha+1
if k.isdigit():
digit=digit+1
if k.isspace():
space=space+1
return alpha,digit,space,lctr
a,d,s,l=count()
print("Total no of alphabet :",a)
print("total no of digit :",d)
print("total no of space:",s)
print("total no of lines :",l)
magic.txt file :-
Output :-
Q10. Write a function in Python, which should read each character of a text file remarks.txt ,should
count and display the occurrence of alphabet A and E (Including small letter a and e too)
Sol :
import os
def acount():
afile="remarks.txt"
if os.path.isfile(afile):
f=open(afile,"r")
ctra=ctre=0
while True:
line=f.readline()
if not line:
break
str=line.upper().rstrip()
for k in range(len(str)):
if str[k]=='A' or str[k]=='a':
ctra=ctra+1
if str[k]=='E' or str[k]=='e':
ctre=ctre+1
print("Total number of A is :",ctra)
print("Total number of E is :",ctre)
acount()
File remarks.txt –
Output –
Q11. Write a function countdm() to read the content of text file “delhi.txt” and display all those lines
on the screen. Which are either starting with ‘D’ or starting with ‘M’
Sol :
def countdm(file1):
f=open(file1,"r")
ctr=0
print("The lines are ")
while 1:
line=f.readline()
line=line.rstrip()
print(line)
if not line:
break
if line[0]=='D' or line[0]=='M':
ctr=ctr+1
return ctr
f.close()
file1="delhi.txt"
result=countdm(file1)
if result >0:
print(" Total no of lines started from D or M :",result)
else:
print(" Not a single line started from D or M ")
output :-
Q12. A binary file “tele.dat” contains customer name and telephone number . Write a function to do
the following
a. Append the records in a file
b. Display the name for a given telephone number if the telephone number does not exist then
display the message “ Record not found “
sol :
import pickle
def add_rec(file):
fobj=open(file,'ab+')
if not fobj:
print("File is not created ")
else:
while True:
rec=[]
name=input("Enter name :")
rec.append(name)
tno=int(input("Enter telephone number :"))
rec.append(tno)
pickle.dump(rec,fobj)
ch=input("Do you want next record ?")
if ch in 'Nn':
break
fobj.close()
def search(file):
mtno=int(input("Enter telephone number :"))
fobj=open(file,'rb')
if not fobj:
print("File does not exist ")
else:
try:
trec=[]
while True :
rec=[]
rec=pickle.load(fobj)
if rec[1]==mtno:
print("Record found :")
print(rec)
except EOFError:
fobj.close()
while True:
print(" 1.Add records in binary file ")
print("2. Search the telephone number ")
print("3. Exit")
choice=int(input("Enter choice :"))
if choice==1:
file1="tele.dat"
add_rec(file1)
elif choice==2:
file1="tele.dat"
search(file1)
elif choice==3:
break
else:
print("Wrong choice try again ")
output :-
Q13. Write a program to read the content from a text file “dictionary .txt” and count the number of
words having length more than 5 letter in them. Assume that each word is separated from other with
a single space.
Sol:
import os
file1="dict.txt"
if os.path.isfile(file1):
f=open(file1,'r')
print(" Words more than 5 characters are ")
while 1:
line=f.readline()
if not line:
break
str=line.rstrip()
list1=str.split(' ')
for k in list1:
if len(k)>5:
print(k)
f.close()
else:
print("File does not exist")
input file :
Output :-
14. Write a program in python to read lines from text file “ india.txt” . To find and display the
occurrence of the word “India “
import os
def wordindia():
ctr=0
if os.path.isfile("india.txt"):
f=open('india.txt','r')
lines=f.read()
while lines:
word=lines.split()
for w in word:
if w=='India':
ctr=ctr+1
lines=f.read()
print("Total no of words ",ctr)
f.close()
else:
print("File does not exist")
wordindia()
output
Input :-
15. Write a program in python to define and call the user defined function
a) add()- To accept and add data of an employee to a csv file record.csv .Each record consist of a list
with field elements as empid, name and mobile to store employee id , employee name and
employee salary respectively
b) counter()- To count the number of records present in the csv named records.csv .
import csv
def add():
f=open("record.csv","w",newline='')
wobj=csv.writer(f)
wobj.writerow(['empid','empname','salary'])
while True:
wempid=int(input("Enter employee id :"))
wempname=input("Enter employee name :")
wsal=int(input("Enter salary :"))
rec=[wempid,wempname,wsal]
wobj.writerow(rec)
ch=input("Do you want to enter more record ?")
if ch in 'Nn':
break
f.close()
def count():
f=open('record.csv','r')
ctr=0
robj=csv.reader(f)
for i in robj:
ctr=ctr+1
print(ctr)
while True:
print("1. Add records to csv file ")
print("2. Count the no of records")
print("3. Exit ")
choice=int(input("Enter your choice :"))
if choice==1:
add()
elif choice==2:
count()
elif choice==3:
break
else:
print("Wrong choice ")
add()
count()
16. Raghav has created a vocabulary list. You need to help him to create a program with separate
user defined function to perform the following
• Traverse the content of the list and push the entries having less than 7 characters into a stack
• Display the content of stack
top=-1
stack=[]
def push(stack,top):
word=[]
no=int(input("Enter total no of words"))
for i in range(no):
w=input("Enter word :")
word.append(w)
for k in word:
if len(k)<7:
stack.append(k)
top=top+1
return top
def show(stack,top):
if len(stack)<=0:
print("stack is empty ")
else:
k=top
print("Stack is :")
while k>=0:
print(stack[k])
k=k-1
top=push(stack,top)
show(stack,top)
17. Write a program to perform the following using user defined function/method.
a) push()- Enter the doctor details (doctor name, department, salary) and store it to stack
where stack is a list.
b)pop():- delete the doctors details from stack
c) show():- Display the content of stack
sol :
stack=[]
top=-1
def push(stack,top):
while True:
dname=input("Enter doctor name :")
dept=input("Enter department :")
sal=int(input("Enter salary :"))
s=[dname,dept,sal]
stack.append(s)
top=top+1
ch=input("Do you want next record ?")
if ch in 'Nn':
break
return top
def pop(stack,top):
if len(stack)<=0:
print("Stack is empty ")
else:
dname,dept,sal=stack.pop()
print("Doctor name :",dname)
print("Department :",dept)
print("Salary :",sal)
top=top-1
return top
def show(stack,top):
k=top
print("Stack content is ...")
if len(stack)<=0:
print("stack is empty ")
else:
while k>=0:
print(stack[k])
k=k-1
while True:
print(" 1.Enter doctor detail in a stack ")
print(" 2. Delete doctor detail from stack ")
print(" 3. Display the stack content ")
print(" 4. Exit from stack ")
choice=int(input("Enter choice :"))
if choice==1:
top=push(stack,top)
elif choice==2:
top=pop(stack,top)
elif choice==3:
show(stack,top)
elif choice==4:
break
else:
print(" Wrong choice ")
18. Write a function to replace first half of the list of numbers with second half of the list of
numbers
Sol :
a=[2,4,1,6,7,9,23,10]
def exchange(a):
print("The input array is :",a)
n=len(a)
for i in range(int(n/2)):
temp=a[i]
a[i]=a[int(n/2)+i]
a[int(n/2)+i]=temp
print("The output is :",a)
exchange(a)
19. Write a function/method to enter 10 values from a list . Store even position values in even list
and odd position values in odd list.
Sol :
all=[]
no=int(input("Enter how many values ?"))
for i in range(no):
val=int(input("Enter value :"))
all.append(val)
even=[]
odd=[]
for i in range(no):
if i%2==0:
even.append(all[i])
else:
odd.append(all[i])
print("The even list is ",even)
print("The odd list is ",odd)
output :-
Python 3.7.9 (bundled)
>>> %Run t19.py
Enter how many values ?10
Enter value :2
Enter value :4
Enter value :5
Enter value :6
Enter value :7
Enter value :8
Enter value :9
Enter value :11
Enter value :12
Enter value :13
The even list is [2, 5, 7, 9, 12]
The odd list is [4, 6, 8, 11, 13]
>>> %Run t19.py
20. Write a function to enter two list of numbers and merge them to create a sorted list.
Sol:
r1=[2,8,15,23,37]
r2=[4,6,15,20]
s=[]
def merge(r1,r2):
r3=[]
a=0
b=0
while a<len(r1) and b<len(r2):
if r1[a]<r2[b]:
r3.append(r1[a])
a=a+1
else:
r3.append(r2[b])
b=b+1
while a<len(r1):
r3.append(r1[a])
a=a+1
while b<len(r2):
r3.append(r2[b])
b=b+1
return r3
print (" The first array :",r1)
print(" The second array :",r2)
s=merge(r1,r2)
print("The merged array is ",s)
output :-
21. Write a program using table employee under Archies database to enter employee details in a
table also write a function to display the record
Sol :
import pymysql
con=pymysql.connect(host='localhost', user='root',passwd='123',db='archies')
cur=con.cursor()
def add_record():
while True:
mecode=int(input("Enter employee code :"))
mename=input("Enter employee name :")
mdept=input("Enter department :")
msal=int(input("Enter monthly sal :"))
mgrade=input("Enter grade :")
sql="insert into emp values({},'{}','{}',{},'{}')".format(mecode,mename,mdept,msal,mgrade)
cur.execute(sql)
con.commit()
print("Record is added ")
choice=input("Enter next records ?")
if choice in 'Nn':
break
def show():
sql="select * from emp"
cur.execute(sql)
rec=cur.fetchall()
print(" The recors is ...")
for i in rec:
print(i)
con.close()
cur.close()
add_record()
show()
output –
22. Write a function search_record() which is used to search the particular record from employee
table under archies database and display the record.
Sol:
import pymysql
con=pymysql.connect(host='localhost', user='root',passwd='123',db='archies')
cur=con.cursor()
def search_record():
meno=int(input("Enter employee no :"))
sql=" select * from emp where eno=%s"
data=meno
cur.execute(sql,data)
row=cur.fetchone()
print("-------------- search record -----------------")
print(row)
search_record()
con.close()
cur.close()
output :-
23. Write a program to increase the salary of all employees by 500 in employee table under archies
database.
Sol :
import pymysql
con=pymysql.connect(host='localhost', user='root',passwd='123',db='archies')
cur=con.cursor()
def update_record():
msal=int(input("Enter salary increment :"))
sql=" update emp set sal=sal+%s"
data=msal
cur.execute(sql,data)
con.commit()
def show():
sql="select * from emp"
cur.execute(sql)
rows=cur.fetchall()
print("The updated records are :")
for r in rows:
print(r)
update_record()
show()
con.close()
cur.close()
input :-
Output :-
24.Write a function delete_rec to delete a particular employee record from employee table under
archies database.
Sol
import pymysql
con=pymysql.connect(host='localhost', user='root',passwd='123',db='archies')
cur=con.cursor()
def delete_record():
meno=int(input("Enter salary increment :"))
sql=" delete from emp where eno=%s"
data=meno
cur.execute(sql,data)
print("The employee data is deleted ")
con.commit()
def show():
sql="select * from emp"
cur.execute(sql)
rows=cur.fetchall()
print("The updated records are :")
for r in rows:
print(r)
delete_record()
show()
con.close()
cur.close()
input :-
Output –
SQL QUERIES
Sol :
3. Write a query to Enter the following data into travel table : (V01,VOLVOBUS ,150)
Also insert the following data into travel table : (101, K.NIWAL, 13/12/2015, 200,VO1,32)
4. Display all records from travel table :
Sol :
6. Write a query to display cno, cname, traveldate from the table travel in descending order of cno
Sol :
7. Write a query to display cname of all customer from the table travel who are travelling by vechicle
with code vo1 or vo2
8. Write a query to increase the nop by 10 in a travel table whose vcode is ‘VO5’
9. Write a query to display those travellers whose 2nd character of cname is ‘a’
12. Write a query to display vechicletype , perkm , cno,cname ,nop from table vehicle and travel
13. Delete those records from travel table whose traveldate is before 2016
`````````````