Cs Practical File
Cs Practical File
Guided By: Mrs. Jaya Khatri Submitted By: Mr. Devansh Upreti
XII A
Certificate
Page 2
Acknowledgment
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
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:-
#_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:-
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:-
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:-
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:-
OUTPUT 7:
Page 13
8. Write a program to fnd the second largest number of a list of numbers.
Ans:-
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:-
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:-
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:-
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:-
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:-
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
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
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
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 :
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" ;
Page 31
OUTPUT 22:
Page 32
Page 33
Before 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
Ans:-
(a) SELECT Book_Name, Author_Name, Price
FROM Books
WHERE Publisher = "First Publ";
(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
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:-
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:-
OUTPUT 25:
Page 40