D Practical File 2
D Practical File 2
COMPUTER SCIENCE
[083]
PRACTICAL FILE
SESSION: 2023-2024
S.N
O INDEX
PROGRAMS BASED ON CONTROL STRUCTURES
1. Write a program to implement a card game called “DRAGONS AND
WIZARDS”. Make two teams Dragons and Wizards. The rules of the
game are as follows
If the card drawn is a diamond or a club, Team Dragons gets a point.
If the card drawn is a heart which is a number, team Wizard gets a
point
If the card drawn is a heart that is not a number, team dragon gets
a point
For any other card, team wizard gets a point
The team with highest point is the winner.
Input: shape, value
Process: Increment in respective team scores by one based on the
outcome of the card drawn, as defined in the rules.
Output: Winning Team
2. Write a Python program that requests five integer values from the user.
It then prints the maximum and minimum values entered. If the user
enters the values 3, 2, 5, 0, and 1, the program would indicate that 5 is
the maximum and 0 is the minimum. Your program should handle ties
properly; for example, if the user enters 2, 4, 2, 3, and 3, the program
should report 2 as the minimum and 4 as maximum.
3. Write a program that simulates a traffic light. The program should
consist of the following:
A user defined function trafficLight() that accepts input from
the user and displays an error message if user enters anything
other than RED, YELLOW or GREEN. Function LIGHT() is
called and following is displayed depending upon return value
from LIGHT()
o “STOP, your life is precious” if the value returned by
LIGHT() is 0.
o “Please WAIT, untill the light is green”, if the
value returned by LIGHT() is 1
o “GO! Thankyou for being patient”, if the value returned by
LIGHT() is 2.
A user defined function LIGHT() that accepts a string as input
and returns 0 when the input is RED, 1 when the input is
YELLOW and 2 when the input is GREEN. The input should be
passed as an argument.
Talk. Give me a word with three consecutive double letters. I’ll give you a couple of
words that almost qualify, but don’t. For example, the word committee, c-o-m-m-i-
t-t-e-e. It would be great except for the ‘i’ that sneaks in there. Or Mississippi: M-i- s-
s-i-s-s-ip- p-i. If you could take out those i’s it would work. But there is a word that
has three consecutive pairs of letters and to the best of my knowledge this may
be the only word. Of course there are probably 500 more but I can only think of one.
What is the word? Write a program to find it/them out of the given string.
8. Two words are anagrams if you can rearrange the letters from one to spell the other.
Write a function called is_anagram that takes two strings and returns True if they
are anagrams.
9. Complete the following function that determines if the number of even and odd
values in an integer list is the same. The function would return true if the list contains
5, 1, 0, 2 (two evens and two odds), but it would return false for the list containing 5,
1, 0, 2, 11 (too many odds). The function should return true if the list is empty, since
an empty list contains the same number of evens and odds (0 for both). The function
does not affect the contents of the list.
def balanced(a):
# Add your code...
10. Write a program that takes a list of words and creates a dictionary with frequency
(number of occurences) of word as key and list of words for that frequency as value.
For example, if list is given as [‘the’,’of’, ‘an’, ‘is’, ‘an’, ‘the’]
Then dictionary should be {2:[‘the’,’an’],1:[‘of’,’is’]}
11. Write a program to find the frequency of values in the given dictionary. For example,
if the dictionary is given as D={‘P1’:60,’P2’:30,’P3’:50,’P4’:60,’P5’:30,’P6’:10}
Then output should be {10:1,30:2,50:1,60:2}
PROGRAMS BASED ON TEXT FILES
14 Create the tables and Write the SQL queries and capture the screens of executed
queries for the following:
Table: STOCK
NO ITEMCODE QUANTITY
DATEOFPURCHASE WARRANTY
1 C201 9 21-May-2005 2
2 P1010 3 21-May-2005 4
3 S203 1 29-Sep-2004 3
4 C201 2 13-Jun-2005 1
5 P1010 1 31-Oct-2004 2
6 U34 5 21-May-2005 1
7 P1010 2 11-Jan-2006 2
Table: ITEM
ITEMCODE ITEMNAME PRICE
C201 Computer 39000
P1010 Printer 11000
S203 Scanner 4500
WC05 Camera 1200
U34 UPS 1900
Table: INTERIORS
NO ITEMNAME TYPE DATEOFSTOCK PRICE DISCOUNT
1 Red rose Double 23-Feb-2006 32000 15
Bed
2 Soft touch Baby cot 20-Jan-2006 9000 10
3 Jerry’s home Baby cot 19-Feb-2006 8500 10
4 Rough woof Office 01-Jan-2006 20000 20
table
5 Comfort zone Double bed 12-Jan-2006 15000 20
6 Jerry look Baby cot 24-Feb-2006 7000 19
7 Lion king Office 20-Feb-2006 16000 20
table
1. To show all information about the Sofa’s from the interiors table.
2. To list the item name which are priced more than 10000 from the interiors
table. I
3. To display item name and date of stock of those items, in which the
discount percentage is more than 15.
4. To list item name and type of items, in which data of stock is before 22- Jan-
2002 in descending order of item name.
5. To count the number of items of each type.
6. To insert new row in interiors table with following data:
11 White wood Double bed 23-Feb-2006 20000 20
Aim 1:
Write a program to implement a card game called “DRAGONS AND
WIZARDS”. Make two teams Dragons and Wizards. The rules of the
game are as follows
If the card drawn is a diamond or a club, Team Dragons gets a point.
If the card drawn is a heart which is a number, team Wizard gets a
point
If the card drawn is a heart that is not a number, team dragon gets a
point For any other card, team wizard gets a point
The team with highest point is the winner.
Input: shape, value
Process: Increment in respective team scores by one based on the
outcome of the card drawn, as defined in the rules.
Output: Winning Team
Code:
print('WELCOME TO DRAGONS AND WIZARDS!')
s=input('WHAT IS THE SHAPE OF YOUR CARD? (SPADE/
DIAMOND/ CLUB/ HEART): ')
v=input('WHAT IS THE VALUE OF YOUR CARD? (FACE/ JOKER/
NUMBER): ')
dragons=wizards=0
if s=='DIAMOND' or s=='CLUB':
dragons=dragons+1
elif s=='HEART':
if v=='NUMBER':
wizards=wizards+1
else:
dragons=dragons+1
else:
wizards=wizards+1
print('SCORES ARE: WIZARDS = {} AND DRAGONS =
{}'.format(wizards,dragons))
if wizards<dragons:
print('CONGRATULATIONS SPINE-CHILLING DRAGONS!
YOU HAVE WON THE BATTLE!')
else:
DIVVYANSH KUDESIAA SESSION 2023-2024 CLASS XII-D
COMPUTER SCIENCE PRACTICAL FILE
Output:
Aim 2:
Write a Python program that requests five integer values from the user.
It then prints the maximum and minimum values entered. If the user
enters the values 3, 2, 5, 0, and 1, the program would indicate that 5 is
the maximum and 0 is the minimum. Your program should handle ties
properly; for example, if the user enters 2, 4, 2, 3, and 3, the program
should report 2 as the minimum and 4 as maximum.
Code:
n1=int(input('Enter first number: '))
n2=int(input('Enter second number: '))
n3=int(input('Enter third number: '))
n4=int(input('Enter fourth number: '))
n5=int(input('Enter fifth number: '))
if n1>=n2 and n1>=n3 and n1>=n4 and n1>=n5:
print('Maximum value is',n1)
elif n2>=n1 and n2>=n3 and n2>=n4 and n2>=n5:
print('Maximum value is',n2)
elif n3>=n1 and n3>=n2 and n3>=n4 and n3>=n5:
print('Maximum value is',n3)
elif n4>=n1 and n4>=n2 and n4>=n3 and n4>=n5:
print('Maximum value is',n4)
else:
print('Maximum value is',n5)
if n1<=n2 and n1<=n3 and n1<=n4 and n1<=n5:
print('Minumum value is',n1)
elif n2<=n1 and n2<=n3 and n2<=n4 and n2<=n5:
print('Minumum value is',n2)
else:
print('Minumum value is',n5)
Output:
Aim 3:
Write a program that simulates a traffic light. The program should
consist of the following:
A user defined function trafficLight() that accepts input from
the user and displays an error message if user enters anything
other than RED, YELLOW or GREEN. Function LIGHT() is
called and following is displayed depending upon return value
from LIGHT()
o “STOP, your life is precious” if the value returned by
LIGHT() is 0.
o “Please WAIT, untill the light is green”, if the value
returned by LIGHT() is 1
o “GO! Thankyou for being patient”, if the value returned
by LIGHT() is 2.
A user defined function LIGHT() that accepts a string as input
and returns 0 when the input is RED, 1 when the input is
YELLOW and 2 when the input is GREEN. The input should
be passed as an argument.
Display “SPEED THRILLS BUT KILLS” after the function
trafficLight() is executed.
Code:
sig=input("Enter the light from the trafic signal(RED,YELLOW OR
GREEN):")
if sig=='RED':
print("STOP, your life is precious!")
elif sig=='YELLOW':
print("Please WAIT, untill the light is green.")
elif sig=='GREEN':
print("GO! Thankyou for being patient.")
else:
print("Error")
print("SPEED THRILLS BUT KILLS")
Output:
DIVVYANSH KUDESIAA SESSION 2023-2024 CLASS XII-D
COMPUTER SCIENCE PRACTICAL FILE
Aim 4:
To secure your account, whether it be an email, online bank account or
any other account, it is important that we use authentication. Use your
programming expertise to create a program using user defined function
named login that accepts userid and password as parameters
(login(uid,pwd)) that displays a message “account blocked” in case of
three wrong attempts. The login is successful if the user enters user ID
as “ADMIN” and password as “St0rE@1”. On successful login, display
a message, “Login Successful”
Code:
n1=input("Please enter you login ID:")
n2=input("Please enter the passcode:")
if n1=="ADMIN" and n2=="St0rE@1":
print("Login Successful")
else:
print("Login failed")
Output:
Aim 5:
Write a program to convert a given number into equivalent Roman
number (store its value as a string). You can use following guidelines to
develop solution for it:
From the given number, pick successive digits, using %10 and /10 to
gather the digits from right to left.
The rules for Roman Numerals involve using four pairs of symbols
for ones and fives, tens and fifties, hundreds and five hundreds. An
additional symbol for thousands covers all the relevant bases.
When a number is followed by the same or smaller number, it means
addition. “II” is two 1’s =2. “VI” is 5+1=6.
When one number is followed by a large number, it means
subtraction. “IX” is 1 before 10=9. “IIX” isn’t allowed, this would be
“VIII”. For numbers from 1 to 9, the symbols are “I” and “V”, and the
coding works like this. “I”, “II”, “III”, “IV”, “V”, “VI”, “VII”, “VIII”,
“IX”. The same rules work for numbers from 10 to 99, using “X” and
“L”. For numbers from 100 to 900, using the symbols “C” and “D”. For
numbers from 1000 to 4000, using “M”.
Here are some examples. 1994=MCMXCIV, 1956=MCMLVI,
3888=MMMDCCCLXXXVIII
Code:
while True:
d = {1: 'I', 5: 'V', 10: 'X', 50: 'L', 100: 'C', 500: 'D', 1000: 'M'}
no = input('enter a number: ')
try:
if int(no) >= 4000:
print('number should be less than 4000')
DIVVYANSH KUDESIAA SESSION 2023-2024 CLASS XII-D
COMPUTER SCIENCE PRACTICAL FILE
continue
s = list(no)[::-1]
w = []
i=0
while i < len(s):
q = int(s[i]) * (10 ** i)
if 10 ** i <= q <= 3 * 10 ** i:
w += [d[10 ** i] * int(s[i])]
elif q == (4 * 10 ** i):
w += [d[10 ** i] + d[5 * 10 ** i]]
elif q == (9 * 10 ** i):
w += [d[10 ** i] + d[10 ** (i + 1)]]
elif 5 * 10 ** i <= q <= 8 * 10 ** i:
w += [d[5 * 10 ** i] + d[10 ** i] * (int(s[i]) - 5)]
i += 1
a = (''.join(w[::-1]))
print("ROMAN NUMERAL OF NUMBER {} IS {}".format(no,
a))
print()
except ValueError:
print('invalid input')
print()
Output:
Aim 6:
ROT13 is a weak form of encryption that involves “rotating” each letter
in a word by 13 places. To rotate a letter means to shift it through the
alphabet, wrapping around to the beginning if necessary, so ’A’ shifted
by 3 is ’D’ and ’Z’ shifted by 1 is ’A’. Write a function called
rotate_word that takes a string and an integer as parameters, and that
returns a new string that contains the letters from the original string
“rotated” by the given amount. For example, “cheer” rotated by 7 is
“jolly” and “melon” rotated by -10 is “cubed”. You might want to use
the built-in functions ord, which converts a character to a numeric code,
and chr, which converts numeric codes to characters.
Code:
def rotate_letter(letter,n):
if letter.isupper():
start=ord("A")
elif letter.islower():
start=ord("a")
else:
return letter
c=ord(letter)-start
i=(c+n) % 26+ start
return chr(i)
def rotate_word(word,n):
res=""
DIVVYANSH KUDESIAA SESSION 2023-2024 CLASS XII-D
COMPUTER SCIENCE PRACTICAL FILE
Output:
Aim 7:
This question is based on a Puzzler that was broadcast on the radio
program Car Talk. Give me a word with three consecutive double
letters. I’ll give you a couple of words that almost qualify, but don’t.
For example, the word committee, c-o-m-m-i- t-t-e-e. It would be great
except for the ‘i’ that sneaks in there. Or Mississippi: M-is-s-i-s-s-ip- p-
i. If you could take out those i’s it would work. But there is a word that
has three consecutive pairs of letters and to the best of my knowledge
this may be the only word. Of course there are probably 500 more but I
can only think of one. What is the word? Write a program to find
it/them out of the given string.
Code:
while True:
word = input('Enter a word or enter 0 to Terminate: ')
if word == '0':
print('QUITTING THE PUZZLE CHECKER')
break
if len(word) < 6:
print('The word should be greater than 6 in size')
continue
s=i=0
while i < (len(word) - 1):
if word[i] == word[i + 1]:
DIVVYANSH KUDESIAA SESSION 2023-2024 CLASS XII-D
COMPUTER SCIENCE PRACTICAL FILE
s += 1
i += 2
if s == 3:
print("HURRAY!", word, "IS THE WORD")
break
else:
s=0
i += 1
else:
print("OOPS!", word, "IS NOT THE WORD")
Output:
Aim 8:
Two words are anagrams if you can rearrange the letters from one to
spell the other. Write a function called is_anagram that takes two
strings and returns True if they are anagrams.
Code:
def is_lower(word1, word2):
flag=True
if len(word1) != len(word2):
flag=False
else:
for i in word1.lower():
if i not in word2.lower():
flag=False
break
if flag==True:
print('TRUE, words "{}" and "{}" ARE anagrams'.format(word1,
word2))
else:
print('FALSE, words "{}" and "{}" ARE NOT
anagrams'.format(word1, word2))
word1 = input('enter a word: ')
word2 = input('enter a word: ')
is_lower(word1, word2)
Output:
Aim 9:
Complete the following function that determines if the number of even
and odd values in an integer list is the same. The function would return
true if the list contains 5, 1, 0, 2 (two evens and two odds), but it would
return false for the list containing 5, 1, 0, 2, 11 (too many odds). The
function should return true if the list is empty, since an empty list
contains the same number of evens and odds (0 for both). The function
does not affect the contents of the list.
Code:
def balanced(a):
e=o=0
for i in a:
if i % 2 == 0:
e += 1
else:
o += 1
if e == o:
print('TRUE, the list contains an equal number of odd and even
numbers')
else:
print("FALSE, the list doesn't contain an equal number of odd and
even numbers")
Output:
Aim 10:
Write a program that takes a list of words and creates a dictionary with
frequency (number of occurences) of word as key and list of words for
that frequency as value. For example, if list is given as [‘the’,’of’, ‘an’,
‘is’, ‘an’, ‘the’].Then dictionary should be {2:[‘the’,’an’],1:[‘of’,’is’]}
Code:
l = eval(input("enter a list: "))
if type(l) is list:
d = {}
for i in l:
if l.count(i) not in d:
d[l.count(i)] = [i]
else:
if i not in d[l.count(i)]:
d[l.count(i)].append(i)
else:
pass
print(d)
else:
print('ENTER A LIST')
Output:
Aim 11:
Write a program to find the frequency of values in the given
dictionary. For example, if the dictionary is given as
D={‘P1’:60,’P2’:30,’P3’:50,’P4’:60,’P5’:30,’P6’:10}
Then output should be {10:1,30:2,50:1,60:2}
Code:
D = eval(input("Enter a Dictionary : "))
if type(D) is dict:
d = {}
for i in D:
if D[i] not in d:
d[D[i]] = 1
else:
d[D[i]] += 1
l = list(d.items())
l.sort()
d = dict(l)
print(d)
else:
print('enter a valid dictionary')
Output:
Aim 12:
Write a menu driven program to
to display last three characters of all the lines available in the
text File ‘abcd.txt’
to display the content of a text file ‘abcd.txt’ file in uppercase.
to find and display the count of all the uppercase characters
available in text file ‘abcd.txt’
to count and display total number of vowels available in a text
File ‘abcd.txt’
Code:
def d1():
f = open('abcd.txt', 'r')
s=1
for i in f.readlines():
print('line', s, '=', end='')
if i[-1] == '\n':
print(i[-4:], end='')
else:
print(i[-3:])
s += 1
def d2():
f = open('abcd.txt', 'r')
print(f.read().upper())
def d3():
f = open('abcd.txt', 'r')
c=0
for i in f.read():
if i.isupper():
c += 1
print('no of upper case letters=', c)
def d4():
f = open('abcd.txt', 'r')
c=0
for i in f.read():
DIVVYANSH KUDESIAA SESSION 2023-2024 CLASS XII-D
COMPUTER SCIENCE PRACTICAL FILE
if i in 'AEIOUaeiou':
c += 1
print('no of vowels=', c)
while True:
choice = input('enter your choice:\n1 display last 3 characters of
each line\n2 display contents in uppercase\n3 count no of uppercase\n4
count no of vowels\n0 Exit\n')
if choice == '0':
exit()
elif choice == '1':
d1()
elif choice == '2':
d2()
elif choice == '3':
d3()
elif choice == '4':
d4()
Output:
Aim 13:
Write a menu driven program to
to read the content of a text file ‘abcd.txt’ file and copy the
same content in another file ‘Copy.txt’ file
to read a word from keyboard and find out the frequency of
this word in a text file ‘abcd.txt’
To read a text file ‘abcd.txt’ and copy all those lines that start
with ‘the’ into another text file ‘copy.txt’
to read the text file ‘abcd.txt’ and replace the word ‘This’
with ‘That’ in this file. to read the text file ‘abcd.txt’ and
display the content after removing the word ‘This’ from the
file
Code:
def w():
f = open('abcd.txt','r')
f1 = open('Copy.txt', 'w')
f1.write(f.read())
f1.close()
print('copied')
def r():
f = open('abcd.txt','r')
word = input('enter the word: ')
a = f.read().lower().split()
print(a.count(word.lower()))
def w1():
f = open('abcd.txt','r')
f1 = open('Copy.txt', 'w')
for i in f.readlines():
if i.strip().lower().startswith('the'):
f1.write(i)
f1.close()
def replace():
f = open('abcd.txt', 'r+')
a = f.readlines()
for i in range(len(a)):
DIVVYANSH KUDESIAA SESSION 2023-2024 CLASS XII-D
COMPUTER SCIENCE PRACTICAL FILE
if 'this' in a[i].lower():
l1 = a[i].split()
for j in range(len(l1)):
if l1[j].lower() == 'this':
l = list(l1[j])
if l[2].isupper():
l[2] = 'A'
else:
l[2] = 'a'
if l[3].isupper():
l[3] = 'T'
else:
l[3] = 't'
l1[j] = ''.join(l)
a[i] = ' '.join(l1) + '\n'
f.seek(0)
f.writelines(a)
f.close()
print('replaced')
def d():
f = open('abcd.txt', 'r+')
a = f.readlines()
for i in range(len(a)):
if 'this' in a[i].lower():
l1 = a[i].split()
l1 = [j for j in l1 if j.lower() != 'this']
a[i] = ' '.join(l1) + '\n'
while '\n' in a:
a.remove('\n')
f.seek(0)
f.writelines(a)
f.close()
while True:
c = input('enter your choice:\n1 copy to file Copy.txt\n2 find
frequency of a word\n3 copy lines starting with "the"\n4 Convert
"this" to "that"\n5 delete "this" from file\nenter: ')
DIVVYANSH KUDESIAA SESSION 2023-2024 CLASS XII-D
COMPUTER SCIENCE PRACTICAL FILE
if c == '1':
w()
elif c == '2':
r()
elif c == '3':
w1()
elif c == '4':
replace()
elif c == '5':
d()
Output:
Aim 14:
DIVVYANSH KUDESIAA SESSION 2023-2024 CLASS XII-D
COMPUTER SCIENCE PRACTICAL FILE
Create the tables and Write the SQL queries and capture the screens
of executed queries for the following:
Table: STOCK
NO ITEMCODE QUANTITY DATEOFPURCHASE WARRANTY
1 C201 9 21-May-2005 2
2 P1010 3 21-May-2005 4
3 S203 1 29-Sep-2004 3
4 C201 2 13-Jun-2005 1
5 P1010 1 31-Oct-2004 2
6 U34 5 21-May-2005 1
7 P1010 2 11-Jan-2006 2
Table: ITEM
ITEMCODE ITEMNAME PRICE
C201 Computer 39000
P1010 Printer 11000
S203 Scanner 4500
WC05 Camera 1200
U34 UPS 1900
i) To select item purchased after 31-Jan-2005.
ii) To list the item name in descending order of date of
purchase where quantity is more than three
iii) To count number of Items (total quantity) whose cost is more
than 10000.
iv) To insert a new record in the table STOCK with following
data:
8 C201 5 13-Jun-2005 1
v) To find minimum distinct item type (itemcode) from STOCK.
vi) To generate a report on each item code with the item name
and total value (quantity * Price).
vii) To find average cost of all items with more than 2 items.
viii) To find average cost of items with date of purchase is before
1-Jan-2005.
ix) To reduce the cost of all UPS by 100.
x) To delete the table STOCK.
Aim 15:
DIVVYANSH KUDESIAA SESSION 2023-2024 CLASS XII-D
COMPUTER SCIENCE PRACTICAL FILE
Create the table and write the SQL queries and capture the screens
of executed queries for the following:
1. To show all information about the Sofa’s from the interiors table.
2. To list the item name which are priced more than 10000 from the
interiors table. I
3. To display item name and date of stock of those items, in
which the discount percentage is more than 15.
4. To list item name and type of items, in which data of stock is
before 22- Jan-2002 in descending order of item name.
5. To count the number of items of each type.
6. To insert new row in interiors table with following data:
11 White wood Double bed 23-Feb-200620000
20
7. To count distinct types from interiors table.
8. To find average discount from interiors for each type of interiors.
9. To calculate sum of price from interiors where data of stock is
before 12- Feb-2002
10. To increase price of all Office table by 3000 from interiors
table.
Aim 16:
Consider the following tables product and client.
Code:
import mysql.connector as mycon
if ('store',) not in l:
cur.execute('create database STORE')
cur.execute('use STORE')
cur.execute('create table PRODUCT (P_id varchar(10) primary
key,Productname varchar(30),Manufacturer varchar(30),price int(10))')
cur.execute('create table Client (C_id int(10) primary
key,Clientname varchar(30),City varchar(30),P_id varchar(10))')
con.commit()
else:
cur.execute('use STORE')
def inser
t():
n = 'NONE'
while n.upper() not in ('PRODUCT', 'CLIENT'):
n = input('Enter table: PRODUCT/CLIENT')
while True:
if n.upper() == 'PRODUCT':
i = input('enter P_id:')
nm = input('enter PRODUCT name:')
m = input('enter MANUFACTURER:')
p = int(input('enter PRICE:'))
DIVVYANSH KUDESIAA SESSION 2023-2024 CLASS XII-D
COMPUTER SCIENCE PRACTICAL FILE
def desc():
cur.execute('select Clientname,Productname from CLIENT
C,PRODUCT P where P.P_Id=C.P_Id order by Clientname desc')
d = cur.fetchall()
print('Client_Name \t- Product_NAME')
for i in d:
print(i[0], '\t-', i[1])
def upd():
cur.execute('Update Product set Price=Price+0.05*Price')
cur.execute('Select * from Product')
d = cur.fetchall()
print('PID\tPNAME\t\tMANUFACTURER\tPRICE')
for i in d:
print(i[0],'\t',i[1],'\t',i[2],'\t\t',i[3])
def delete():
cur.execute('delete from Client where city="Bangalore"')
cur.execute('Select * from Client')
d = cur.fetchall()
print('CID\tClientNAME\tCITY\tPID')
for i in d:
print(i[0], '\t', i[1], '\t', i[2],
DIVVYANSH KUDESIAA
' ', i[3])
SESSION 2023-2024 CLASS XII-D
COMPUTER SCIENCE PRACTICAL FILE
def count():
cur.execute('select count(*),city from Client group by City')
d = cur.fetchall()
print('COUNT(*)\tCITY')
for i in d:
print(i[0], '\t\t', i[1])
def alter():
cur.execute('Alter table Client Modify City Varchar(50)')
print(‘updated’)
cur.execute('use STORE')
while True:
a = input('choose your option:\n1 to INSERT\n2 to DISPLAY
CLIENTNAME AND PRODUCT PURCHASED\n3 to increase each
product price by 5%\n4 to DELETE records of people from Bangalore\
n5 to DISPLAY NUMBER OF CLIENTS FROM EACH CITY\n6 to
increase the width of column city to 50\n0 to EXIT\n')
print()
if a == '0':
exit()
elif a == '1':
insert()
elif a == '2':
desc()
elif a == '3':
upd()
elif a == '4':
delete()
elif a == '5':
count()
elif a == '6':
alter()
print()
con.commit()
Output:
Aim 17:
Following is the structure of each record in a data file named
“PRODUCT.DAT”.
{"prod_code":value, "prod_desc":value, "stock":value}
The values for prod_code and prod_desc are strings, and the value for
stock is an integer.
Code:
import pickle
def main_menu():
while True:
choice = input('Enter your choice:\n0 to exit\n1 to add records\n2
to display records\n3 to update stock\n')
if choice == '0':
exit()
elif choice == '1':
add_record()
elif choice == '2':
display_records()
elif choice == '3':
update_stock()
else:
print('Invalid input')
DIVVYANSH KUDESIAA SESSION 2023-2024 CLASS XII-D
COMPUTER SCIENCE PRACTICAL FILE
print()
def add_record():
file = open('PRODUCT.DAT', 'ab')
while True:
record = {}
record['code'] = input('Enter product code: ')
record['description'] = input('Enter product description: ')
record['stock'] = int(input('Enter stock quantity: '))
pickle.dump(record, file)
continue_input = input('Do you want to add more records?
(yes/no): ')
if continue_input.lower() != 'yes':
break
file.close()
def display_records():
file = open('PRODUCT.DAT', 'rb')
file.seek(0)
while True:
try:
record = pickle.load(file)
print(record['code'], '\t', record['description'], '\t',
record['stock'])
except EOFError:
file.close()
break
def update_stock():
file = open('PRODUCT.DAT', 'rb')
file.seek(0)
code = input('Enter product code to update stock: ')
updated_records = []
while True:
try:
record = pickle.load(file)
if record['code'] == code:
new_stock = int(input('Enter
DIVVYANSH KUDESIAA
new stock quantity: '))CLASS XII-D
SESSION 2023-2024
COMPUTER SCIENCE PRACTICAL FILE
record['stock'] = new_stock
updated_records.append(record)
except EOFError:
file.close()
break
file = open('PRODUCT.DAT', 'wb')
for r in updated_records:
pickle.dump(r, file)
file.close()
main_menu()
Output:
Aim 18:
Given a binary file “STUQ2.DAT”, containing records of the
following type:
[S_Admno, S_Name, Percentage]
Where these three values are:
S_Admno – Admission Number of student (string)
S_Name – Name of student (string)
Percentage – Marks percentage of student (float)
Write a menu driven program using functions
to enter records
to display all records
to read contents of the file “STUDENT.DAT” and display the details
of those students whose percentage is above 75
DIVVYANSH KUDESIAA SESSION 2023-2024 CLASS XII-D
COMPUTER SCIENCE PRACTICAL FILE
Code:
import pickle
def add_student_record():
file = open('STUDENT.DAT', 'ab')
while True:
admission_number = input('Enter admission number: ')
student_name = input('Enter name: ')
percentage = float(input('Enter percentage: '))
pickle.dump([admission_number, student_name, percentage],
file)
continue_input = input('Do you want to enter more records?
(yes/no): ')
if continue_input.lower() != 'yes':
break
file.close()
def display_student_records():
file = open('STUDENT.DAT', 'rb')
file.seek(0)
while True:
try:
record = pickle.load(file)
print(record[0], '\t', record[1], '\t', record[2])
except EOFError:
file.close()
break
def display_students_above_75_percent():
file = open('STUDENT.DAT', 'rb')
file.seek(0)
students_above_75_percent = []
while True:
try:
record = pickle.load(file)
file.close()
break
if not students_above_75_percent:
print('NO RECORDS FOUND')
else:
for student in students_above_75_percent:
print(student[0], '\t', student[1], '\t', student[2])
while True:
choice = input('Enter your choice:\n0 to exit\n1 to enter records\n2
to display records\n3 to display records with percentage > 75%\n')
print()
if choice == '0':
exit()
elif choice == '1':
add_student_record()
elif choice == '2':
display_student_records()
elif choice == '3':
display_students_above_75_percent()
Output:
Aim 19:
Assuming the tuple Vehicle as follows:
(vehicletype, no_of_wheels)
DIVVYANSH KUDESIAA SESSION 2023-2024 CLASS XII-D
COMPUTER SCIENCE PRACTICAL FILE
break
print('Number of Records:', count)
file.close()
while True:
choice = input('Enter your choice:\n0 to exit\n1 to enter records\n2 to
display records\n3 to count the number of records\n')
print()
if choice == '0':
exit()
elif choice == '1':
add_vehicle_record()
elif choice == '2':
display_vehicle_records()
elif choice == '3':
count_vehicle_records()
else:
pass
Output:
Aim 20:
Create a file PRODUCT.CSV. Sample data of the file is as follows:
reader = csv.reader(file)
writer = csv.writer(file_pro1, delimiter=',')
for row in reader:
try:
if int(row[3]) > 150:
writer.writerow(row)
except ValueError:
writer.writerow(row)
print("records inserted")
def calculate_cost_sum():
with open('PRODUCT.csv', 'r') as file:
reader = csv.reader(file)
total_cost = 0
for row in reader:
try:
total_cost += int(row[2])
except ValueError:
pass
print('Sum of the cost of all products:', total_cost)
def find_record_with_max_cost():
with open('PRODUCT.csv', 'r') as file:
reader = csv.reader(file)
header = next(reader)
max_cost = 0
max_cost_record = None
for row in reader:
try:
cost = int(row[2])
if cost > max_cost:
max_cost = cost
max_cost_record = row
except ValueError:
pass
if max_cost_record:
print('Record with max cost:')
print(header[0], '\t', header[1], '\t', header[2], '\t', header[3])
print(max_cost_record[0], '\t', max_cost_record[1], '\t',
max_cost_record[2], '\t', max_cost_record[3])
else:
DIVVYANSH KUDESIAA SESSION 2023-2024 CLASS XII-D
COMPUTER SCIENCE PRACTICAL FILE
Output:
Aim 21:
Create a file Tour.csv having headings as follows
TID,DESTINATION,DAYS,FARE. Sample data of file is as follows:
records_within_range.append(row)
except ValueError:
pass
if not records_within_range:
print('No records with fare between 500 and 750.')
else:
print('TID\tDESTINATION\tDAYS\tFARE')
for row in records_within_range:
print(row[0], '\t', row[1], '\t', row[2], '\t', row[3])
while True:
choice = input('Enter your choice:\n0 to exit\n1 to enter initial
records\n2 to display records\n3 to display records with fare between
500 and 750\n')
print()
if choice == '0':
exit()
elif choice == '1':
insert_initial_records()
elif choice == '2':
display_records()
elif choice == '3':
display_records_within_fare_range()
Output:
DIVVYANSH KUDESIAA SESSION 2023-2024 CLASS XII-D
COMPUTER SCIENCE PRACTICAL FILE
Aim 22:
Write a function in python, MakePush(Package) and
MakePop(Package) to add a new Package and delete a Package from
DIVVYANSH KUDESIAA SESSION 2023-2024 CLASS XII-D
COMPUTER SCIENCE PRACTICAL FILE
Code:
def MakePush(Package):
n = input('enter Package info:')
Package += [n]
def MakePop(Package):
if Package == []:
print('Empty stack, no value to delete')
else:
print('Deleted item:', Package.pop())
Package = []
while True:
c = input('press:\n0.EXIT \n1.ADD \n2.REMOVE\n')
if c == '0':
exit()
elif c == '1':
MakePush(Package)
elif c == '2':
MakePop(Package)
Output:
Aim 22:
Write the functions in Python push (stk, item ) and pop(stk) to check
whether the stack is empty, to add a new item, to delete an item and
DIVVYANSH KUDESIAA SESSION 2023-2024 CLASS XII-D
COMPUTER SCIENCE PRACTICAL FILE
Code:
def push(stk, item):
stk += [item]
def pop(stk):
if stk == []:
print('Stack is empty, nothing to delete')
else:
print('Deleted element:', stk.pop())
def emptystack(stk):
if stk == []:
print('Oops! The stack is empty')
else:
print('Stack is not empty')
def display(stk):
for i in stk[::-1]:
print(i)
stk = []
while True:
choice = input('0.EXIT\n1.ADD item to stack\n2.DELETE item from
stack\n3.FIND whether stack is empty or not\n4.DISPLAY STACK\n')
if choice == '0':
exit()
elif choice == '1':
item = input('Enter element to insert:')
push(stk, item)
elif choice == '2':
pop(stk)
elif choice == '3':
emptystack(stk)
elif choice == '4':
display(stk)
Output:
Aim 23:
Write the functions in Python push (stk, item ) and pop(stk) to check
DIVVYANSH KUDESIAA SESSION 2023-2024 CLASS XII-D
COMPUTER SCIENCE PRACTICAL FILE
whether the stack is empty, to add a new item, to delete an item and
display the stack respectively. Implement the menu driven program.
Code:
def push(stk, item):
stk += [item]
def pop(stk):
if stk == []:
print('Stack is empty, nothing to delete')
else:
print('Deleted element:', stk.pop())
def emptystack(stk):
if stk == []:
print('Oops! The stack is empty')
else:
print('Stack is not empty')
def display(stk):
for i in stk[::-1]:
print(i)
stk = []
while True:
choice = input('0.EXIT\n1.ADD item to stack\n2.DELETE item from
stack\n3.FIND whether stack is empty or not\n4.DISPLAY STACK\n')
if choice == '0':
exit()
elif choice == '1':
item = input('Enter element to insert:')
push(stk, item)
elif choice == '2':
pop(stk)
elif choice == '3':
emptystack(stk)
elif choice == '4':
display(stk)
DIVVYANSH KUDESIAA SESSION 2023-2024 CLASS XII-D
COMPUTER SCIENCE PRACTICAL FILE
Output:
Aim 24:
Write a program to perform push operation on a stack to push all prime
numbers from a list entered by a user.
DIVVYANSH KUDESIAA SESSION 2023-2024 CLASS XII-D
COMPUTER SCIENCE PRACTICAL FILE
Code:
while True:
choice = input('Enter a number you want to insert or press s to stop
entering: ')
try:
num = int(choice)
l.append(num)
except ValueError:
if choice.lower() == 's':
break
else:
print('Invalid input')
for i in l[::-1]:
j=2
r=0
if i == 1 or i == 0:
r=1
else:
while j <= math.sqrt(i):
if i % j == 0:
r=1
break
j += 1
if r == 0:
stk.append(i)
print(stk)
Output:
=========================================================================
=================
FILE END
=========================================================================
=================