0% found this document useful (0 votes)
45 views40 pages

Cs Practical File

Uploaded by

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

Cs Practical File

Uploaded by

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

PRACTICAL FILE

Guided By: Mrs. Jaya Khatri Submitted By: Mr. Devansh Upreti
XII A
Certificate

This is to certify that Mr Devansh Upreti of class XII A has


satisfactorily prosecuted the work assigns to his for the preparation of the
practical file .

This is a bonafied work carried out by the above candidate in my


supervision and guidance .

I gladfully approved his piece of work.

Page 2
Acknowledgment

“Education is not filling-up of a pall but lightning of a fire.” This


saying goes very appropriate in today’s competitive atmosphere where you
have to put in your best constantly to survive. But continuous guidance &
nourishment of experienced hands, side-by-side is also very necessary to
keep you going on the right track. So, this projective and practical
approach towards studies, specially in computers has helped me a lot &
this project has enabled me to understand several concepts of python even
more minutely.

I am truly thankful to my computer teacher Mrs. Jaya Khatri who


encouraged us to do something creative & constructive, apart from our
syllabus. And also, for her unbiased help & guidance which provoked me
to better & better.

I am also thankful to my family members who were with me


throughout the working period of this project and helped me both
mentally & monetarily. I am also thankful to my friends for their
support and cooperation.

THANKS TO ALL

Devansh Upreti
XII A
Page 3
Table of Contents:-

1. Program to calculate simple interest using a function interest() that can receive principal amount, time and
rate and returns calculated simple interest. Do specify default values for rate and time as 10% and 2 years
respectively. ................ 7
2. Program that receives two numbers in a function and returns the results of all arithmetic operation (+,-, ", /,
%) on these numbers......................................................................................................... 8

3. Write a program to input a number and test if it is a prime number...................................................................... 9


4. Write a program to check if a given number is an Armstrong number or not.....................................................10
5. Write a program to check if a given number is a palindrome number or not. .....................................................11
6. Write a program to print the following pattern. ..................................................................................................12
7. Write a program to find frequencies of all elements of a list. Also, print the list of unique elements in the list
and duplicate elements in the given list.
...............................................................................................................13
8. Write a program to find the second largest number of a list of numbers. ...........................................................14
9. Write a program to check if the elements in the first half of a tuple are sorted in ascending order or
not............15
10. Write a program to create a dictionary with the roll number, name and marks of n students in a class and
display the names of students who have marks above 75....................................................................................16
11. Write a program to input your friend’s names and their Phone Numbers and store them in the dictionary as
the key- value pair. Perform the following operations on the dictionary: ...........................................................17
12. Write a program that inputs a main string and then creates an encrypted string by embedding a short symbol-
based string after each character. The program should also be able to produce the decrypted string from
encrypted string. .........................................................................................................................................19
13. Write a random number generator that generates random numbers between 1 and 6 (simulates a dice). ..........20
14.Write a program to read a text file line by line and display each word separated by a "#". .........................22
15. Write a program to read a text file and display the count of vowels and consonants in the file. .......................23
16. Write a program to get student data (roll no., name and marks) from user and write onto a binary file............24
17.Write a program to append student records to file created in previous program, by getting data from user.......25
18. Write a program to open file Stu.dat and search for records with roll numbers as 12 or 14. If found , display
the records.............................................................................................................................................................26
19. Write a program to update the records of the file Stu.dat so that those who have scored more than 81.0, get
additional bonus marks of 2..................................................................................................................................27
20. Write a program to create a CSV file to store student data (Roll no., Name, Marks). Obtain data from user
and write 5 records into the file. ..................................................................................................................28

Page 4
21. Write a program to read following details of sports performance (sport, competitions, prizes-won) of your
school and store into a csv file delimited with tab character. .......................................................29
22. Given the following student relation: ......................................................................................................30
Write SQL commands or (a) to (f) and write output for (g). ...........................................................................33
Before inserting new value to student ………………………………………………………….………34
After inserting new value to student ..............................................................................................................34
23. Given the following tables for a database LIBRARY: ....................................................................................35
Write SQL queries for (a) to (f): ......................................................................................................................36
Before inserting new value to books.......................................................................................................................37
After inserting new value to books ....................................................................................................................38
24. Write a Python program that displays first three rows fetched from student table of MySQL database "test".
.............39
25. Write a Python database connectivity script that deletes records from category table of database items that
have name = "Stockable"..............................................................................................40

Page 5
Problem- Solving
Python
Programs

Page 6
1. Program to calculate simple interest using a function interest() that can receive
principal amount, time and rate and returns calculated simple interest. Do specify default
values for rate and time as 10% and 2 years respectively.
Ans:-

def interest (principal, time = 2, rate = 0.10) :


return principal * rate * time

#_main_
prin = float (input ("Enter principal amount : "))
print("Simple interest with default ROI and time
values is :") si1 = interest(prin)
print("Rs.", si1)
roi = float (input("Enter rate of interest (ROI) :"))
time = int (input("Enter time in years :"))
print("Simple interest with your provided ROI and time values is :")
si2 = interest(prin, time, roi/100)
print("Rs.", si2)

OUTPUT 1 :

Page 7
2. Program that receives two numbers in a function and returns the results of all arithmetic
operation
(+,-, ", /,%) on these numbers.

Ans:-
def arCalc(x, y) :
return x+y , x-y , x*y, x/y,
x%y

#_main_
num1 = int (input("Enter number 1 : "))
num2 = int(input ("Enter number 2 : "))
add, sub, mult, div, mod = arCalc(num1,
num2) print("Sum of given numbers :",
add) print("Subtraction of given
numbers :", sub) print("Product of given
numbers :", mult) print("Division of
given numbers :", div) print("Modulo of
given numbers :", mod)

OUTPUT 2 :

Page 8
3. Write a program to input a number and test if it is a prime number.
Ans:-

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


lim = int(num/2)
+1 for i in range
(2, lim) :
rem = num
% i if rem
== 0:
print(num, "is not a prime number")
break
else:
print (num, "is a prime number")

OUTPUT 3 :

Page 9
4. Write a program to check if a given number is an Armstrong number or not.
(NOTE : If a 3 digit number is equal to the sum of the cubes of its each digit, then it is an
Armstrong Number.)

Ans:-

num = int(input("Enter a 3 digit number: "))


summ = 0
temp =
num
while (temp > 0):
digit = temp %
10 summ +=
digit ** 3
temp //= 10
if (num == summ):
print(num, "is an Armstrong number")
else:
print(num, "is Not an Armstrong number")

OUTPUT 4 :

Page 10
5. Write a program to check if a given number is a palindrome number or not.
(NOTE: A palindrome number's reversed number is same as the number.)
Ans:-

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


wnum = num #working number stores num
initially rev = 0
while(wnum> 0):
dig = wnum %
10 rev = rev*10
+ dig wnum =
wnum // 10

if(num == rev):
print("Number", num, "is a palindrome!")
else:
print("Number", num, "is not a palindrome!")

OUTPUT 5 :

Page 11
6. Write a program to print the following pattern.

*
***
*****
***
*
Ans:-

n =5 #number of lines

#upper half
k = round (n/2)*2 # for initial spaces
for i in range (0, n, 2):
for j in range (0, k + 1):
print (end="")
for j in range (0, i+1):
print( "*", end="")
k =k-2
print ()

#lower half
k=1
for i in range(n-1, 0, -2):
for j in range(0, k+2):
print (end = "")
for j in range(0, i-1):
print("*", end = "")
k = k+2
print()

OUTPUT 6 :

Page 12
7. Write a program to find frequencies of all elements of a list. Also, print the list of
unique elements in the list and duplicate elements in the given list.
Ans:-

lst = eval(input ( "Enter list :"))


length = len (lst)
uniq = [ ] # list to hold unique elements
dupl = [ ] # list to hold duplicate elements
count = i = 0
while i< length:
element = lst [i]
count = 1 # count as 1 for the element at lst[i]
if element not in uniq and element not in dupl:
i+=1
for j in range (i, length):
if element == lst[j]:
count+=1
else: #when inner loop for loop ends
print ("Element", element, "frequency: ", count)
if count == 1:
uniq.append (element )
else:
dupl.append (element)
#when element is found in uniq or dupl lists
else:
i+=1

print("Original list", lst)


print("Unique element list", uniq)
print("Duplicates elements list", dupl)

OUTPUT 7:

Page 13
8. Write a program to fnd the second largest number of a list of numbers.
Ans:-

lst = eval(input ("Enter list: "))


length = len(lst)
biggest = secondbiggest = lst[0] #though
logically not fair for i in range (1, length) :
if lst[i] > biggest:
secondbiggest =
biggest biggest =
lst[i]
elif lst[i] < biggest and lst[i] > secondbiggest:
secondbiggest =
lst[i]
print("Largest number of the list:", biggest)
print ("Second Largest number of the list:", secondbiggest)

OUTPUT 8 :

Page 14
9. Write a program to check if the elements in the first half of a tuple are sorted in
ascending order or not.
Ans:-

tup = eval(input ("Enter a tuple: "))


ln = len(tup)
mid= ln//2
if ln % 2 == 1:
mid = mid+1
half =
tup[ :mid]
if sorted (half) == list(tup[ :mid]):
print("First half is
sorted")
else:
print("First half is not sorted")

OUTPUT 9 :

Page 15
10. Write a program to create a dictionary with the roll number, name and marks of n
students in a class and display the names of students who have marks above 75.
Ans:-

n = int (input ("How many Students?"))


stu = {}
for i in range (1, n+1):
print("Enter details of Student", (i))
rollno = int (input ("Roll number :"))
name = input ( "Name:")
marks = float (input ("Marks:"))
d ={"Rol1_no": rollno, "Name" : name, "Marks": marks}
key ="Stu" + str(i)
stu[key] = d
print("Students with marks > 75 are: ")
for i in range (1, n+1):
key = "Stu" + str(i)
if stu[key]["Marks"] >= 75:
print (stu[key])

OUTPUT 10 :

Page 16
11. Write a program to input your friend’s names and their Phone Numbers and store them in the
dictionary as the key-value pair. Perform the following operations on the dictionary :
(a) Display the name and phone number of all your friends
(b) Add a new key-value pair in this dictionary and display the modified dictionary
(c) Delete a particular friend from the dictionary
(d) Modify the phone number of an existing friend
(e) Check if a friend is present in the dictionary or not
(f) Display the dictionary in sorted order of names
Ans:-
n = int(input ("How many friends?"))
fd = {}
for i in range(n):
print("Enter details of friends",(i+1))
name = input("Name:")
ph = int(input('Phone : '))
fd[name] = ph
print("Friends dictionary is",fd)
ch= 0
while ch!= 7:
print("\tMenu")
print("1. Display all friends")
print("2. Add new friend")
print("3. Delete a friend")
print("4. Modify the phone number")
print("5. Search for a friend")
print("6. Sort on names")
print("7. Exit")
ch = int(input(" Enter your choice (l..7): "))
if ch == 1:
print(fd)
if ch == 2:
print("Enter details of a new friend")
name = input ("Name:")
ph = int(input ("Phone : "))
fd[name] = ph
elif ch == 3:
nm = input ("Friend Name to be deleted: ")
res = fd.pop(nm, -1)
if res != -1:
print (res, "deleted")
else:
print ("No such friend")
elif ch == 4:
name = input("Friend Name: ")
Page 17
ph = int(input ("changed Phone :"))
fd[name] = ph
elif ch == 5:
name = input ("Friend Name : ")
if name in fd:
print (name, "exists in the dictionary.")
else:
print (name, "does not exist in the dictionary .")
elif ch == 6:
lst = sorted (fd)
print("{", end = "")
for a in lst:
print (a, ":", fd[a], end = "")
print ("}")
elif ch == 7:
break
else:
print("Valid choices are 1..7")

OUTPUT 11 :

Page 18
12. Write a program that inputs a main string and then creates an encrypted string by
embedding a short symbol based string after each character. The program should also be
able to produce the decrypted string from encrypted string.
Ans:-

def encrypt(sttr, enkey):


return enkey.join (sttr)
def decrypt (sttr, enkey):
return sttr.split(enkey)
#_main_
mainString = input ("Enter main
string:") encryptStr = input (" Enter
encryption key : ") enStr =
encrypt(mainString, encryptStr)
deLst = decrypt (enStr, encryptStr)
# deLst is in the form of a list, converting it to
string below deStr = "".join(deLst)
print("The encrypted string is", enStr)
print("String after decryption is: ", deStr)

OUTPUT 12 :

Page 19
13. Write a random number generator that generates random numbers between 1 and
6 (simulates a dice).
Ans:-

import
random min
=1
max = 6
roll_again =
"y"
while roll_again == "y" or roll_again == "Y" :
print("Rolling the dice... ")
val = random.randint (min, max)
print("You get...:", val)
roll_again = input ("Roll the dice again? (y/n)... ")

OUTPUT 13 :

Page 20
File
Handling and
SQL Programs

Page 21
14.Write a program to read a text file line by line and display each word separated by a
"#".
Ans:-

myfile= open("Answer.txt", "r")


line = "" #initially stored a space (a non-None value)
while line:
line = myfile.readline() # one line read from file
# printing the line word by word using split()
for word in line.split():
print (word, end= '#')
print()
#close the
file
myfile.close
()

OUTPUT 14 :

Page 22
15. Write a program to read a text file and display the count of vowels and consonants in the
file.
Ans:-

myfile = open("Answer.txt ", "r")


ch= "" #initially stored a space (a non-None value)
vcount = 0 #variable to store count of
vowels ccount = 0 #variable to store
count of consonants while ch : #while
ch stores a Non - None value
ch = myfile.read(1) #one character read
from file if ch in ['a', 'A', 'e', 'E', 'i', 'I', 'o', '0',
'u', 'U']:
vcount =
vcount+1 else :
ccount= ccount+1
print("Vowels in the file:",
vcount) print("consonants in the
file: " , ccount)
#close the file
myfile.close( )

OUTPUT 15 :

Page 23
16. Write a program to get student data (roll no., name and marks) from user and
write onto a binary file.
The program should be able to get data from the user and write onto the file as long as the user
wants.
Ans:-
import pickle
stu = {} # declare empty
dictionary stufile = open("Stu.dat", "wb")
#open file
# get data to write onto
the file ans = 'y'
while ans == 'y':
rno = int(input ("Enter roll number: "))
name = input ("Enter name: ")
marks = float (input ("Enter marks: "))
# add read data into
dictionary stu['Rollno'] =
rno
stu['Name'] =
name stu['Marks']
= marks
# now write into the
file pickle.dump (stu,
stufile)
ans = input("Want to enter more records? (y/n)...")
stufile.close( ) #close file

OUTPUT 16 :

Page 24
17.Write a program to append student records to file created in previous program, by
getting data from user.
Ans:-
import pickle
# declare empty
dictionary stu = {}
#open file in append mode
stufile = open('Stu.dat ', 'ab')
#get data to write onto
the file ans = 'y'
while ans == 'y':
rno= int(input ("Enter roll number: "))
name = input("Enter name : ")
marks = float ( input("Enter marks: "))
#add read data into
dictionary stu['Rollno'] =
rno
stu['Name'] =
name stu['Marks']
= marks
# now write into the
file pickle.dump(stu,
stufile)
ans = input("Want to append more records? (y/n)...")
#close file
stufile.close
()

OUTPUT 17 :

Page 25
18. Write a program to open file Stu.dat and search for records with roll numbers as 12
or 14. If found , display the records.
Ans:-

import pickle
stu = {} # declare empty dictionary object to hold
read records found = False
fin = open('Stu.dat', 'rb') #open binary file in read mode
searchkeys = [12, 14] #list contains key values to be searched for

# read from the


file try:
print("Searching in File Stu.dat ...")
while True: #it will become False upon EOF exception
stu = pickle.load(fin) #read record in stu dictionary from fin
file handle if stu["Rollno"] in searchkeys:
print(stu) #print the
record found = True

except EOFError :
if found == False :
print("No Such records found in the file")
else:
print(" Search successful. ")
fin.close( ) # close file

OUTPUT 18 :

Page 26
19. Write a program to update the records of the file Stu.dat so that those who have scored
more than 81.0 , get additional bonus marks of 2.
Consider the binary file Stu.dat storing student details, which you created in earlier programs,
Ans:-
import pickle
stu = {} # declare empty dictionary object to hold
read records found = False
fin = open('Stu.dat', 'rb+') #open binary file in read and write mode

# read from the


file try:
while True:
rpos = fin.tell( ) #store file-pointer position before reading
the record stu = pickle.load(fin)

if stu["Marks"] >
81: stu["Marks"]
+= 2
fin.seek(rpos)
pickle.dump(stu,f
in) found = True

except EOFError :
if found == False :
print("Sorry, no matching records found.")
else:
print("Record(s) successfully updated ")
fin.close( ) # close file

OUTPUT 19:

Page 27
20. Write a program to create a CSV file to store student data (Rollno. , Name, Marks).
Obtain data from user and write 5 records into the file.
Ans:-
import csv
fh = open("student.csv", "w")
#open file stuwriter = csv.writer (fh)
stuwriter.writerow([ "Rollno", "Name", "Marks"]) #write header row

for i in range (5) :


print("Student record", (i+1))
rollno = int (input ("Enter rollno: "))
name = input ("Enter name: ")
marks = float (input ("Enter marks: "))
sturec = [rollno , name, marks] #create sequence
of user data stuwriter.writerow(sturec)

fh.close( ) #close file

OUTPUT 20 :

Page 28
21. Write a program to read following details of sports performance (sport, competitions,
prizes-won) of your school and store into a csv file delimited with tab character.
Ans:-

import csv
fh = open("Sport.csv ", "w")
swriter = csv.writer(fh, delimiter='\t')
swriter.writerow( ['Sport', 'Competitions', 'Prizes won' ]) #write header row
ans= 'y'
i=1
while ans == 'y':
print("Record", i)
sport = input('Sport name: ' )
comp =int (input ('No. of competitions participated: ') )
prizes= int(input ("prizes won:"))
srec = [ sport, comp, prizes ] #create sequence of user data
swriter.writerow(srec)
i = i+1
ans = input ('Want to enter more records? (y/n).. ')
fh.close( )

OUTPUT 21:

Page 29
22. Given the following student relation :

Table: Relation Student

NO. NAME AGE DEPARTMENT DATEOFADM FEE SEX


1. Pankaj 24 Computer 10/01/97 120 M
2. Shalini 21 History 24/03/98 200 F
3. Sanjay 22 Hindi 12/12/96 300 M
4. Sudha 25 History 01/07/99 400 F
5. Rakesh 22 Hindi 05/09/97 250 M
6. Shakeel 30 History 27/06/98 300 M
7. Surya 34 Computer 25/02/97 210 M
8. Shikha 23 Hindi 31/07/97 200 F

Write SQL commands or (a) to (f) and write output for (g).
(a) To show all information about the students of History
department. (b) To list the names of female students who
are in Hindi department.
(c) To list names of all students with their date of admission in
ascending order. (d) To display student's Name, Fee, Age for male
Students only.
(e) To count the number of student with Age < 23.
(f) To insert a new row in the STUDENT table with the following data :
9, "Zaheer", 36, "Computer", {12/03/97},
230, "M " (g) Give the output of following SQl
statements:
(i) Select COUNT(distinct department) from
STUDENT; (ii) Select MAX(Age) from
STUDENT where Sex="F";
(iii) Select AVG(Fee) from STUDENT where Dateofadm<
'1998-01-01' ; (iv)Select SUM(Fee) from STUDENT where
Dateofadm< '1998-01-01';

Page 30
Ans:-
(a) SELECT * FROM Student
WHERE Department = "History" ;

(b) SELECT Name FROM Student


WHERE sex = "F" and Department =
"Hindi" ;

(c) SELECT name FROM Student


ORDER BY Dateofadm ;

(d) SELECT Name,Fee, Age


FROM Student WHERE Sex= "M" ;

(e) SELECT Count(*) FROM Student


Where age < 23;

(f) INSERT INTO Student


VALUES (9, "Zaheer",36, "Computer", '1997-03-12', 230, "M");

(g) (i)3 (ii)25 (iii)216 or 220 (iv)1080 or 1540

Page 31
OUTPUT 22:

Page 32
Page 33
Before inserting new value to student

After inserting new value to student

Page 34
23. Given the following tables for a database LIBRARY :

Table : BOOKS
BOOK_ID BOOK_NAME AUTHOR_NAME PUBLISHER PRICE TYPE QTY
C0001 Fast Cook Lata Kapoor EPB 355 Cookery 5
F0001 The Tears William Hopkins First Publ 650 Fiction 20
T0001 My First C++ Brian & Brooke EPB 350 Text 10
T0002 C++ Brainworks A.W. Rossaine TDH 350 Text 15
F0002 Thunderbolts Anna Roberts First Publ 750 Fiction 50

Table : ISSUED
BOOK_ID QUALITY_ISSUED
T0001 4
C0001 5
F0001 2

Write SQL queries for (a) to (f):


(a) To show Book name, Author name and Price of books of First Publ. publishers.
(b) To list the names from books of Text type.
(c) To display the names and price from books in ascending order of their price.
(d) To increase the price of all books of EPB Publishers by 50.
(e) To display the Book_ld, Book_Name and Quantity_Issued for all books which have been issued. (The query
will require contents from both the tables.)
(f) To insert a new row in the table Issued having the following data: "F0003", 1
(g) Give the output of the following queries based on the above tables:
(i) SELECT COUNT(*) FROM Books;
(ii) SELECT MAX(Price) FROM Books WHERE Qty >= 15;
(iii) SELECT Book_Name, Author_Name FROM Books WHERE Publisher = "EPB";
(iv) SELECT COUNT(DISTINCT Publisher) FROM Books WHERE Price >= 400;

Ans:-
(a) SELECT Book_Name, Author_Name, Price
FROM Books
WHERE Publisher = "First Publ";

(b) SELECT Book_Name


FROM Books
WHERE Type ="Text";

(c) SELECT Book_Name, Price


FROM Books
ORDER BY Price;
Page 35
(d) UPDATE Books
SET Price = Price+50
WHERE Publisher = "EPB";

(e) SELECT Books.Book_Id, Book_Name, Quantity_Issued


FROM Books, Issued
WHERE Books.Book_Id = Issued.Book_Id ;

(f) INSERT INTO Issued


VALUES("F0003", 1);

(e) (i) 5 (ii) 750 (iii) Fast Cook Lata Kapoor (iv) 1 or 2
My First C++ Brian & Brooke

OUTPUT 23 :

Page 36
Page 37
Before inserting new value to books

After inserting new value to books

Page 38
24. Write a Python program that displays first three rows fetched from student table of
MySQL database
"test".
(NOTE : user is "learner" and password is "fast")

Ans:-

import mysql.connector as sqltor


mycon = sqltor.connect (host ="localhost ", user = "learner", passwd="fast", database= "test")
if mycon.is_connected() == False:
print('Error connecting to MySQL database')
cursor = mycon.cursor()
cursor.execute("select * from
student") data = cursor.
fetchmany(3)
count =
cursor.rowcount for
row in data :
print(row)
mycon.close ()

OUTPUT 24:

Page 39
25. Write a Python database connectivity script that deletes records from category
table of database items that have name = "Stockable".
Ans:-

import mysql.connector as ctor


dbcon = ctor.connect (host = "localhost", user= "learner", passwd="fast", database = "items")
cursor= dbcon.cursor()
sql1 = "DELETE FROM category WHERE name='{}'".format('Stockable')
cursor.execute (sql1)
dbcon.commit () # commit the
changes print("Rows affected: ",
cursor.rowcount) dbcon.close()

OUTPUT 25:

Page 40

You might also like