C.S ASSIGNMENT FILE 2020 21 Python
C.S ASSIGNMENT FILE 2020 21 Python
C.S ASSIGNMENT FILE 2020 21 Python
ASSIGNMENT FILE
XII - C
INDEX
SR TITLE PAGE
NO . NO.
1. Program to calculate simple interest 4
2. Program that receives two numbers in a function and returns the results 5
of all arithmetic operations( +,-,*,/,%) on these numbers
7. Write a program to take two strings from user and displays the smaller 10
string in single line and larger string
8. Program to find frequencies of all elements of a list . Also , print the list 11-12
of unique elements in the list and duplicate elements in the given list
10. Write a program to check if the elements in the first half of a tuple are 14
sorted in ascending order or not
Write a program to create a dictionary with the roll number, name and
12. marks of n students in a class and display the names of students who 16-17
have marks above 75
13. Write a program to input your friend’s names and their phone numbers 18-22
and store them in the dictionary as the key-value pair
16. Write a program that inputs main string and then creates an encrypted 25
string by embedding a short symbol based string after each character
18. Write a program to read a text file line by line and display each word 27
separated by a ‘#’
19. Write a program to read a text file and display the count of vowels and 28
consonants in the file
20. Write a program to get student data(roll no. , name and marks) from 29
user and write onto a binary file
22. Write a program to open file Stu.dat and search for records with roll 31
numbers as 46 or 48 . If found display the records
23. Write a program to update the records of the file Stu.dat so that those 32
who have scored more than 81.0, get additional bonus marks of 2
32. Write a python program that displays a first three rows fetched from 55
student table of MySQL database “test”.
33. Write a python database connectivity script that deletes records from 56
category table of database items that have name = ‘Stockable’
Q.1 Program to calculate simple interest using a function interes() 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 .
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 )
Q.3 Program to input a number and test if it is a prime number .
FOR EXAMPLE:
import json
sentence = "This is a super idea This\
idea will change the idea of learning"
words = sentence.split()
d = {}
for one in words:
key = one
if key not in d:
count= words.count(key)
d[key] = count
print("Counting frequencies in list \n",words)
print(json.dumps(d, indent=1))
Q.12 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.
aList = [15,6,13,22,3,52,2]
print("Original list is:",aList)
for i in range(1,len(aList)):
key = aList[i]
j = i-1
while j >= 0 and key < aList[j]:
aList[j+1] = aList[j]
j=j-1
else:
aList[j+1] = key
print("List after sorting:",aList)
Q.15 Program to sort a list using bubble sort.
alist = [15,6,13,22,3,52,2]
print("original list is:",alist)
n = len(alist)
for i in range(n):
for j in range(0,n-i-1):
if alist[j] > alist[j+1]:
alist[j],alist[j+1] = alist[j+1],alist[j]
print("list after sorting:",alist)
Q.16 Write a program that inputs 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.
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)
destr = "".join(delst)
print("the encrypted string is",enstr)
print("string after dcryption is:",destr)
Q.17 Write a random number generator that generates random numbers between 1 and
6(simulates a dice).
import random
min = 1
max = 6
rollagain = "y"
while rollagain == "y" or rollagain =="Y":
print("Rolling the dice...")
val = random.randint(min,max)
print("You get...:",val)
rollagain = input("Roll the dice again? (y/n)..")
Q.18 Write a program to read a text file line by line and display each word separated by
a ‘#’.
myfile = open("answer.txt","r")
ch = ""
vcount = 0
ccount = 0
while ch:
ch = myfile.read(1)
if ch in['a','A','e','E','i','I','o','O','u','U']:
vcount = vcount +1
else:
ccount = ccount +1
print("vowels in the file:",vcount)
print("consonants in the file:",ccount)
myfile.close()
Q.20 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
import pickle
stu= {}
stufile = open('Stu.dat', 'wb')
ans = 'y'
while ans == 'y' :
rno = int(input("Enter roll number : "))
name = input("Enter name :")
marks = float(input("Enter marks : "))
stu['Rollno'] = rno
stu['Name'] = name
stu['Marks'] = marks
pickle.dump(stu, stufile)
ans = input("Want to enter more records? (y/n)...")
stufile.close()
Q.21 Write a program to append student records to file created in previous program, by
getting data from user.
import pickle
stu = { }
stufile = open('Stu.dat', 'ab')
ans = 'y'
while ans == 'y' :
rno = int(input("Enter roll number :"))
name = input("Enter name :")
marks = float( input("Enter marks: "))
stu['Rollno'] = rno
stu[ 'Name'] = name
stu[ 'Marks'] = marks
pickle.dump(stu, stufile)
ans = input("Want to append more records? (y/n)...")
stufile.close()
Q.22 Write a program to open file Stu.dat and search for records with roll numbers as
46 or 48 . If found display the records.
import pickle
stu = {}
found = False
fin = open('Stu.dat', 'rb')
searchkeys = [46, 48]
try:
print("Searching in File Stu.dat ...")
while True :
stu = pickle.load(fin)
if stu['Rollno'] in searchkeys :
print(stu)
found = True
except EOFError:
if found == False :
print("No such records found in the file")
else:
print("Search successful.")
fin.close()
Q.23 Consider the binary file Stu.dat storing student details, which you created in
earlier programs. 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.
import pickle
stu = {}
found = False
fin = open('Stu.dat', 'rb+')
try:
while True :
rpos = fin.tell()
stu = pickle.load(fin)
if stu['Marks'] > 81 :
stu['Marks'] += 2
fin.seek(rpos)
pickle.dump(stu, fin)
found = True
except EOFError:
if found == False:
print("Sorry, no matching record found.")
else:
print("Record(s) successfully updated.")
fin.close()
Q.24 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.
import csv
fh = open("Student.csv", "w")
stuwriter = csv.writer(fh)
stuwriter.writerow(['Rollno', 'Name', 'Marks'])
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 ]
stuwriter.writerow(sturec)
fh.close()
Q.25 Write a program to read following details of sport’s performance (sport ,
competitions, prizes-won) of your school and store into a csv file delimited with tab
character .
import csv
fh = open("Sport.csv", "w")
swriter = csv.writer(fh, delimiter='\t')
swriter.writerow( ['Sport', 'Competitions', 'Prizes won'])
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 = 1+1
ans = input("Want to enter more records? (y/n)..")
fh.close()
Q.26 Inserting an element in a sorted array using traditional algorithm.
i = size -1
while i >= pos :
AR[i] = AR[i-1]
i =i-1
#_main_
myList = [18, 29, 30, 40, 50, 60, 70]
print("The list in sorted order is")
print(myList)
ITEM = int(input("Enter new element to be inserted :"))
position = FindPos( myList, ITEM)
Shift (myList, position)
myList[position] = ITEM
print("The list after inserting", ITEM, "is")
print(myList)
Q.27 Deletion of an element from a sorted linear list.
if position :
del myList[position]
print("The list after deleting", ITEM, "is")
print(myList)
else:
print("SORRY! No such element in the list")
Q.28 Python program to implement stack operations.
def Pop(stk):
if isEmpty(stk):
return "Underflow"
else:
item = stk.pop()
if len (stk) == 0:
top = None
else:
top = len(stk) - 1
return item
def Peek(stk):
if isEmpty(stk):
return "Underflow"
else:
top = len(stk) - 1
return stk[top]
def Display(stk):
if isEmpty(stk) :
print("Stack empty")
else :
top = len(stk) - 1
print(stk[top], "<- top")
for a in range(top-1, -1, -1):
print(stk[a])
Stack = []
top = None
while True :
print("STACK OPERATIONS")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display stack")
print("5. Exit")
ch = int(input("Enter your choice (1-5) :"))
if ch == 1 :
item = int(input("Enter item :"))
Push(Stack, item)
elif ch == 2 :
item = Pop(Stack)
if item == "Underflow" :
print("Underflow! Stack is empty!")
else:
print("Popped item is", item)
elif ch == 3:
item = Peek (Stack)
if item == "Underflow" :
print("Underflow! Stack is empty!")
else:
print("Topmost item is", item)
elif ch == 4 :
Display (Stack)
elif ch == 5 :
break
else:
print("Invalid choice!")
Q.29 Program to implement Queue operations.
def cls():
print("\n"* 100)
def Peek(Qu):
if isEmpty(Qu):
return "Underflow"
else:
front = 0
return Qu[front]
def Display(Qu):
if isEmpty(Qu):
print("Queue Empty!")
elif len(Qu) == 1:
print(Qu[0], "<== front, rear")
else:
front = 0
rear = len(Qu) - 1
print(Qu[front], "<- front")
for a in range(1, rear):
print(Qu[a])
print(Qu[rear], "<-rear")
#_main_program
queue = []
front = None
while True :
cls()
print("QUEUE OPERATIONS")
print("1. Enqueue")
print("2. Dequeue")
print("3. Peek")
print("4. Display queue")
print("5. Exit")
ch = int(input("Enter your choice (1-5): "))
if ch == 1:
item = int(input("Enter item :"))
Enqueue (queue, item)
input("Press Enter to continue...")
elif ch == 2:
item - Dequeue (queue)
if item == "Underflow":
print("Underflow! Queue is empty!")
else:
print("Dequeue-ed item is", item)
input("Press Enter to continue...")
elif ch == 3:
item = Peek (queue)
if item == "Underflow" :
print("Queue is empty!")
else :
print("Frontmost item is", item)
input("Press Enter to continue...")
elif ch == 4 :
Display(queue)
input("Press Enter to continue...")
elif ch == 5:
break
else:
print("Invalid choice!")
input("Press Enter to continue...")
Q.30 Given the following student relation :
Write SQL commands for (a) to (f) and write output for (g).
(d) To display student’s Name, Fee, Age for male Students only.
(e) To display the Book_id,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