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

Solution_Practical _file_list_XII_CS_202425

The document contains a practical file for Computer Science (083) for Class XII, detailing various programming tasks to be completed in Python. Each task includes a description, source code, and expected output, covering topics such as prime number checking, palindrome checking, ASCII code conversion, and file handling. The practicals aim to enhance students' programming skills and understanding of basic concepts in Python.
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)
12 views

Solution_Practical _file_list_XII_CS_202425

The document contains a practical file for Computer Science (083) for Class XII, detailing various programming tasks to be completed in Python. Each task includes a description, source code, and expected output, covering topics such as prime number checking, palindrome checking, ASCII code conversion, and file handling. The practicals aim to enhance students' programming skills and understanding of basic concepts in Python.
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/ 11

KENDRIYA VIDYALAYA ONGC CHANDKHEDA

PRACTICAL FILE- COMPUTER SCIENCE (083)


SOLUTION OF PRACTICALS (2024-25) CLASS-XII

SN NAME OF PRACTICAL
1 Write a program in python to check a number whether it is prime or not.
Source
Code num=int(input("Enter the number: "))
for i in range(2,num):
if num%i==0:
print(num, "is not prime number")
break;
else:
print(num,"is prime number")

Output

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


num=int(input("Enter a number : "))
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 Enter a number :6556


Number is Palindrome
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

\nPress-2 to find a character of a value\n"))


if choice==1:
ch=input("Enter a character : ")
int(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

Output Press-1 to find the ordinal value of a character


Press-2 to find a character of a value 1​
Enter a character : a
97
Do you want to continue? Y/N
Y
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
N
4 Write a program to generate random numbers between 1 to 6 and check 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 :"))
if n==guess:
print("Congratulations, You won the lottery ")
else:
print("Sorry, Try again, The lucky number was : ", n)

Output
Enter a number between 1 to 6 : 4

Sorry, Try again, The lucky number was : 1

5 Write a function SwapNumbers( ) to swap two numbers and display the numbers before swapping
and after swapping.
def SwapNumbers(x,y):
a, b = y, x
print("After Swap:")
print("Num1: ", a)
print("Num2: ", b)
# main program
Num1=int(input("Enter Number-1: "))
Num2=int(input("Enter Number-2: "))
print("Before Swap: ")
print("Num1: ", Num1)
print("Num2: ", Num2)
SwapNumbers(Num1, Num2)
Output Enter Number-1: 10
Enter Number-2: 20
Before Swap:
Num1: 10
Num2: 20
After Swap:
Num1: 20
Num2: 10
6 Write a program to compute GCD and LCM of two numbers using functions.
def gcd(x,y):
while(y):
x, y = y, x % y
​ return x
def lcm(x, y):
​ lcm = (x*y)//gcd(x,y)
​ return lcm
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))
Output Enter first number: 15
Enter second number: 35
The L.C.M. of 15 and 35 is 105
The G.C.D. of 15 and 35 is 5
7 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
​ print("Factorial of ", n, "is: ", f)
num=int(input("Enter the number: "))
FACT(num)
Output enter the number: 5
The factorial of 5 is 120
8 Write a program to read a text file line by line and display each word separated by '#'.
file = open(“filename.txt”, “r")
data = file.readlines()
for i in data:
print(i.replace(" ", "#"))
Output This#is#my#computer#lab.
9 Write a program to count the number of vowels/consonants/uppercase/lowercase character present
in a text file.
fin=open("D:\\python programs\\Book.txt",'r')
string = fin.read( )
vowels = consonants = uppercase = lowercase = 0
vowels_list = ['a','e','i','o','u',’A’,’E’,’I’,’O’,’U’]
for i in string:
if i in vowels_list:
vowels += 1
if i not in vowels_list:
consonants += 1
if i.isupper():
uppercase += 1
if i.islower():
lowercase += 1
print("Number of Vowels in this String = ", vowels)
print("Number of Consonants in this String = ", consonants)
print("Number of Uppercase characters in this String = ", uppercase)
print("Number of Lowercase characters in this String = ", lowercase)
fin.close( )
Output
10 Write a program to find the most common words in a file.
count = 0
word = " "
maxCount = 0
words = [ ]

#Opens a file in read mode


file = open("data.txt", "r")

#Gets each line till end of file is reached


for line in file:
#Splits each line into words
string = line.lower().replace(',' , ' ').replace('.' , ' ').split(" ");
#Adding all words generated in previous step into words
for s in string:
words.append(s);
#Determine the most common word in a file
for i in range(0, len(words)):
count = 1;
#Count each word in the file and store it in variable count
for j in range(i+1, len(words)):
if(words[i] == words[j]):
count = count + 1;

#If maxCount is less than count then store value of count in maxCount
#and corresponding word to variable word
if(count > maxCount):
maxCount = count;
word = words[i];

print("Most common word: " + word);


file.close();
Output
11 Write a program to count number of words in a file.
fin=open("D:\\python programs\\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
12 Write a program to count the number of times the occurrence of 'is' word in a text file.
fname = input("Enter file name: ")
word= ‘is’
k=0
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
if(i==word):
k=k+1
print("Occurrences of the word:")
print(k)
Output
13 Write a program to write those lines which have the character 'p' from 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:
if 'p' in j:
fout.write(j)
fin.close()
fout.close()

Output 9
14 Create a binary file with name and roll number of student and display the data by reading the file.
import pickle
list =[ ]​# empty list
while True:
​ roll = input("Enter student Roll No:")
​ sname​ = input("Enter student Name :")
​ student = {"roll":roll,"name":sname}
​ list.append(student)
​ choice= input("Want to add more record(y/n) :")
​ if(choice=='n'):
​ break
file = open("student.dat","wb")
pickle.dump(list, file)
file.close( )
Output Enter student Roll No:1201
Enter student Name :Anil
Want to add more record(y/n) :y
Enter student Roll No:1202
Enter student Name :Sunil
Want to add more record(y/n) :n
15 Write a program to search a record using its roll number and display the name of student. If record
not found then display appropriate message.
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( )
for x in list:
if roll in x['roll']:
​ print("Name of student is:", x['name'])
​ break
else:
​ print("Record not found")
Output Enter roll number that you want to search in binary file :1202
Name of student is: Harish
16 Write a program to update the name of student by using its roll number in a binary file
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
x['name'] = input('Enter new name: ')
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( )
Output Enter roll number whose name you want to update in binary file :1202
Enter new name: Harish
Record Updated
17 Write a program to delete a record from 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']:
​ lst.append(x)
else:
​ found = 1
if found == 1:
file.seek(0)
pickle.dump(lst, file)
print("Record Deleted ")
else:
print('Roll Number does not exist')
file.close( )
Output Enter roll number whose record you want to delete:1201
Record Deleted
18 Write a program to read data from a csv file and write data to a 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:
writer = csv.writer(file, delimiter=',', quotechar='"')
#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:
writecsv( )
else:
print("Invalid value")
Output Press-1 to Read Data and Press-2 to Write data:
1
['Roll No.', 'Name of student', 'stream', 'Marks']
['1', 'Anil', 'Arts', '426']
['2', 'Sujata', 'Science', '412']
['3', 'Shivani', 'Commerce', '448']
['4', 'Devansh', 'Arts', '404']
19 Write a program to Create a CSV file by entering user-id and password, read and search the
password for given user-id.
import csv
def searchcsv(id):
with open('E:\\data.csv','rt') as f:
​ data = csv.reader(f)​
​ for row in data:
if row[0]==id:
print(row[1])
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)
Output How many userid you want to enter: 3
Enter userid 1
Saurav
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
20 Write a program to pass an integer list as stack to a function and push 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)
print("The Stack is ", STACK)
M=eval(input("Enter an integer list: "))
PUSH(M)
Output Enter an integer list: [12,21,77,45,14,79,49]
The Stack is [21, 77, 14, 49]
21 Write a menu based program to perform the operation on stack in python.

def push(n):
L.append(n)
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
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:
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

Output MENU BASED STACK


1.​ Push
2.​ Pop
3.​ Display
4.​ Size of Stack
5. Value at Top
Enter your choice (1-5) : 1
Enter the element: 45
Do you want to continue? Y/N y
1.​ Push
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
SQL Queries :
22 Queries using Create database, Show databases, USE, Create table, Show Tables, Describe,
Rename, Alter, Select, From, Where, Insert, Update commands
#Command to create a database
mysql> CREATE DATABASE RAILWAYS;
# Command to show the available databases
mysql> SHOW DATABASES;
# 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”);

# 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;
Write output accordingly
23 Queries using DISTINCT, BETWEEN, IN, LIKE, IS NULL, ORDER BY, GROUP BY, HAVING.
A.​ Display the name of departments. Each department should be displayed once.
SELECT DISTINCT(Dept) FROM EMPLOYEE;
B.​ Find the name and salary of those employees whose salary is between 35000 and 40000.
SELECT Ename, salary FROM EMPLOYEE
WHERE salary BETWEEN 35000 and 40000;
C.​ Find the name of those employees who live in guwahati, surat or jaipur city.
SELECT Ename, city FROM​ EMPLOYEE
WHERE city IN(‘Guwahati’,’Surat’,’Jaipur’);
D.​ Display the name of those employees whose name starts with ‘M’.
SELECT Ename FROM EMPLOYEE
WHERE Ename LIKE ‘M%’;
E.​ List the name of employees not assigned to any department.
SELECT Ename FROM EMPLOYEE
WHERE Dept IS NULL;
F.​ Display the list of employees in descending order of employee code.
SELECT * FROM EMPLOYEE
ORDER BY ecode DESC;

G.​ Find the average salary at each department.


SELECT Dept, avg(salary) FROM EMPLOYEE
group by Dept;

H.​ Find maximum salary of each department and display the name of that
department which has maximum salary more than 39000.
SELECT Dept, Max(salary FROM EMPLOYEE
Group by dept HAVING salary >39000.
Output Write output accordingly
24 Queries for Aggregate functions- SUM( ), AVG( ), MIN( ), MAX( ), COUNT( )
a. Find the average salary of the employees in employee table.
​ SELECT avg(salary) FROM EMPLOYEE;
b. Find the minimum salary of a female employee in EMPLOYEE table.
​ SELECT Ename, min(salary) FROM EMPLOYEE WHERE sex=’F’;
c. Find the maximum salary of a male employee in EMPLOYEE table.
​ SELECT Ename, max(salary) FROM EMPLOYEE WHERE sex=’M’;​
d. Find the total salary of those employees who work in Guwahati city.​ ​ ​
​ SELECT sum(salary) FROM EMPLOYEE WHERE city=’Guwahati’;​
e. Find the number of tuples in the EMPLOYEE relation.​
​ SELECT count(*) FROM EMPLOYEE;​
Write output accordingly
25 Write a program to connect Python with MySQL using database connectivity and perform the
following operation on data in database: Create a table in database.
Solution import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root", passwd="root",
database="EDUCATION")
democursor=demodb.cursor( )
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))")
26 Write a program to connect Python with MySQL using database connectivity and perform the
following operation on data in database: Insert record in the table.
Solution import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="root", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("insert into student values (%s, %s, %s, %s, %s, %s)", (1245, 'Arush', 'M',
'2003-10-04', 'science', 67.34))
demodb.commit( )
27 Write a program to connect Python with MySQL using database connectivity and perform the
following operation on data in database: Fetch records from the table using fetchone( ), fetchall()
and fetchmany( ).
Solution FETCHONE()
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="root", database="EDUCATION")
democursor=demodb.cursor()
democursor.execute("select * from student")
print(democursor.fetchone())

ETCHALL( )
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root", passwd="root",
database="EDUCATION")
democursor=demodb.cursor()
democursor.execute("select * from student")
print(democursor.fetchall())

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

28 Write a program to connect Python with MySQL using database connectivity and perform the
following operation on data in database: Update record in the table
Solution import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="root", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("update student set marks=55.68 where
admn_no=1356")
demodb.commit( )
29 Write a program to connect Python with MySQL using database connectivity and perform the
following operation on data in database: Delete record from the table.
Solution import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="toot", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("delete from student where admn_no=1356")
demodb.commit( )

You might also like