0% found this document useful (0 votes)
1K views

Grade 12 Python Practical Questions With Solutions

The document contains 12 programming questions related to Python. The questions cover topics like menu driven programs, Fibonacci series, factorials, stacks, queues, databases, searching, sorting and binary search. Sample code is provided as answers to each question involving database connectivity using MySQL, data structures like stacks and queues, recursion, and other Python programming concepts.

Uploaded by

Purvesh Sohony
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views

Grade 12 Python Practical Questions With Solutions

The document contains 12 programming questions related to Python. The questions cover topics like menu driven programs, Fibonacci series, factorials, stacks, queues, databases, searching, sorting and binary search. Sample code is provided as answers to each question involving database connectivity using MySQL, data structures like stacks and queues, recursion, and other Python programming concepts.

Uploaded by

Purvesh Sohony
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

1) Write a menu driven program in python to display Fibonacci series of a given

no and print factorial of a given no. Show result to the examiner.


Ans:
ch='Y'
while (ch=='Y' or ch=='y'):
print("Enter 1 : fibonacci series:")
print("Enter 2 : factorial:")
opt=int(input('enter ur choice:='))
if opt==1:
n=int(input('enter no. of terms:'))
no1=1
no2=0
x=1
while(x<=n):
no3=no1+no2
no1=no2
no2=no3
print (no3)
x=x+1
elif opt==2:
f=1
n=int(input('enter no:'))
for i in range(1,n+1):
f=f*i
print('factorial is:',f)
else:
print('invalid choice')
ch=(input('want to continue?'))

2) Write a python code to add student using mysql connectivity and show result to
the examiner. Create database and table as below:
Name of database =school
Name of table = student (roll,name,age,class,city) give primary key and not null
constraints
Ans:
import mysql.connector
mydb=mysql.connector.connect(host="localhost",\
user="root",\
passwd="root",\
database="school")
print(mydb)
mycursor=mydb.cursor()
L=[]
roll=int(input("Enter the roll number : "))
L.append(roll)
name=input("Enter the Name: ")
L.append(name)
age=int(input("Enter Age of Student : "))
L.append(age)
class=input("Enter the Class : ")
L.append(class)
city=input("Enter the City of the Student : ")
L.append(city)
stud=(L)
sql="insert into student (roll,name,age,class,city) values (%s,%s,%s,%s,%s)"
mycursor.execute(sql,stud)
mydb.commit()

3) Write a menu driven program to push book no in stack and pop it from stack
Ans:
stk=[]
ch='Y'
while(ch=='Y' or ch=='y'):
print("Enter 1 : Push")
print("Enter 2 : Pop")
opt=int(input('enter ur choice:='))
if opt==1:
d=int(input("enter book no : "))
stk.append(d)
elif opt==2:
if (stk==[]):
print( "Stack empty")
else:
p=stk.pop()
print ("Deleted element:", p)
else:
print('invalid choice')
ch=(input('want to continue?'))

4) Write a python code to delete student as per given roll number in using mysql
connectivity and show result to the examiner.
Create database and table as below:
Name of database =school
Name of table = student(roll,name,age,class,city) give possible constraints on
your own. Insert 3 records in table.
Ans:
import mysql.connector

mydb=mysql.connector.connect(host="localhost",\
user="root",\
passwd="root",\
database="school")
print(mydb)
mycursor=mydb.cursor()
roll=int(input("Enter the roll number of the student to be deleted : "))
rl=(roll,)
sql="delete from Student where roll=%s"
mycursor.execute(sql,rl)
print('Record deleted!!!')
mydb.commit()
5) Write a menu driven program to insert book no in queue and delete it from queue .
Ans:
q=[]
ch='Y'
while(ch=='Y' or ch=='y'):
print("Enter 1 : Enqueue")
print("Enter 2 : Dequeue")
opt=int(input('enter ur choice:='))
if opt==1:
d=int(input("enter book no : "))
q.append(d)
elif opt==2:
if (q==[]):
print( "Queue empty")
else:
p=q.pop(0)
print ("Deleted element:", p)
else:
print('invalid choice')
ch=(input('want to continue?'))
6) Write a python code to search student as per given roll number in database
using mysql connectivity and show result to the examiner. Create database and table
as below:
Name of database =school
Name of table = student(roll,name,age,class,city) give possible constraints on
your own
Ans:
import mysql.connector
mydb=mysql.connector.connect(host="localhost",\
user="root",\
passwd="root",\
database="school")
print(mydb)
mycursor=mydb.cursor()
s=int(input("Enter roll no to search: "))
rl=(s,)
sql="select * from student where roll=%s"
mycursor.execute(sql,rl)
res=mycursor.fetchall()
print("The Students details are as follows : ")
print("(ROll, Name, Age, Class, City)")
for x in res:
print(x)

7) Write a menu driven code in python to check whether string is palindrome or not and no.
is prime or not. Show result to the examiner.
Ans:
ch='Y'
while (ch=='Y' or ch=='y'):
print("Enter 1 : String palindrome:")
print("Enter 2 : prime no:")
opt=int(input('enter ur choice:='))
if opt==1:
str=input('Enter Text:=')
rev=str[::-1]
if str==rev:
print(str, "is Palindrome")
else:
print(str, "is not Palindrome")
elif opt==2:
no=int(input('Enter Number : '))
for i in range(2,no):
ans=no%i
if ans==0:
print ("Non Prime")
break;
elif i==no-1:
print("Prime Number")
else:
print('invalid choice')
ch=(input('want to continue?'))

8) Write a menu driven python code to add following tuples in database using mysql
connectivity and show result to the examiner
Consider the following table ITEMS & database as TRY

CODE INAME QTY PRICE COMPANY


DIGITAL
1001 120 11000 XENITA
PAD 121
LED SCREEN
1006 70 38000 SANTORA
40

Ans:
import mysql.connector
mydb=mysql.connector.connect(host="localhost",\
user="root",\
passwd="root",\
database="TRY")
print(mydb)
mycursor=mydb.cursor()
L=[]
code=int(input("Enter the CODE : "))
L.append(code)
iname=input("Enter the item Name: ")
L.append(iname)
qty=int(input("Enter quantity : "))
L.append(qty)
price=input("Enter price : ")
L.append(price)
company=input("Enter the company : ")
L.append(company)
st=(L)
sql="insert into ITEMS (code,iname,qty,price,company) values (%s,%s,%s,%s,%s)"
mycursor.execute(sql,st)
mydb.commit()

9) Write a python code for binary search using function.


Ans:
def bsearch(ar,n,item):
flag=0
beg=0
last=len(ar)-1
while(beg<=last) and flag==0:
mid=int(beg+last)//2
if(item==ar[mid]):
flag=mid
return flag
elif (item>ar[mid]):
beg=mid+1
else:
last=mid-1
else:
return -1
n=int(input('enter size of list:'))
print('enter numbers in sorted ordeer:\n')
ar=[0]*n
for i in range(n):
ar[i]=int(input('element '+str(i)+':'))
item=int(input('enter no. to search:'))
index=bsearch(ar,n,item)
if index>-1:
print('\n element found at index :',index,',position: ',(index+1))
else:
print('\n sorry no not found')

10) Write a python code to delete tuples from database as per given CODE using mysql
connectivity and show result to the examiner
Consider the following table ITEMS & database as TRY

COD QT
INAME PRICE COMPANY
E Y
DIGITAL PAD 1100
1001 120 XENITA
121 0
3800
1006 LED SCREEN 40 70 SANTORA
0
GEOKNO
1004 CAR GPS SYSTEM 50 2150
W

Ans:
import os
import platform
import mysql.connector

mydb=mysql.connector.connect(host="localhost",\
user="root",\
passwd="root",\
database="TRY")
print(mydb)
mycursor=mydb.cursor()
code=int(input("Enter code of the item to be deleted : "))
rl=(code,)
sql="Delete from ITEMS where code=%s"
mycursor.execute(sql,rl)
print('Record deleted!!!')
mydb.commit()

11) Write a python code for recursive binary search function.


Ans:
def bsearch(ar,l,r,x):
if r>=l:
mid=int((l+r)//2)
if(ar[mid]==x):
return mid
elif ar[mid]>x:
return bsearch(ar,l,mid-1,x)
else:
return bsearch(ar,mid+1,r,x)
else:
return -1
ar=[2,3,4,10,40,44,45,50,52]
x=int(input('enter element t search:'))
index=bsearch(ar,0,len(ar)-1,x)
if index!=-1:
print('element present at index:',index+1)
else:
print('element is not found')

12) Write a python code to search an item as per given INAME in database using
mysql connectivity and show result to the examiner
Consider the following table ITEMS & database as TRY

COD QT
INAME PRICE COMPANY
E Y
1100
1001 DIGITAL PAD 121 120 XENITA
0
3800
1006 LED SCREEN 40 70 SANTORA
0
1004 CAR GPS SYSTEM 50 2150 GEOKNOW
DIGITAL
1003 160 8000 DIGICLICK
CAMERA
STOREHOM
1005 PEN DRIVE 600 1200
E

Ans:
import os
import platform
import mysql.connector

mydb=mysql.connector.connect(host="localhost",\
user="root",\
passwd="root",\
database="TRY")
print(mydb)
mycursor=mydb.cursor()
iname=(input("Enter item name of the item to be searched : "))
rl=(iname,)
sql="select * from ITEMS where iname=%s"
mycursor.execute(sql,rl)
res=mycursor.fetchall()
print("The Item details are as follows : ")
print("(CODE, ITEM Name, QTY, PRICE, COMPANY)")
for x in res:
print(x)
13) Write a menu driven program in python to read text file and display
● No. of words
● No. of lines
● No. of alphabets
Ans:
ch='Y'
while (ch=='Y' or ch=='y'):

print("Enter 1 : count words:")


print("Enter 2 : count line:")
print("Enter 3 : count alphabets:")
print("Enter 4 : exit:")
opt=int(input('enter ur choice:='))
if opt==1:

f=open("abc.txt","r")
linesList=f.readlines()
count=0
for line in linesList:

wordsList=line.split()
print(wordsList)
count = count+ len(wordsList)
print("The number of words in this file are : ",count)
f.close()

elif opt==2:
c=0
f=open("abc.txt" , "r")
line=f.readline( )
while line:

c=c+1
line=f.readline( )
print('no. of lines:',c)
f.close( )

elif opt==3:
F=open('abc.txt','r')
c=0
for line in F:
words=line.split( )
for i in words:
for letter in i:
if(letter.isalpha( )):
c=c+1
print('Total no. of alphabets are:',c)
elif opt==4:
break
else:
print('invalid choice')
ch=(input('want to continue?'))

14) Write a python code to add following tuples in database using mysql connectivity
and show result to the examiner
Consider the following table STUDENT.

N NAME AG DEPARTMEN FE SE
O E T E X
1 PANKAJ 24 COMPUTER 12 M
0
2 SHALIN 21 HISTORY 20 F
I 0
Ans:
import os
import platform
import mysql.connector

mydb=mysql.connector.connect(host="localhost",\
user="root",\
passwd="root",\
database="school")
print(mydb)
mycursor=mydb.cursor()
L=[]
no=int(input("Enter the roll number : "))
L.append(no)
name=input("Enter the Name: ")
L.append(name)
age=int(input("Enter Age of Student : "))
L.append(age)
fee=input("Enter the fee : ")
L.append(fee)
dept=input("Enter the department of the Student : ")
L.append(dept)
sex=input("Enter the sex of the Student : ")
L.append(sex)
stud=(L)
sql="insert into student (roll,name,age,fee,dept,sex) values (%s,%s,%s,%s,%s,%s)"
mycursor.execute(sql,stud)
mydb.commit()

15) Write a python code for linear search using function


Ans:
def lsearch(ar,n,item):
for i in range(0,n):
if ar[i]==item:
return i
return -1
n=int(input('enter size of list:'))
print('enter numbers in sorted order:\n')
ar=[0]*n
for i in range(n):
ar[i]=int(input('element '+str(i)+':'))
item=int(input('enter no. to search:'))
index=lsearch(ar,n,item)
if index!=-1:
print('\n element found at index :',index,',position: ',(index+1))
else:
print('\n sorry no not found')

16) Write a python code to delete tuples from database as per given CODE
using mysql connectivity and show result to the examiner
Consider the following table ITEMS & database as TRY

Consider the following table STUDENT.

N NAME AG DEPARTMEN FE SE
O E T E X
1 PANKAJ 24 COMPUTER 12 M
0
2 SHALIN 21 HISTORY 20 F
I 0
3 SANJAY 22 HINDI 30 M
0
4 SUDHA 25 HISTORY 40 F
0
Ans:
import mysql.connector

mydb=mysql.connector.connect(host="localhost",\
user="root",\
passwd="root",\
database="TRY")
print(mydb)
mycursor=mydb.cursor()
code=int(input("Enter roll of to be deleted : "))
rl=(no,)
sql="Delete from STUDENT where no=%s"
mycursor.execute(sql,rl)
print('Record deleted!!!')
mydb.commit()

17) Write a menu driven python code to push and pop bookname in stack
Ans:
stk=[]
ch='Y'
while(ch=='Y' or ch=='y'):
print("Enter 1 : Push")
print("Enter 2 : Pop")
opt=int(input('enter ur choice:='))
if opt==1:
d=(input("enter book name : "))
stk.append(d)
elif opt==2:
if (stk==[]):
print( "Stack empty")
else:
p=stk.pop()
print ("Deleted element:", p)
else:
print('invalid choice')
ch=(input('want to continue?'))

18) Write a python code to search a record as per given NO using mysql connectivity and
show result to the examiner
Consider the following table STUDENT.

NO NAME AGE DEPARTMENT FEE SEX


1 PANKAJ 24 COMPUTER 120 M
2 SHALIN 21 HISTORY 200 F
I
3 SANJAY 22 HINDI 300 M
4 SUDHA 25 HISTORY 400 F

Ans:

import mysql.connector

mydb=mysql.connector.connect(host="localhost",\
user="root",\
passwd="root",\
database="TRY")
print(mydb)
mycursor=mydb.cursor()
no=(input("Enter no to be searched : "))
rl=(no,)
sql="select * from student where no=%s"
mycursor.execute(sql,rl)
res=mycursor.fetchall()
print("The student details are as follows : ")
print("(NO, NAME , AGE, DEPARTMENT, FEE,SEX)")
for x in res:
print(x)

19) Write a menu driven python code to insert and delete bookname from queue

Ans:

q=[]

ch='Y'

while(ch=='Y' or ch=='y'):

print("Enter 1 : Enqueue")

print("Enter 2 : Dequeue")

opt=int(input('enter ur choice:='))

if opt==1:

d=(input("enter book name : "))

q.append(d)

elif opt==2:

if (q==[]):

print( "Queue empty")

else:

p=q.pop(0)

print ("Deleted element:", p)

else:

print('invalid choice')

ch=(input('want to continue?'))

20) Write a python code to add following tuples in database using mysql
connectivity and show result to the examiner

Consider the following table EMPLOYEE.

EMPI FNAM LNAME CITY SALAR DESIG


D E Y
010 RAVI KUMAR MUMBA 15000 MANAGER
I
101 HARRY WALTO PUNE 12000 CLERK
R
215 ARUN KUMAR DELHI 13000 CLERK
152 SAM LEE MUMBA 20000 DIRECTO
I R

Ans:
import mysql.connector

mydb=mysql.connector.connect(host="localhost",\
user="root",\
passwd="root",\
database="emp")
print(mydb)
mycursor=mydb.cursor()
L=[]
id=int(input("Enter the employee id : "))
L.append(id)
fname=input("Enter the first Name: ")
L.append(fname)
lname=input("Enter the last Name: ")
L.append(lname)
city=int(input("Enter city : "))
L.append(city)
sal=input("Enter the salary : ")
L.append(sal)
desig=input("Enter designation : ")
L.append(desig)
stud=(L)
sql="insert into employee (id,fname,lname,city,sal,desig) values (%s,%s,%s,%s,%s,%s)"
mycursor.execute(sql,stud)
mydb.commit()

21) Write a menu driven python code to display those lines which have first
character 'g' & count all the line having 'a' as last character also print lines

Ans:
ch='Y'
while (ch=='Y' or ch=='y'):
print("Enter 1 : lines start with g:")
print("Enter 2 : count lines end with a :")
opt=int(input('enter ur choice:='))
if opt==1:
file=open("abc.txt" , "r")
line=file.readline( )
while line:
if line[0]=="g" :
print(line)
line=file.readline( )
file.close( )
elif opt==2:
count =0
f=open("abc.txt","r")
data=f.readlines()
print(data)
for line in data:
if line[-2] == 'a':
count=count+1
print("Number of lines having 'a' as last character is/are : " ,count)
f.close()
else:
print('invalid choice')
ch=(input('want to continue?'))

22) Write a python code to delete a tuple after giving value of EMPID using mysql
connectivity and show result to the examiner

Consider the following table EMPLOYEE.

ID FNAM LNAME CITY SALARY DESIG


E
01 RAVI KUMAR MUMBA 15000 MANAGER
0 I
10 HARRY WALTO PUNE 12000 CLERK
1 R
21 ARUN KUMAR DELHI 13000 CLERK
5
15 SAM LEE MUMBA 20000 DIRECTOR
2 I
Ans:

import mysql.connector

mydb=mysql.connector.connect(host="localhost",\
user="root",\
passwd="root",\
database="emp")
print(mydb)
mycursor=mydb.cursor()

def removeStu():
id=int(input("Enter the id of an employee to be deleted : "))
rl=(id,)
sql="Delete from employee where id=%s"
mycursor.execute(sql,rl)
print('Record deleted!!!')
mydb.commit()

23) Write a pyhon code to search a record as per given FNAME using mysql 3
connectivity and show result to the examiner a tuple after giving value of id using
mysql connectivity and show result to the examiner
Consider the following table EMPLOYEE.
ID FNAM LNAME CITY SALAR DESIG
E Y
01 RAVI KUMAR MUMBA 15000 MANAGER
0 I
10 HARRY WALTO PUNE 12000 CLERK
1 R
21 ARUN KUMAR DELHI 13000 CLERK
5
15 SAM LEE MUMBA 20000 DIRECTO
2 I R

Ans:

import mysql.connector

mydb=mysql.connector.connect(host="localhost",\
user="root",\
passwd="root",\
database="emp")
print(mydb)
mycursor=mydb.cursor()
fname=(input("Enter emp first name to be searched : "))
rl=(fname,)
sql="select * from employee where fname=%s"
mycursor.execute(sql,rl)
res=mycursor.fetchall()
print("The employee details are as follows : ")
print("(ID, FNAME , LNAME, CITY, SALARY, DESIGNATION)")
for x in res:
print(x)

24) Write python code for bubble sort using function 5


Ans:
def bubblesort(a, number):

for i in range(number -1):


for j in range(number - i - 1):
if(a[j] > a[j + 1]):
temp = a[j]
a[j] = a[j + 1]
a[j + 1] = temp

a = []
number = int(input("Please Enter the Total Number of Elements : "))
for i in range(number):
value = int(input("Please enter the %d Element of List1 : " %i))
a.append(value)

bubblesort(a, number)
print("The Sorted List in Ascending Order : ", a)
25) Write a python code to add following tuples in database using mysql 3
connectivity and show result to the examiner
Consider the following table FLIGHT.
FLNO START END NO_FLIGH AIRLINE FARE
T
IC301 MUMBAI DELHI 8 INDIAN 6500
AIRLINES
IC799 BANGALOR DELHI 2 INDIGO 9400
E
MC10 INDORE MUMBA 4 SPICEJET 1345
1 I 0
IC302 DELHI MUMBA 6 JET AIRWAYS 8300
I

Ans:
import mysql.connector

mydb=mysql.connector.connect(host="localhost",\
user="root",\
passwd="root",\
database="school")
print(mydb)
mycursor=mydb.cursor()
L=[]
flno=(input("Enter the flight number : "))
L.append(flno)
start=input("Enter the start: ")
L.append(start)
end=(input("Enter end : "))
L.append(end)
no_flight=int(input("Enter no.of flights : "))
L.append(no_flight)
air=input("Enter the airline name : ")
L.append(air)
fare=input("Enter fare : ")
L.append(fare)
stud=(L)
sql="insert into flight (flno,start,end,no_flight,air,fare) values (%s,%s,%s,%s,%s,%s,%s)"
mycursor.execute(sql,stud)
mydb.commit()

26) Write a python code to delete a tuple as per FLNO using mysql connectivity and show
result to the examiner

Consider the following table FLIGHT.

FLNO START ENDING NO_FLIGHT AIRLINES FARE


A S
IC301 MUMBAI DELHI 8 INDIAN 6500
AIRLINES
IC799 BANGALOR DELHI 2 INDIGO 9400
E
MC10 INDORE MUMBA 4 SPICEJET 13450
1 I
IC302 DELHI MUMBA 6 JET AIRWAYS 8300
I

Ans:
import os
import platform
import mysql.connector

mydb=mysql.connector.connect(host="localhost",\
user="root",\
passwd="root",\
database="TRY")
print(mydb)
mycursor=mydb.cursor()
flno=(input("Enter flight no. of to be deleted : "))
rl=(flno,)
sql="Delete from flight where flno=%s"
mycursor.execute(sql,rl)
print('Record deleted!!!')
mydb.commit()

You might also like