0% found this document useful (0 votes)
350 views

Solution of Practicals Class Xii Comp. Sci. 083 2022 23

1. This document provides 15 Python programming problems and their solutions related to working with files, strings, numbers, and binary data. Some key problems addressed include checking if a number is prime, palindrome, or swapping numbers. Other problems involve counting characters in files, generating random numbers, and reading/writing student data to binary files. Detailed code solutions are provided for each problem to demonstrate how to implement the required programming tasks in Python.

Uploaded by

Night Fury
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)
350 views

Solution of Practicals Class Xii Comp. Sci. 083 2022 23

1. This document provides 15 Python programming problems and their solutions related to working with files, strings, numbers, and binary data. Some key problems addressed include checking if a number is prime, palindrome, or swapping numbers. Other problems involve counting characters in files, generating random numbers, and reading/writing student data to binary files. Detailed code solutions are provided for each problem to demonstrate how to implement the required programming tasks in Python.

Uploaded by

Night Fury
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/ 30

https://pythonschoolkvs.wordpress.

com/
CLASS-XII
SUBJECT – COMPUTER SCIENCE (083)
PRACTICAL FILE SOLUTION (Session 2022-23)
PRACTIC
OBJECTIVE & SOLUTION
AL NO.
1. Write a program in python to check a number whether it is prime or not.
num=int(input("Enter the number: "))
for i in range(2,num):
if num%i==0:
SOURCE print(num, "is not prime number")
CODE: break;
else:
print(num,"is prime number")

OUTPUT:

2. Write a program to check a number whether it is palindrome or not.


SOURCE num=int(input("Enter a number : "))

Page 1 of 30
CODE: n=num
res=0
while num>0:
rem=num%10
res=rem+res*10
num=num//10
if res==n:
print("Number is Palindrome")
else:
print("Number is not Palindrome")

OUTPUT:

3. Write a program to display ASCII code of a character and vice versa.


var=True
while var:
choice=int(input("Press-1 to find the ordinal value of a character
SOURCE
\nPress-2 to
CODE:
find a character of a value\n"))
if choice==1:
ch=input("Enter a character : ")

Page 2 of 30
print(ord(ch))
elif choice==2:
val=int(input("Enter an integer value: "))
print(chr(val))
else:
print("You entered wrong choice")

print("Do you want to continue? Y/N")


option=input()
if option=='y' or option=='Y':
var=True
else:
var=False

Press-1 to find the ordinal value of a character


Press-2 to find a character of a value
1
OUTPUT: Enter a character : a
97
Do you want to continue? Y/N
Y

Page 3 of 30
Press-1 to find the ordinal value of a character
Press-2 to find a character of a value
2
Enter an integer value: 65
A
Do you want to continue? Y/N

Write a function SwapNumbers( ) to swap two numbers and display the


4.
numbers before swapping and after swapping.
def SwapNumbers(x,y):
a, b = y, x
print("After Swap:")
print("Num1: ", a)
print("Num2: ", b)

SOURCE
# main program
CODE:
Num1=int(input("Enter Number-1: "))
Num2=int(input("Enter Number-2: "))
print("Before Swap: ")
print("Num1: ", Num1)
print("Num2: ", Num2)
SwapNumbers(Num1, Num2)
Page 4 of 30
Enter Number-1: 10
Enter Number-2: 20
Before Swap:
Num1: 10
OUTPUT: Num2: 20
After Swap:
Num1: 20
Num2: 10

Write a program to compute GCD and LCM of two numbers using


5.
functions.
def gcd(x,y):
while(y):
x, y = y, x % y
return x
SOURCE
CODE:
def lcm(x, y):
lcm = (x*y)//gcd(x,y)
return lcm

Page 5 of 30
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2))


print("The G.C.D. of", num1,"and", num2,"is", gcd(num1, num2))

Enter first number: 15


Enter second number: 35
OUTPUT:
The L.C.M. of 15 and 35 is 105
The G.C.D. of 15 and 35 is 5
6. Write a function FACT( ) to calculate the factorial of an integer .
def FACT(n):
f=1
for i in range(1,n+1):
f= f*i
SOURCE
print("Factorial of ", n, "is: ", f)
CODE:

num=int(input("Enter the number: "))


FACT(num)

enter the number: 5


OUTPUT:
The factorial of 5 is 120
Page 6 of 30
Write a program to generate random numbers between 1 to 6 and check
7.
whether a user won a lottery or not.
import random
n=random.randint(1,6)
guess=int(input("Enter a number between 1 to 6 :"))
SOURCE if n==guess:
CODE: print("Congratulations, You won the lottery ")
else:
print("Sorry, Try again, The lucky number was : ", n)

Enter a number between 1 to 6 : 4


OUTPUT:
Sorry, Try again, The lucky number was : 1
8. Write a program to count the number of vowels present in a text file.
fin=open("D:\\python programs\\Book.txt",'r')
str=fin.read( )
count=0
SOURCE for i in str:
CODE: if i=='a' or i=='e' or i=='i' or i=='o' or i=='u':
count=count+1

print(count)

Page 7 of 30
13
OUTPUT:

Write a program to write those lines which have the character 'p' from
9.
one text file to another text file.
fin=open("E:\\book.txt","r")
fout=open("E:\\story.txt","a")
s=fin.readlines( )
for j in s:
SOURCE if 'p' in j:
CODE: fout.write(j)

fin.close()
fout.close()

**Write contents of book.txt and story.txt


OUTPUT:

10. Write a program to count number of words in a file.


fin=open("D:\\python programs\\Book.txt",'r')
str=fin.read( )
SOURCE
L=str.split()
CODE:
count_words=0
for i in L:
Page 8 of 30
count_words=count_words+1
print(count_words)

16
OUTPUT:

11. Write a python program to write student data in a binary file.


import pickle
list =[ ] # empty list
while True:
roll = input("Enter student Roll No:")
sname = input("Enter student Name :")
SOURCE
student = {"roll":roll,"name":sname}
CODE:
list.append(student)
choice= input("Want to add more record(y/n) :")
if(choice=='n'):
break
file = open("student.dat","wb")

Page 9 of 30
pickle.dump(list, file)
file.close( )

Enter student Roll No:1201


Enter student Name :Anil
Want to add more record(y/n) :y
OUTPUT:
Enter student Roll No:1202
Enter student Name :Sunil
Want to add more record(y/n) :n
12. Write a python program to read student data from a binary file.
import pickle
file = open("student.dat", "rb")
SOURCE
list = pickle.load(file)
CODE:
print(list)
file.close( )

OUTPUT: [{'roll': '1201', 'name': 'Anil'}, {'roll': '1202', 'name': 'Sunil'}]


13. Write a python program to modify/update student data in a binary file.
Page 10 of 30
import pickle
roll = input('Enter roll number whose name you want to update in binary
file :')
file = open("student.dat", "rb+")
list = pickle.load(file)
found = 0
lst = [ ]
for x in list:
if roll in x['roll']:
found = 1
SOURCE
x['name'] = input('Enter new name: ')
CODE:
lst.append(x)
if found == 1:
file.seek(0)
pickle.dump(lst, file)
print("Record Updated")
else:
print('roll number does not exist')

file.close( )

Page 11 of 30
Enter roll number whose name you want to update in binary file :1202
Enter new name: Harish
OUTPUT:
Record Updated

14. Write a python program to delete student data from a binary file.
import pickle
roll = input('Enter roll number whose record you want to delete:')
file = open("student.dat", "rb+")
list = pickle.load(file)
found = 0
lst = []
for x in list:
if roll not in x['roll']:
SOURCE
lst.append(x)
CODE:
else:
found = 1

if found == 1:
file.seek(0)
pickle.dump(lst, file)
print("Record Deleted ")
else:
Page 12 of 30
print('Roll Number does not exist')
file.close( )

Enter roll number whose record you want to delete:1201


OUTPUT: Record Deleted

15. Write a python program to search a student record in a binary file.


import pickle
roll = input('Enter roll number that you want to search in binary file :')
file = open("student.dat", "rb")
list = pickle.load(file)
file.close( )
SOURCE for x in list:
CODE: if roll in x['roll']:
print("Name of student is:", x['name'])
break
else:
print("Record not found")

Enter roll number that you want to search in binary file :1202
OUTPUT:
Name of student is: Harish

Page 13 of 30
16. Write a program to perform read and write operation with .csv file.
import csv
def readcsv():
with open('C:\\ data.csv','rt')as f:
data = csv.reader(f)
for row in data:
print(row)

def writecsv( ):
with open('C:\\data.csv', mode='a', newline='') as file:
SOURCE writer = csv.writer(file, delimiter=',', quotechar='"')
CODE:
#write new record in file
writer.writerow(['4', 'Devansh', 'Arts', '404'])

print("Press-1 to Read Data and Press-2 to Write data: ")


a=int(input())
if a==1:
readcsv()
elif a==2:
Page 14 of 30
writecsv()
else:
print("Invalid value")

Press-1 to Read Data and Press-2 to Write data:


1
['Roll No.', 'Name of student', 'stream', 'Marks']
['1', 'Anil', 'Arts', '426']
OUTPUT:
['2', 'Sujata', 'Science', '412']
['3', 'Shivani', 'Commerce', '448']
['4', 'Devansh', 'Arts', '404']

Create a CSV file by entering user-id and password, read and search the
17.
password for given userid.
import csv
def searchcsv(id):
with open('E:\\data.csv','rt')as f:
SOURCE
data = csv.reader(f)
CODE:
for row in data:
if row[0]==id:
print(row[1])

Page 15 of 30
break
else:
print("Userid is not present")

def writecsv( ):
with open('E:\\data.csv','a', newline='') as f:
w = csv.writer(f)

#write new records in file


n=int(input("How many userid you want to enter: "))
for i in range(n):
print("Enter userid",i+1)
id=input()
pswd=input("Enter Password: ")
w.writerow([id,pswd])

writecsv()
userid=input("Enter userid for which you want to search password: ")
searchcsv(userid)
How many userid you want to enter: 3
OUTPUT: Enter userid 1
Saurav
Page 16 of 30
Enter Password: 123
Enter userid 2
Garima
Enter Password: 456
Enter userid 3
Anoop
Enter Password: 789
Enter userid for which you want to search password: Garima
456
18. Write a program for linear search.
L=eval(input("Enter the elements: "))
n=len(L)
item=eval(input("Enter the element that you want to search : "))
for i in range(n):
SOURCE if L[i]==item:
CODE: print("Element found at the position :", i+1)
break
else:
print("Element not Found")

OUTPUT: Enter the elements: [23,67,44,99,65,33,78,12]

Page 17 of 30
Enter the element that you want to search : 33
Element found at the position : 6

Write a program to pass an integer list as stack to a function and push


19.
only those elements in the stack which are divisible by 7.
STACK=[]
def PUSH(L):
for i in L:
if i%7==0:
STACK.append(i)
SOURCE
print("The Stack is ", STACK)
CODE:

M=eval(input("Enter an integer list: "))


PUSH(M)

Enter an integer list: [12,21,77,45,14,79,49]


OUTPUT: The Stack is [21, 77, 14, 49]

20. Write a menu based program to perform the operation on stack in python.
SOURCE def push(n):
CODE: L.append(n)
Page 18 of 30
print("Element inserted successfully")

def Pop( ):
if len(L)==0:
print("Stack is empty")
else:
print("Deleted element is: ", L.pop( ))

def Display( ):
print("The list is : ", L)

def size( ):
print("Size of list is: ", len(L))

def Top( ):
if len(L)==0:
print("Stack is empty")
else:
print("Value of top is: ", L[len(L)-1])

#main program

Page 19 of 30
L=[ ]
print("MENU BASED STACK")
cd=True
while cd:
print(" 1. Push ")
print(" 2. Pop ")
print(" 3. Display ")
print(" 4. Size of Stack ")
print(" 5. Value at Top ")

choice=int(input("Enter your choice (1-5) : "))

if choice==1:
val=input("Enter the element: ")
push(val)
elif choice==2:
Pop( )
elif choice==3:
Display( )
elif choice==4:
size( )
elif choice==5:
Page 20 of 30
Top( )
else:
print("You enetered wrong choice ")

print("Do you want to continue? Y/N")


option=input( )
if option=='y' or option=='Y':
var=True
else:
var=False
MENU BASED STACK
1. Push
2. Pop
3. Display
4. Size of Stack
OUTPUT: 5. Value at Top
Enter your choice (1-5) : 1
Enter the element: 45
Do you want to continue? Y/N
y
1. Push

Page 21 of 30
2. Pop
3. Display
4. Size of Stack
5. Value at Top
Enter your choice (1-5) : 3
['45']
Do you want to continue? Y/N
y
1. Push
2. Pop
3. Display
4. Size of Stack
5. Value at Top

Create database, Show databases, USE, Create table, Show Tables,


21.
Describe, Rename, Alter, Select, From, Where, Insert, Update commands
#Command to create a database
mysql> CREATE DATABASE RAILWAYS;

SOLUTION: # Command to show the available databases


mysql> SHOW DATABASES;

Page 22 of 30
#Command to enter in a databse
mysql> USE RAILWAYS;
Database changed

#Create a table in the database


mysql> Create table TRAIN(Train_No int primary key, Tname
varchar(30), Source varchar(10), Destination varchar(10), fare float(6,2),
start_date date);

#Show the available tables in the database


mysql> Show tables;

# Show the details of a table


mysql> describe Train;
# Rename/Change the name of the table
mysql> Alter table Train rename Traindetails;

#Insert row in the table


mysql> insert into Traindetails values(22454, “Rajdhani Exp”, “Mumbai”,
“Delhi”, 2856.20, “2019-06-22”);

Page 23 of 30
#Show all data/rows of the table
mysql> SELECT * FROM TRAINDETAILS;

#Change/Modify the fare of train to 3000.00 whose train no. is 22454


mysql> update Traindetails set fare = 3000.00 where Train_No=22454;

OUTPUT: Write output accordingly


Queries using DISTINCT, BETWEEN, IN, LIKE, IS NULL, ORDER BY,
22.
GROUP BY, HAVING
Display the name of departments. Each department should be displayed
A.
once.
SELECT DISTINCT(Dept)
SOLUTION: FROM EMPLOYEE;

Find the name and salary of those employees whose salary is between
B.
35000 and 40000.
SELECT Ename, salary
FROM EMPLOYEE
SOLUTION:
WHERE salary BETWEEN 35000 and 40000;

Find the name of those employees who live in guwahati, surat or jaipur
C.
city.
Page 24 of 30
SELECT Ename, city
FROM EMPLOYEE
SOLUTION:
WHERE city IN(‘Guwahati’,’Surat’,’Jaipur’);

D. Display the name of those employees whose name starts with ‘M’.
SELECT Ename
FROM EMPLOYEE
SOLUTION:
WHERE Ename LIKE ‘M%’;

List the name of employees not assigned to any department.


E.

SELECT Ename
FROM EMPLOYEE
SOLUTION:
WHERE Dept IS NULL;

F. Display the list of employees in descending order of employee code.


SELECT *
FROM EMPLOYEE
SOLUTION:
ORDER BY ecode DESC;

Page 25 of 30
G. Find the average salary at each department.
SELECT Dept, avg(salary)
FROM EMPLOYEE
SOLUTION:
group by Dept;

Find maximum salary of each department and display the name of that
H. department which has maximum salary more than 39000.

Queries for Aggregate functions- SUM( ), AVG( ), MIN( ), MAX( ), COUNT(


23.
)
a. Find the average salary of the employees in employee table.
Solution:- SELECT avg(salary)
FROM EMPLOYEE;
b. Find the minimum salary of a female employee in EMPLOYEE
table.
Solution:- SELECT Ename, min(salary)
FROM EMPLOYEE
WHERE sex=’F’;
c. Find the maximum salary of a male employee in EMPLOYEE
table.
Solution:- SELECT Ename, max(salary)
FROM EMPLOYEE
Page 26 of 30
WHERE sex=’M’;
d. Find the total salary of those employees who work in Guwahati
city.
Solution:- SELECT sum(salary)
FROM EMPLOYEE
WHERE city=’Guwahati’;
e. Find the number of tuples in the EMPLOYEE relation.
Solution:- SELECT count(*)
FROM EMPLOYEE;

24. Write a program to connect Python with MySQL using database


connectivity and perform the following operations on data in database:
CREATE a table in database
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
SOLUTION: democursor.execute("CREATE TABLE STUDENT (admn_no int primary
key, sname varchar(30), gender char(1), DOB date, stream varchar(15),
marks float(4,2))")

Page 27 of 30
Write a program to connect Python with MySQL using database
25. connectivity and perform the following operation on data in database:
Insert record in the table
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
SOLUTION: democursor.execute("insert into student values (%s, %s, %s, %s, %s,
%s)", (1245, 'Arush', 'M', '2003-10-04', 'science', 67.34))
demodb.commit( )

Write a program to connect Python with MySQL using database


connectivity and perform the following operation on data in database:
26.
Fetch records from the table using fetchone( ), fetchall() and fetchmany(
).
FETCHONE()
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
SOLUTION: democursor=demodb.cursor()
democursor.execute("select * from student")
print(democursor.fetchone())
Page 28 of 30
FETCHALL( )
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
SOLUTION: democursor=demodb.cursor()
democursor.execute("select * from student")
print(democursor.fetchall())

FETCHMANY( )

import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
SOLUTION: democursor=demodb.cursor()
democursor.execute("select * from student")
print(democursor.fetchmany(3))

Write a program to connect Python with MySQL using database


connectivity and perform the following operation on data in database:
27.
Update record in the table

Page 29 of 30
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("update student set marks=55.68 where
SOLUTION:
admn_no=1356")
demodb.commit( )

Write a program to connect Python with MySQL using database


connectivity and perform the following operation on data in database:
28.
Delete record from the table

import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
SOLUTION: democursor=demodb.cursor( )
democursor.execute("delete from student where admn_no=1356")
demodb.commit( )

Page 30 of 30

You might also like