0% found this document useful (0 votes)
429 views36 pages

Class-Xii: Subject - Computer Science (083) Practical File Solution 2020-21 Objective & Solution 1

The document provides source code solutions for 16 computer science practical problems. The problems cover topics like checking if a number is prime, palindrome, compound interest calculation, ASCII value conversion, character classification, counting vowels in a text file, random number generation, linear and bubble sort algorithms, stack operations, and finding most common words in a file. For each problem, the source code, inputs and outputs are listed.

Uploaded by

Soumen Mahato
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)
429 views36 pages

Class-Xii: Subject - Computer Science (083) Practical File Solution 2020-21 Objective & Solution 1

The document provides source code solutions for 16 computer science practical problems. The problems cover topics like checking if a number is prime, palindrome, compound interest calculation, ASCII value conversion, character classification, counting vowels in a text file, random number generation, linear and bubble sort algorithms, stack operations, and finding most common words in a file. For each problem, the source code, inputs and outputs are listed.

Uploaded by

Soumen Mahato
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/ 36

CLASS-XII

SUBJECT – COMPUTER SCIENCE (083)


PRACTICAL FILE SOLUTION 2020-21
PRACTICAL
NO. OBJECTIVE & SOLUTION
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.


num=int(input("Enter a number : "))
SOURCE
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 calculate compound interest.


p=float(input("Enter the principal amount : "))
r=float(input("Enter the rate of interest : "))
t=float(input("Enter the time in years : "))
SOURCE
CODE: x=(1+r/100)**t

CI= p*x-p
print("Compound interest is : ", round(CI,2))
OUTPUT:

4. 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 : ")
print(ord(ch))
elif choice==2:
SOURCE val=int(input("Enter an integer value: "))
CODE: 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
Enter a character : a
97
Do you want to continue? Y/N
OUTPUT: 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
Write a program to input a character and to print whether a given character is an
5.
alphabet, digit or any other character.
ch=input("Enter a character: ")
if ch.isalpha():
print(ch, "is an alphabet")
SOURCE
CODE: elif ch.isdigit():
print(ch, "is a digit")
elif ch.isalnum():
print(ch, "is alphabet and numeric")
else:
print(ch, "is a special symbol")
Enter a character: 7
7 is a digit
OUTPUT:
Enter a character: P
P is an alphabet
6. Write a program to count the number of vowels present in a text file.
Assume that you have a test file Book.txt in the path specified D:\\python
programs\\Book.txt
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)
OUTPUT: 9
Write a program to write those lines which have the character 'p' from one text
7.
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
CODE: if 'p' in j:
fout.write(j)

fin.close()
fout.close()
OUTPUT: **Write contents of book.txt and story.txt
8. 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()
SOURCE
CODE: count_words=0
for i in L:
count_words=count_words+1
print(count_words)
OUTPUT: 16
Write a python function sin(x,n) to calculate the value of sin(x) using its taylor
9. series expansion up to n terms.

import math
def fact(k):
if k<=1:
return 1
else:
return k*fact(k-1)
SOURCE
CODE: step=int(input("How many terms : "))
x=int(input("Enter the value of x :"))
sum=0
for i in range(step+1):
sum+=(math.pow(-1,i)*math.pow(x,2*i+1))/fact(2*i+1)

print("The result of sin",'(', x, ')', "is :", sum)

How many terms : 5


OUTPUT: Enter the value of x :2
The result of sin ( 2 ) is : 0.9092961359628027
Write a program to generate random numbers between 1 to 6 and check whether
10.
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)

OUTPUT:
Enter a number between 1 to 6 : 4
Sorry, Try again, The lucky number was : 1
11. Write a program to create a library in python and import it in a program.
#Rect.py
class Rectangle:
def init (self):
print("Rectangle")
SOURCE
CODE: def Area(self, length, width):
self.l=length
self.w=width
print("Area of Rectangle is : ", self.l*self.w)
#Sq.py
class Square:
def init (self):
print("Square")
def Area(self, side):
self.a=side
print("Area of square is : ", self.a*self.a)

#Tri.py
class Triangle:
def init (self):
print("Trinagle")

def Area(self, base, height):


self.b=base
self.h=height
ar= (1/2)*self.b*self.h
print("Area of Triangle is : ", ar )

#main.py
from Shape import Rect
from Shape import Sq
from Shape import Tri

r=Rect.Rectangle( ) #Create an object r for Rectangle class


r.Area(10,20) # Call the module Area( ) of Rectangle class by passing
argument

s=Sq.Square( ) #Create an object s for Square class


s.Area(10) # Call the module Area( ) of Square class by passing argument

t=Tri.Triangle( ) #Create an object t for Triangle class


t.Area(6,8) # Call the module Area( ) of Triangle class by passing argument

Rectangle
Area of Rectangle is : 200
Square
OUTPUT: Area of square is : 100
Trinagle
Area of Triangle is : 24.0
12. Write a program for linear search.
L=eval(input("Enter the elements: "))
SOURCE n=len(L)
CODE: item=eval(input("Enter the element that you want to search : "))
for i in range(n):
if L[i]==item:
print("Element found at the position :", i+1)
break
else:
print("Element not Found")

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


OUTPUT: Enter the element that you want to search : 33
Element found at the position : 6
13. Write a program for bubble sort.
L=eval(input("Enter the elements:"))
n=len(L)
for p in range(0,n-1):
for i in range(0,n-1):
SOURCE if L[i]>L[i+1]:
CODE: t=L[i]
L[i]=L[i+1]
L[i+1]=t
print("The sorted list is : ", L)

OUTPUT:
Enter the elements:[67,13,89,34,65,8,74,19]
The sorted list is : [8, 13, 19, 34, 65, 67, 74, 89]
14. Write a menu based program to perform the operation on stack in python.
def main():
s=[]
ch="y"
while True:
print( "1. PUSH" )
print( "2. POP " )
print( "3. Display")
choice=int(input("Enter your choice: "))
if (choice==1):
a=input("Enter any number :")
SOURCE
s.append(a)
CODE: elif (choice==2):
if (s==[]):
print( "Stack Empty")
else:
print( "Deleted element is : ",s.pop())
elif (choice==3):
l=len(s)
# To display elements from last element to first
for i in range(l-1,-1,-1):
print(s[i])
else:
print("Wrong Input")
ch=input("Do yo want to continue (y/n) ?,N to exit ")
if ch=='N' or ch=='n':
break
OUTPUT:
15. Write a program to find the most common words in a file.

import collections
SOURCE fin = open('E:\\email.txt','r')
CODE: a= fin.read()
d={ }
L=a.lower().split()

for word in L:
word = word.replace(".","")
word = word.replace(",","")
word = word.replace(":","")
word = word.replace("\"","")
word = word.replace("!","")
word = word.replace("&","")
word = word.replace("*","")

for k in L:
key=k
if key not in d:
count=L.count(key)
d[key]=count

n_print = int(input("How many most common words to print: "))

print("\nOK. The {} most common words are as follows\n".format(n_print))


word_counter = collections.Counter(d)

for word, count in word_counter.most_common(n_print):


print(word, ": ", count)

fin.close()

How many most common words to print: 5

OK. The 5 most common words are as follows

OUTPUT: the : 505


a : 297
is : 247
in : 231
to : 214
16. Write a program to Create a Binary file having students record and display its:-
Content.

#bcbDemo22.py
#Create and Display
SOURCE
CODE:
from pickle import load, dump
import os
import sys
def bfileCreate():
#Creating the dictionary
sd = {'Rollno':10,'Name':'Tom','Marks':550}
fname = input("Enter filename: ")
fout=open(fname,'wb')
choice='N'
while True :
rollno = int(input('Enter roll number: '))
name = input('Enter Name:')
marks = int(input('Enter Marks '))
sd['Rollno'] = rollno
sd['Name']=name
sd['Marks']=marks
dump(sd,fout)
choice =input("want to enter more data Y / N: ")
if choice == 'N' or choice=='n':
break
fout.close()

def bfileDisplay():
import pickle
fname = input("Enter filename you searched for: ")
if not os.path.isfile(fname):
print( "file does not exist")
else:
fin= open(fname,'rb')
try :
while True:
sd = {}
sd = pickle.load(fin)
print(sd)
except EOFError:
pass
fin.close()

WARNING: Maintain proper indentation of the above program


#bcbDemo26.py
def updateRecord():
import pickle
file = open('c:\python37\mybfile1.dat','rb')
sdlst = []
r=int(input("enter roll no to be updated "))
m=int(input("enter correct marks "))
while True:
try:
sd= pickle.load(file)
sdlst.append(sd)
except EOFError:
break
file.close()
for i in range(len(sdlst)):
if sdlst[i]['Rollno']==r:
sdlst[i]['Marks'] = m
file = open('c:\python37\mybfile1.dat','wb')
for x in sdlst:

pickle.dump(x,file)
file.close()
OUTPUT:

17. Write a program to -Search a Record in a Binary file


#bcbDemo25.py
SOURCE def searchRecord():
CODE: import pickle
file = open('c:\python37\mybfile1.dat','rb')
flag = False
#sd = {'Rollno':0,'Name':'','Marks':0}
r=int(input("Enter Rollno to be searched"))
while True:
try:
sd = pickle.load(file)
if sd['Rollno'] == r:
print('Rollno. ',sd['Rollno'])
print('Name:',sd['Name'])
print('Marks:',sd['Marks'])
flag = True
except EOFError:
break
if flag == False:
print('No Records found')
file.close()
OUTPUT

18. Write a program to Update a record read in a binary file.


#bcbDemo26.py
SOURCE
CODE
def updateRecord():
import pickle
file = open('c:\python37\mybfile1.dat','rb')
sdlst = []
r=int(input("enter roll no to be updated "))
m=int(input("enter correct marks "))
while True:
try:
sd= pickle.load(file)
sdlst.append(sd)
except EOFError:
break
file.close()
for i in range(len(sdlst)):
if sdlst[i]['Rollno']==r:
sdlst[i]['Marks'] = m
file = open('c:\python37\mybfile1.dat','wb')
for x in sdlst:
pickle.dump(x,file)
file.close()
OUTPUT

19. Write a program to -Delete a record in a binary file


SOURCE def deleteRecord():
CODE
import pickle
file = open('c:\python37\mybfile1.dat','rb')
sdlst = []
r=int(input("enter roll no to be deleted "))
while True:
try:
sd = pickle.load(file)
sdlst.append(sd)
except EOFError:
break
file.close()
file = open('c:\python37\mybfile1.dat','wb')
for x in sdlst:
if x['Rollno']==r:
continue
pickle.dump(x,file)
file.close()
OUTPUT

20. Write a program to perform read and write operation with .csv file.
import csv
SOURCE
def readcsv():
CODE: with open('C:\\Users\\ViNi\\Downloads\\data.csv','rt')as f:
data = csv.reader(f) #reader function to generate a reader object
for row in data:
print(row)

def writecsv( ):
with open('C:\\Users\\ViNi\\Downloads\\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']

MYSQL -COMMANDS

Queries using DISTINCT, BETWEEN, IN, LIKE, IS NULL, ORDER BY,


GROUP BY, HAVING
21.
A. Display the name of departments. Each department should be displayed once.
SELECT DISTINCT(Dept)
SOLUTION FROM EMPLOYEE;

Find the name and salary of those employees whose salary is between 35000
B.
and 40000.
SELECT Ename, salary
SOLUTION
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
SOLUTION
FROM EMPLOYEE
WHERE city IN(‘Guwahati’,’Surat’,’Jaipur’);

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

E. List the name of employees not assigned to any department.

SELECT Ename
SOLUTION
FROM EMPLOYEE
WHERE Dept IS NULL;

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


SELECT *
FROM EMPLOYEE
SOLUTION
ORDER BY ecode DESC;

G. Find the average salary at each department.


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

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

22. Queries for Aggregate functions- SUM( ), AVG( ), MIN( ), MAX( ), COUNT( )
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
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;

23. Write a program to connect Python with MySQL using database connectivity and
perform the following operations on data in database: Fetch, Update and delete
the data.

A. CREATE A TABLE
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
SOLUTION 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))")

B. INSERT THE DATA


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( )
C. FETCH THE DATA
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
SOLUTION
democursor.execute("select * from student")
for i in democursor:
print(i)

D. UPDATE THE RECORD


import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
SOLUTION democursor=demodb.cursor( )
democursor.execute("update student set marks=55.68 where admn_no=1356")
demodb.commit( )
E. DELETE THE DATA
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( )

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy