Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

XII Prac cal

Program 1: Program to enter two numbers and print the arithme c


opera ons like +,-,*, /, // and %.
Solu on:

Output:

Program 2: Write a program to find whether an inpu ed number is perfect or


not.
Solu on:
Output:

Program 3: Write a Program to check if the entered number is Armstrong or


not.
Solu on:

Output:

Program 4: Write a Program to find factorial of the entered number.


Solu on:

Output:
Program 5: Write a Program to enter the number of terms and to print the
Fibonacci Series.
Solu on:

Output:

Program 6: Write a Program to enter the string and to check if it’s palindrome
or not using loop.
Solu on:

Output:
Program 7: Write a Program to enter the number and print the Floyd’s
Triangle in decreasing order.
Solu on:

Output:

Program 8: Write a Program to read data from data file and show Data File
Handling related func ons u lity in python.
Solu on:
Output:

Program 9: Write a Program to read data from data file in read mode and
count the par cular word occurrences in given string, number of mes in
python.
Solu on:
Output:

Program 10: Write a Program to read data from data file in read mode and
append the words star ng with le er ‘T’ in a given file in python.
Solu on:

Output:

Program 11: Write a program to perform basic opera ons on a binary file
using pickle module.
Solu on:
# Program to write and read employee records in a binary file
import pickle
print("WORKING WITH BINARY FILES")
bfile=open("empfile.dat","ab")
recno=1
print ("Enter Records of Employees")
print()
#taking data from user and dumping in the file as list object
while True:
print("RECORD No.", recno)
eno=int(input("\tEmployee number : "))
ename=input("\tEmployee Name : ")
ebasic=int(input("\tBasic Salary : "))
allow=int(input("\tAllowances : "))
totsal=ebasic+allow
print("\tTOTAL SALARY : ", totsal)
edata=[eno,ename,ebasic,allow,totsal]
pickle.dump(edata,bfile)
ans=input("Do you wish to enter more records (y/n)? ")
recno=recno+1
if ans.lower()=='n':
print("Record entry OVER ")
print()
break
# retrieving the size of file
print("Size of binary file (in bytes):",bfile.tell())
bfile.close()
# Reading the employee records from the file using load() module
print("Now reading the employee records from the file")
print()
readrec=1
try:
with open("empfile.dat","rb") as bfile:
while True:
edata=pickle.load(bfile)
print("Record Number : ",readrec)
print(edata)
readrec=readrec+1
except EOFError:
pass
Output:
Program 12: Write a program to perform read and write menu base opera on
with text file.
Solu on:
def insert():
with open('myfile.txt', 'a') as file:
name=input("Enter your name:")
f_name=input("Enter your father name:")
m_name=input("Enter your mother name:")
s1='\n'+name+'\t'+f_name+'\t'+m_name
file.writelines(s1)
def view():
with open('myfile.txt','r') as file:
data=file.read()
print(data)
while True:
print('1 add data')
print('2 view data')
print('3 Exit')
ch=input('Enter your choice:')
if ch=='1':
insert()
elif ch=='2':
view()
elif ch=='3':
print('Thanks for using it.')
break
else:
print('you have entered invalid choice')

Output:

Program 13: Write a program to perform read and write menu base opera on
with csv file.
Solu on:
import csv
with open(r'file/c1.csv','w') as file:
witer=csv.writer(file)
witer.writerow([1,2,3,4,5])

import csv
file =open(r'file/c1.csv','r')
reader=csv.reader(file)
for i in reader:
print(i)
file.close()
Output:

Program 14: Write a program to generate random numbers between 1 to 6


and check whether a user won a lo ery or not.

Solu on:
import random
n=random.randint(1,6)
guess=int(input("Enter a number between 1 to 6 :"))
if n==guess:
print("Congratula ons, You won the lo ery ")
else:
print("Sorry, Try again, The lucky number was : ", n)

Output:

Program 15: Write a program to count number of words in a file.


Solution:
fin=open("Book.txt",'r')
str=fin.read( )
L=str.split()
count_words=0
for i in L:
count_words=count_words+1
print(count_words)

Output: 16
Q16. Write a menu-driven python program to implement stack operation.
Answer:
def check_stack_isEmpty(stk):
if stk==[]:
return True
else:
return False
s=[] # An empty list to store stack elements, initially its empty
top = None # This is top pointer for push and pop operation
def main_menu():
while True:
print("Stack Implementation")
print("1 - Push")
print("2 - Pop")
print("3 - Peek")
print("4 - Display")
print("5 - Exit")
ch = int(input("Enter the your choice:"))
if ch==1:
el = int(input("Enter the value to push an element:"))
push(s,el)
elif ch==2:
e=pop_stack(s)
if e=="UnderFlow":
print("Stack is underflow!")
else:
print("Element popped:",e)
elif ch==3:
e=pop_stack(s)
if e=="UnderFlow":
print("Stack is underflow!")
else:
print("The element on top is:",e)
elif ch==4:
display(s)
elif ch==5:
break
else:
print("Sorry, You have entered invalid option")
def push(stk,e):
stk.append(e)
top = len(stk)-1
def display(stk):
if check_stack_isEmpty(stk):
print("Stack is Empty")
else:
top = len(stk)-1
print(stk[top],"-Top")
for i in range(top-1,-1,-1):
print(stk[i])
def pop_stack(stk):
if check_stack_isEmpty(stk):
return "UnderFlow"
else:
e = stk.pop()
if len(stk)==0:
top = None
else:
top = len(stk)-1
return e
def peek(stk):
if check_stack_isEmpty(stk):
return "UnderFlow"
else:
top = len(stk)-1
return stk[top]
main_menu()

OUTPUT:
Stack Implementation
1 - Push
2 - Pop
3 - Peek
4 - Display
5 - Exit
Enter the your choice:1
Enter the value to push an element:10
Stack Implementation
1 - Push
2 - Pop
3 - Peek
4 - Display
5 - Exit
Enter the your choice:1
Enter the value to push an element:13
Stack Implementation
1 - Push
2 - Pop
3 - Peek
4 - Display
5 - Exit
Enter the your choice:1
Enter the value to push an element:14
Stack Implementation
1 - Push
2 - Pop
3 - Peek
4 - Display
5 - Exit
Enter the your choice:4
14 -Top
13
10
Stack Implementation
1 - Push
2 - Pop
3 - Peek
4 - Display
5 - Exit
Enter the your choice:2
Element popped: 14
Stack Implementation
1 - Push
2 - Pop
3 - Peek
4 - Display
5 - Exit
Enter the your choice:4
13 -Top
10
Stack Implementation
1 - Push
2 - Pop
3 - Peek
4 - Display
5 - Exit
Enter the your choice:3
The element on top is: 13
Stack Implementation
1 - Push
2 - Pop
3 - Peek
4 - Display
5 - Exit
Enter the your choice:5
Q17. Write a program to implement a stack for the employee details (empno, name).
stk=[]
top=-1
def isEmpty():
global stk
if stk==[]:
print("Stack is empty!!!")
else:
None

def push():
global stk
global top
empno=int(input("Enter the employee number to push:"))
ename=input("Enter the employee name to push:")
stk.append([empno,ename])
top=len(stk)-1

def display():
global stk
global top
if top==-1:
isEmpty()
else:
top=len(stk)-1
print(stk[top],"<-top")
for i in range(top-1,-1,-1):
print(stk[i])

def pop_ele():
global stk
global top
if top==-1:
isEmpty()
else:
stk.pop()
top=top-1

def main():
while True:
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")
ch=input("Enter your choice:")
if ch=='1':
push()
print("Element Pushed")
elif ch=='2':
pop_ele()
elif ch=='3':
display()
elif ch=='4':
break
else:
print("Invalid Choice")
main()

OUTPUT:
Q18. Write a python program to check whether a string is a palindrome or not using stack.
stack = []
top = -1

# push function
def push(ele):
global top
top += 1
stack[top] = ele

# pop function
def pop():
global top
ele = stack[top]
top -= 1
return ele

# Function that returns 1 if string is a palindrome


def isPalindrome(string):
global stack
length = len(string)

# Allocating the memory for the stack


stack = ['0'] * (length + 1)

# Finding the mid


mid = length // 2
i = 0
while i < mid:
push(string[i])
i += 1

# Checking if the length of the string is odd, if odd then neglect the middle
character
if length % 2 != 0:
i += 1

# While not the end of the string


while i < length:
ele = pop()

# If the characters differ th en the given string is not a palindrome


if ele != string[i]:
return False
i += 1
return True
string = input("Enter string to check:")

if isPalindrome(string):
print("Yes, the string is a palindrome")
else:
print("No, the string is not a palindrome")

OUTPUT:
Enter string to check:naman
Yes, the string is a palindrome
Enter string to check:rajan
No, the string is not a palindrome
Q19.Consider the following MOVIE table and write the SQL queries based on it.

Movie_ID MovieName Type ReleaseDate ProductionCost BusinessCost

M001 The Kashmir Files Action 2022/01/26 1245000 1300000

M002 Attack Action 2022/01/28 1120000 1250000

M003 Looop Lapeta Thriller 2022/02/01 250000 300000

M004 Badhai Do Drama 2022/02/04 720000 68000

M005 Shabaash Mithu Biography 2022/02/04 1000000 800000

M006 Gehraiyaan Romance 2022/02/11 150000 120000


7. Display all information from movie.
8. Display the type of movies.
9. Display movieid, moviename, total_eraning by showing the business done by the movies.
Claculate the business done by movie using the sum of productioncost and businesscost.
10. Display movieid, moviename and productioncost for all movies with productioncost
greater thatn 150000 and less than 1000000.
11. Display the movie of type action and romance.
12. Display the list of movies which are going to release in February, 2022.
Answers:
[1] select * from movie;
Output:

2. select distinct from a movie;


3. select movieid, moviename, productioncost + businesscost “total earning” from movie;

4. select movie_id,moviename, productioncost from movie where producst is >150000 and


<1000000;

5. select moviename from movie where type =’action’ or type=’romance’;


6. select moviename from moview where month(releasedate)=2;
Q20. Write the following database queries.
Create a database “Sports”.
Create a table “TEAM” with following considerations:
• It should have a column TeamID for storing an integer value between 1 to 9,
which refers to unique identification of a team.
• Each TeamID should have its associated name (TeamName), which should be a
string of length not less than 10 characters.
• Using table level constraint, make TeamID as the primary key.
• Show the structure of the table TEAM using a SQL statement.
• As per the preferences of the students four teams were formed as given below.
Insert these four rows in TEAM table:
• Row 1: (1, Tehlka)
• Row 2: (2, Toofan)
• Row 3: (3, Aandhi)
• Row 3: (4, Shailab)
• Show the contents of the table TEAM using a DML statement.

Answers:
[1] create database sports

[2] Creating table with the given specification


create table team
-> (teamid int(1),
-> teamname varchar(10), primary key(teamid));
Showing the structure of table using SQL statement:
desc team;
Inserting data:
mqsql> insert into team
-> values(1,'Tehlka');

Show the content of table – team:


select * from team;
Q21. Now create another table EMPLOYEE and insert data as shown below. Choose appropriate
data types and constraints for each attribute.
EMPID NAME DOB DEPTID DESIG SALARY
120 Alisha 23-Jan-1978 D001 Manager 75000
123 Ni n 10-Oct-1977 D002 AO 59000
129 Navjot 12-Jul-1971 D003 Supervisor 40000
130 Jimmy 30-Dec-1980 D004 Sales
131 Faiz 06-Apr-1984 D001 Dep Manager 65000

Creating another table:

Insert Data into table:

Show table Data:


Q22. Write the following sql queries.
6. Display the matchid, teamid, teamscore whoscored more than 70 in first ining along with
team name.
7. Display matchid, teamname and secondteamscore between 100 to 160.
8. Display matchid, teamnames along with matchdates.
9. Display unique team names
10. Display matchid and matchdate played by Anadhi and Shailab.
Answers:
[1] select match_details.matchid, match_details.firstteamid,
team.teamname,match_details.firstteamscore from match_details, team where
match_details.firstteamid=team.teamid and match_details.firstteamscore>70;

[2] select matchid, teamname, secondteamscore from match_details, team where


match_details.secondteamid=team.teamid and match_details.secondteamscore between 100 and
160;

[3] select matchid,teamname,firstteamid,secondteamid,matchdate from match_details, team where


match_details.firstteamid=team.teamid;
[4] select distinct(teamname) from match_details, team where
match_details.firstteamid=team.teamid;

[5] select matchid,matchdate from match_details, team where


match_details.firstteamid=team.teamid and team.teamname in (‘Aandhi’,’Shailab’);
Q23. Consider the following table stock table to answer the queries:
itemno item dcode qty unitprice stockdate

S005 Ballpen 102 100 10 2018/04/22

S003 Gel Pen 101 150 15 2018/03/18

S002 Pencil 102 125 5 2018/02/25

S006 Eraser 101 200 3 2018/01/12

S001 Sharpner 103 210 5 2018/06/11

S004 Compass 102 60 35 2018/05/10

S009 A4 Papers 102 160 5 2018/07/17


6. Display all the items in the ascending order of stockdate.
7. Display maximum price of items for each dealer individually as per dcode from stock.
8. Display all the items in descending orders of itemnames.
9. Display average price of items for each dealer individually as per doce from stock which
avergae price is more than 5.
10. Display the sum of quantity for each dcode.
[1] select * from stock order by stockdate;

[2] select dcode,max(unitprice) from stock group by code;


[3] select * from stock order by item desc;

[4] select dcode,avg(unitprice) from stock group by dcode having avg(unitprice)>5;

[5] select dcode,sum(qty) from stock group by dcode;


Q24.Write a MySQL connectivity program in Python to
• Create a database school
• Create a table students with the specifications – ROLLNO integer, STNAME
character(10) in MySQL and perform the following operations:
• Insert two records in it
• Display the contents of the table
Answers:
import mysql.connector as ms
con=ms.connect(host="localhost",user="root",password="")
c1=con.cursor()
c1.execute("create database if not exists school")
c1.execute('use school')
c1.execute('create table if not exists students(rollno int(3),stname varchar(20))')

#Function to Insert Data


def add_data():
while True:
rno=int(input("Enter student rollno::"))
name=input("Enter student name::")
c1.execute("insert into students values({},'{}')".format(rno,name))
con.commit()
choice=input("Do you want to add more record<y/n>=")
if choice in "Nn":
break

#Function to Display Data


def view_data():
c1.execute("select * from students")
data=c1.fetchall()
print(" "*10,"ROLL NO\t\tSTUDENT NAME")
for i in data:
for j in i:
print(" "*10,j,"\t",end='')
print()
print("_"*64,)

while True:
print(" "*30,"Menu")
print("_"*64,)
print(" "*10,"1 To Add student Detail")
print(" "*10,"2 To View Students Details")
print(" "*10,"3 To Exit")
choice=input("Enter your choice<1-3>::")
if choice=='1':
add_data()
elif choice =='2':
view_data()
elif choice=='3':
print("you are exit now.")
break
else:
print("Invalid Choice.")
OUTPUT
Menu
_____________________________________
1 To Add student Detail
2 To View Students Details
3 To Exit
Enter your choice<1-3>::1
Enter student rollno::1001
Enter student name::Rakesh
Do you want to add more record<y/n>=y
Enter student rollno::1002
Enter student name::Lokesh
Do you want to add more record<y/n>=n
Menu
________________________________________________________________
1 To Add student Detail
2 To View Students Details
3 To Exit
Enter your choice<1-3>::2
ROLL NO STUDENT NAME
1001 Rakesh
1002 Lokesh
__________________________________________
Menu
__________________________________________
1 To Add student Detail
2 To View Students Details
3 To Exit
Enter your choice<1-3>::3
you are exit now.
Q25. Perform create, insert, delete and update operations with reference to table ‘students’ through
MySQL-Python connectivity.
import mysql.connector as ms
con=ms.connect(host="localhost",user="root",password="")
c1=con.cursor()
c1.execute("create database if not exists school")
c1.execute('use school')
c1.execute('create table if not exists students(rollno int(3),stname varchar(20))')

def add_data():
while True:
rno=int(input("Enter student rollno::"))
name=input("Enter student name::")
c1.execute("insert into students values({},'{}')".format(rno,name))
con.commit()
choice=input("Do you want to add more record<y/n>=")
if choice in "Nn":
break

def view_data():
c1.execute("select * from students")
data=c1.fetchall()
print(" "*10,"ROLL NO\t\tSTUDENT NAME")
for i in data:
for j in i:
print(" "*10,j,"\t",end='')
print()
print("_"*64,)

def update_data():
view_data()
uid=input('Enter student roll No for update data::')
name=input('Enter student Name::')
c1.execute("update students set stname='{}' where rollno={}".format(name,uid))
con.commit()
print("data updated.")
def del_data():
view_data()
did=input('Enter student roll No for detete data::')
c1.execute("delete from students where rollno={}".format(did))
con.commit()
print("data deleted")

while True:
print(" "*30,"Menu")
print("_"*64,)
print(" "*10,"1 To Add student Detail")
print(" "*10,"2 To View Students Details")
print(" "*10,"3 To Update Students Details")
print(" "*10,"4 To Delete Students Details")
print(" "*10,"5 To Exit")
choice=input("Enter your choice<1-5>::")
if choice=='1':
add_data()
elif choice =='2':
view_data()
elif choice =='3':
update_data()
elif choice =='4':
del_data()
elif choice=='5':
print("you are exit now.")
break
else:
print("Invalid Choice.")

OUTPUT:
Menu
________________________________________________________________
1 To Add student Detail
2 To View Students Details
3 To Update Students Details
4 To Delete Students Details
5 To Exit
Enter your choice<1-5>::1
Enter student rollno::1003
Enter student name::fool
Do you want to add more record<y/n>=n
Menu
________________________________________________________________
1 To Add student Detail
2 To View Students Details
3 To Update Students Details
4 To Delete Students Details
5 To Exit
Enter your choice<1-5>::2
ROLL NO STUDENT NAME
1001 Rakesh
1002 Lokesh
1003 fool
________________________________________________________________
Menu
________________________________________________________________
1 To Add student Detail
2 To View Students Details
3 To Update Students Details
4 To Delete Students Details
5 To Exit
Enter your choice<1-5>::3
ROLL NO STUDENT NAME
1001 Rakesh
1002 Lokesh
1003 fool
________________________________________________________________
Enter student roll No for update data::1003
Enter student Name::foolchand
data updated.
Menu
________________________________________________________________
1 To Add student Detail
2 To View Students Details
3 To Update Students Details
4 To Delete Students Details
5 To Exit
Enter your choice<1-5>::2
ROLL NO STUDENT NAME
1001 Rakesh
1002 Lokesh
1003 foolchand
________________________________________________________________
Menu
________________________________________________________________
1 To Add student Detail
2 To View Students Details
3 To Update Students Details
4 To Delete Students Details
5 To Exit
Enter your choice<1-5>::4
ROLL NO STUDENT NAME
1001 Rakesh
1002 Lokesh
1003 foolchand
________________________________________________________________
Enter student roll No for detete data::1003
data deleted
Menu
________________________________________________________________
1 To Add student Detail
2 To View Students Details
3 To Update Students Details
4 To Delete Students Details
5 To Exit
Enter your choice<1-5>::2
ROLL NO STUDENT NAME
1001 Rakesh
1002 Lokesh
________________________________________________________________
Menu
________________________________________________________________
1 To Add student Detail
2 To View Students Details
3 To Update Students Details
4 To Delete Students Details
5 To Exit
Enter your choice<1-5>::5
you are exit now.

You might also like