Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Computer Science Practical File

Uploaded by

hypnopredator
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Computer Science Practical File

Uploaded by

hypnopredator
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 78

Computer science practical file

Computer Science
Practical File
Name:-Aditya Singh
Class:-XII-C
Roll number:- 04

Link :-
https://drive.google.com/drive/folders/1a3mfAUormaRatpPkl1Qh9mKOfQEL9
ux8?usp=drive_link

Aditya Singh Class XII-C Page: 1


Computer science practical file

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:-
def playgame():
Dragons=0
Wizards=0
draw=0
cards=dict()
shapes=['Diamonds','Clubs','Hearts','Spades']
values=['Ace','2','3','4','5','6','7','8','9','10','J','Q','K']
while draw<5:
shape=input('Enter the shape:\t')
if shape.capitalize() not in shapes:
print('Enter a valid shape.')
continue
value=input('Enter the value:\t')
if value.capitalize() not in values:
print('Enter a valid value.')
continue
cards[draw]=(shape.capitalize(),value.capitalize())
draw+=1
print(cards)

Aditya Singh Class XII-C Page: 2


Computer science practical file

for i in range(len(cards)):
shape,value=cards[i]
if shape in ['Diamonds', 'Clubs']:
Dragons+= 1
elif shape == 'Hearts':
if value.isdigit() or value=='Ace':
Wizards+= 1
else:
Dragons+= 1
else:
Wizards += 1
print('Wizards score:',Wizards)
print('Dragons score:',Dragons)

if Wizards==Dragons:
print('Tie!')
elif Wizards>Dragons:
print('Wizards win!')
else:
print('Dragons win!')

playgame()

Aditya Singh Class XII-C Page: 3


Computer science practical file

Aditya Singh Class XII-C Page: 4


Computer science practical file

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:-
integers=[]
for i in range(5):
num=int(input('Enter an integer: '))
integers.append(num)
largest= max(integers)
smallest= min(integers)
print("Maximum value:", largest)
print("Minimum value:", smallest)

Aditya Singh Class XII-C Page: 5


Computer science practical file

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:-
def trafficLight():
signal = input("Enter the colour of the traffic light: \t")
if (signal not in ("RED","YELLOW","GREEN")):
print("Please enter a valid Traffic Light colour in CAPITALS")
else:
value = light(signal)
if (value == 0):
print("STOP, Your Life is Precious.")
elif (value == 1):
print ("PLEASE GO SLOW.")
else:
print("GO!,Thank you for being patient.")
def light(colour):

Aditya Singh Class XII-C Page: 6


Computer science practical file

if (colour == "RED"):
return(0);
elif (colour == "YELLOW"):
return (1)
else:
return(2)
trafficLight()
print("SPEED THRILLS BUT KILLS")

Aditya Singh Class XII-C Page: 7


Computer science practical file

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:-
def login(uid, pwd):
correct_uid = "ADMIN"
correct_pwd = "St0rE@1"
max_attempts = 3
attempts = 0
while attempts < max_attempts:
if uid == correct_uid and pwd == correct_pwd:
print("Login Successful")
return
else:
attempts += 1
if attempts < max_attempts:
print("Incorrect user ID or password. Please try again.")
uid = input("Enter user ID: ")
pwd = input("Enter password: ")
print("Account blocked")
user_id = input("Enter user ID: ")
password = input("Enter password: ")
login(user_id, password)

Aditya Singh Class XII-C Page: 8


Computer science practical file

Aditya Singh Class XII-C Page: 9


Computer science practical file

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
Code:-
def int_to_roman(num):

val = [1000, 900, 500, 400, 100, 90, 50, 40,10, 9, 5, 4,1]
syb = ["M", "CM", "D", "CD","C", "XC", "L", "XL","X", "IX", "V",
"IV","I"]
roman_num = ""
i=0
while num > 0:
for _ in range(num // val[i]):
roman_num += syb[i]
num -= val[i]
i += 1
return roman_num
number = 1987
roman_numeral = int_to_roman(number)
print("Roman numeral of", number, "is:", roman_numeral)

Aditya Singh Class XII-C Page: 10


Computer science practical file

6) 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
Code:-
def rotate_word(word, shift):
def rotate_char(c, shift):
if 'a' <= c <= 'z':
return chr((ord(c) - ord('a') + shift) % 26 + ord('a'))
elif 'A' <= c <= 'Z':
return chr((ord(c) - ord('A') + shift) % 26 + ord('A'))
else:
return c

return ''.join(rotate_char(c, shift) for c in word)

# DC
print(rotate_word("cheer", 7))
print(rotate_word("melon", -10))

Aditya Singh Class XII-C Page: 11


Computer science practical file

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-te-e. It would be great except for the ‘i’ that sneaks in
there. Or Mississippi: M-i-s-s-is-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:-
def has_three_consecutive_double_letters(word):
count = 0
i=0
while i < len(word) - 1:
if word[i] == word[i + 1]:
count += 1
i += 2
if count == 3:
return True
else:
count = 0
i += 1
return False

def find_words_with_consecutive_double_letters(words):
result = []
for word in words:
if has_three_consecutive_double_letters(word):
result.append(word)
return result

Aditya Singh Class XII-C Page: 12


Computer science practical file

words = ["committee", "Mississippi", "bookkeeper", "balloon", "bookkeeping"]

result = find_words_with_consecutive_double_letters(words)
print("Words with three consecutive double letters:", result)

Aditya Singh Class XII-C Page: 13


Computer science practical file

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_anagram(str1, str2):
clean_str1 = ''.join(sorted(str1.lower()))
clean_str2 = ''.join(sorted(str2.lower()))
return clean_str1 == clean_str2
print(is_anagram("listen", "silent"))
print(is_anagram("hello", "world"))

Aditya Singh Class XII-C Page: 14


Computer science practical file

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):
count_o=0
count_e=0
for i in a:
if i%2==0:
count_e+=1
else:
count_o+=1
if count_e==count_o:
print('True')
else:
print('False')
#DC
a=[5,1,0,2]
balanced(a)
a=[5,1,2,3,4,5]
balanced(a)
a=[]
balanced(a)

Aditya Singh Class XII-C Page: 15


Computer science practical file

10) Write a program that takes a list of words and creates a dictionary with
frequency (number of occurrences) 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:-
from collections import defaultdict

def create_frequency_dict(words):
word_count = defaultdict(int)
for word in words:
word_count[word] += 1

frequency_dict = defaultdict(list)
for word, count in word_count.items():
frequency_dict[count].append(word)

return dict(frequency_dict)

words = ['the', 'of', 'an', 'is', 'an', 'the']

frequency_dict = create_frequency_dict(words)
print(frequency_dict)

Aditya Singh Class XII-C Page: 16


Computer science practical file

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:-
def valuefrequency(D):
frequency=dict()
for value in sorted(D.values()):
if value not in frequency:
frequency[value]=list(D.values()).count(value)
print(frequency)
#Driver Code
D={'P1':60,'P2':30,'P3':50,'P4':60,'P5':30,'P6':10}
valuefrequency(D)

Aditya Singh Class XII-C Page: 17


Computer science practical file

SQL Questions
12)
1. Create the tables and insert tuples in them.
2. Display the details of all the employees.

Aditya Singh Class XII-C Page: 18


Computer science practical file

3. Display the Salary, Zone, and Grade of all the employees

Aditya Singh Class XII-C Page: 19


Computer science practical file

4. Display the records of all the employees along with their annual salaries. The
Salary column of the table contains monthly salaries of the employees.

5. This is same as query for requirement number 4.

Aditya Singh Class XII-C Page: 20


Computer science practical file

6. Display the details of all the employees who are below 30 years of age.

7. Display the names of all the employees working in North zone.

8. Display the salaries of all the employees of department 10

9. Display the details of all the employees whose Grade is NULL.

Aditya Singh Class XII-C Page: 21


Computer science practical file

10. Display the details of all the employees whose Grade is not NULL.

11. Display the names of various zones from the table Employee. A zone name
should appear only once

12. Display the various department numbers from the table Employee. A
department number should be displayed only once

13. Display the details of all the employees of department 10 who are above 30
years of age.

Aditya Singh Class XII-C Page: 22


Computer science practical file

14. Display the details of all the employees who are getting a salary of more
than 35000 in the department 30.

15. Display the names and salaries of all the employees who are working neither
in West zone nor in Centre zone.

16. Display the names of all the employees who are working in department 20
or 30.

17. Display the details of all the employees whose salary is between 32000 and
38000

Aditya Singh Class XII-C Page: 23


Computer science practical file

18. Display the details of all the employees whose grade is between ‘A’ and ‘C’

19. Display the names of all the employees who are working in department 20
or 30

20. Display the names and salaries of all the employees who are working
neither in West zone nor in Centre zone.

Aditya Singh Class XII-C Page: 24


Computer science practical file

21. Display the details of all the employees whose salary is between 32000 and
38000.

22. Display the details of all the employees whose grade is between ‘A’ and ‘C’

23. Display the name, salary, and age of all the employees whose names start
with ‘M’.

Aditya Singh Class XII-C Page: 25


Computer science practical file

24. Display the name, salary, and age of all the employees whose names end
with ‘a’.

25. Display the name, salary, and age of all the employees whose names
contain ‘a’

26. Display the name, salary, and age of all the employees whose names do not
contain ‘a’

27. Display the details of all the employees whose names contain ‘a’ as the
second character

Aditya Singh Class XII-C Page: 26


Computer science practical file

28. Display the sum and average of the salaries of all the employees.

29. Display the highest and the lowest salaries being paid in department 10.

30. Display the number of employees working in department 10.

31. Display the details of all the employees in the ascending order of their
salaries.

Aditya Singh Class XII-C Page: 27


Computer science practical file

32. Display the details of all the employees in the descending order of their
names.

33. Display the details of all the employees in the ascending order of their
grades and within grades in the descending order of their salaries.

34. Display the total number of employees in each department.

Aditya Singh Class XII-C Page: 28


Computer science practical file

35. Display the highest salary, lowest salary, and average salary of each zone.

36. Display the average age of employees in each department only for those
departments in which average age is more than 30.

37. Put the grade B for all those whose grade is NULL.

Aditya Singh Class XII-C Page: 29


Computer science practical file

38. Increase the salary of all the employees above 30 years of age by 10%.

39. Delete the records of all the employees whose grade is C and salary is
below 30000.

Aditya Singh Class XII-C Page: 30


Computer science practical file

40. Delete the records of all the employees of department 10 who are above 40
years of age.

41. Add another column HireDate of type Date in the Employee table.

Aditya Singh Class XII-C Page: 31


Computer science practical file

Aditya Singh Class XII-C Page: 32


Computer science practical file

13) Create the tables and Write the SQL queries

Aditya Singh Class XII-C Page: 33


Computer science practical file

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

Aditya Singh Class XII-C Page: 34


Computer science practical file

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 the following data:

v) To find the 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)

Aditya Singh Class XII-C Page: 35


Computer science practical file

vii) To find the average cost of all items with more than 2 items:

viii) To find the average cost of items where the date of purchase is before 1-
Jan-2005

ix) To reduce the cost of all UPS by 100

Aditya Singh Class XII-C Page: 36


Computer science practical file

x) To delete the table STOCK

Aditya Singh Class XII-C Page: 37


Computer science practical file

14) Create the table and write the SQL queries and capture the screens of
executed queries:

i) To show all information about the Sofas from the INTERIORS table

ii)To list the item names that are priced more than 10000 from the INTERIORS
table

Aditya Singh Class XII-C Page: 38


Computer science practical file

iii) To display item names and dates of stock of those items in which the
discount percentage is more than 15:

iv) To list item names and types of items, where the date of stock is before
'2002-01-22', in descending order of item name

v) To count the number of items of each type

vi) To insert a new row in the INTERIORS table with the following data

Aditya Singh Class XII-C Page: 39


Computer science practical file

vii) To count distinct types from interiors table.

viii) To find the average discount from INTERIORS for each type of interiors

ix) To calculate the sum of price from INTERIORS where the date of stock is
before '2002-02-12'

x) To increase the price of all Office tables by 3000 in the INTERIORS table

Aditya Singh Class XII-C Page: 40


Computer science practical file

Aditya Singh Class XII-C Page: 41


Computer science practical file

15) 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 display_last_three_characters():
with open('abcd.txt', 'r') as file:
lines = file.readlines()
for line in lines:
print(line.strip()[-3:]) # Display last three characters

def display_content_uppercase():
with open('abcd.txt', 'r') as file:
content = file.read()
print(content.upper()) # Display content in uppercase

def count_uppercase_characters():
with open('abcd.txt', 'r') as file:
content = file.read()
count = sum(1 for char in content if char.isupper())
print(f"Total uppercase characters: {count}")

def count_vowels():
vowels = 'aeiouAEIOU'
with open('abcd.txt', 'r') as file:

Aditya Singh Class XII-C Page: 42


Computer science practical file

content = file.read()
count = sum(1 for char in content if char in vowels)
print(f"Total vowels: {count}")

def main():
while True:
print("\nMenu:")
print("1. Display last three characters of all lines")
print("2. Display content in uppercase")
print("3. Count uppercase characters")
print("4. Count vowels")
print("5. Exit")

choice = input("Enter your choice (1-5): ")

if choice == '1':
display_last_three_characters()
elif choice == '2':
display_content_uppercase()
elif choice == '3':
count_uppercase_characters()
elif choice == '4':
count_vowels()
elif choice == '5':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

Aditya Singh Class XII-C Page: 43


Computer science practical file

if __name__ == "__main__":
main()

Aditya Singh Class XII-C Page: 44


Computer science practical file

Aditya Singh Class XII-C Page: 45


Computer science practical file

16)
Develop a complete menu driven application using python mySQL connectivity
based on following parameters. Create functions wherever required. Capture
screenshots of reflected outputs along with code.
i) Database name:STORE
ii) Table names: PRODUCT and CLIENT (as shown above)
iii) Primary keys: pid, cid
iv) Write suitable code in python to create database, tables and to insert the
records.
v) Create a function to display the client name and the product purchased by
the client in descending order of client names
vi) Create a function to increase the price of all the products by 5%. Now
display all the records of product table.
vii) Create a function to remove the records of clients who are from Bangalore.
Now display all the records of Client table.
viii) Create a function to display number of clients from each city.
ix) Create a function to increase the width of column city to 50.
Code:-

import mysql.connector as mycon


passwd=input('Enter password: ')
con=mycon.connect(host='localhost',user='root',password=passwd)

i) def createdb():
cur.execute('show databases')
db=cur.fetchall()
if ('store',) not in db:
query='create database STORE'
cur.execute(query)

cur.execute('commit')
print('Database STORE created.')
else:
print('Database already exists.')
cur.execute('use STORE')

Aditya Singh Class XII-C Page: 46


Computer science practical file

ii, iii)
def createtbs():
cur.execute('use STORE')
cur.execute('show tables')
tb=cur.fetchall()
if ('product',) not in tb:
query='create table PRODUCT(\
P_ID varchar(4) primary key,\
PRODUCTNAME varchar(20),\
MANUFACTURER varchar(3),\
PRICE int)'
print('PRODUCT table created.')
cur.execute(query)
cur.execute('commit')
else:
print('PRODUCT table already exists.')
if ('client',) not in tb:
query='create table CLIENT(\
C_ID int primary key,\
CLIENTNAME varchar(20),\
City varchar(20),\
P_ID varchar(4))'
print('CLIENT table created.')
cur.execute(query)
cur.execute('commit')
else:
print('CLIENT table already exists.')

iv) def insert():


cur.execute('use STORE')
query="insert into PRODUCT values(\
'TPO1','TALCOM POWDER','LAK',40),\
('FW05','FACEWASH','ABC',45),\
('BS01','BATH SOAP','ABC',55),\
('SH06','SHAMPOO','XYZ',120),\
('FW12','FACE WASH', 'XYZ',95)"
try:
cur.execute(query)
except:
pass

Aditya Singh Class XII-C Page: 47


Computer science practical file

query="insert into CLIENT values(\


01,'COSMETIC SHOP','Delhi','FW05'),\
(06,'TOTAL HEALTH','Mumbai','BS01'),\
(12,'LIVE LIFE','Delhi','SH06'),\
(15,'PRETTY WOMAN','Delhi','FW12'),\
(16,'DREAMS', 'Bangalore','TP01')"
try:
cur.execute(query)
except:
pass
print('Data has been entered')
print()
print('PRODUCT TABLE')
cur.execute('select * from PRODUCT')
data=cur.fetchall()
for i in data:
for j in i:
if j=='SHAMPOO':
print(j,end='\t\t\t')
else:
print(j,end='\t\t')
print()
print()
print('CLIENT TABLE')
cur.execute('select * from CLIENT')
data=cur.fetchall()
for i in data:
for j in i:
if j=='DREAMS':
print(j,end='\t\t\t')
elif j=='Bangalore':
print(j,end='\t')
else:
print(j,end='\t\t')
print()
print()
cur.execute('commit')
v) def display():
cur.execute('use STORE')

Aditya Singh Class XII-C Page: 48


Computer science practical file

query='select CLIENT.CLIENTNAME, PRODUCT.PRODUCTNAME from


CLIENT,\
PRODUCT where CLIENT.P_ID=PRODUCT.P_ID order by CLIENTNAME
desc'
cur.execute(query)
data=cur.fetchall()
print()
print('CLIENTNAME\t\tPRODUCTNAME\t\t')
for i in data:
for j in i:
print(j,end='\t\t')
print()
print()
vi)def increase():
cur.execute('use STORE')
query='UPDATE PRODUCT SET PRICE=1.05*PRICE'
cur.execute(query)
cur.execute('commit')
print()
print('PRODUCT TABLE')
cur.execute('select * from PRODUCT')
data=cur.fetchall()
for i in data:
for j in i:
if j=='SHAMPOO':
print(j,end='\t\t')
else:
print(j,end='\t')
print()
print()
vii)def rembgl():
cur.execute('use STORE')
query='DELETE from CLIENT where City="Bangalore"'
cur.execute(query)
cur.execute('commit')
print()
print('CLIENT TABLE')
cur.execute('select * from CLIENT')
data=cur.fetchall()
for i in data:

Aditya Singh Class XII-C Page: 49


Computer science practical file

for j in i:
if j=='SHAMPOO':
print(j,end='\t\t')
else:
print(j,end='\t')
print()
print()
viii)def discity():
cur.execute('use STORE')
query='SELECT City,count(*) from CLIENT group by City'
cur.execute(query)
data=cur.fetchall()
for i in data:
for j in i:
print(j,end='\t')
print()
ix)def width():
cur.execute('use STORE')
query='ALTER TABLE CLIENT MODIFY COLUMN City varchar(50)'
cur.execute(query)
cur.execute('commit')
print('Width of City has been extended to 50')

if con.is_connected():
cur=con.cursor()
while True:
choice=int(input('Enter : \n1) To create database \'STORE\' \
\n2) To create tables \'PRODUCT\' and \'CLIENT\' \
\n3) To insert entries in the tables\
\n4) To display client name and product purchased by them\
\n5) To increase price of all products by 5%\
\n6) To remove records of clients from Bangalore\
\n7) To display number of clients from each city\
\n8) To increase the width of column city to 50\
\n0) To exit the program\n'))

if choice==1:
createdb()
elif choice==2:
createtbs()

Aditya Singh Class XII-C Page: 50


Computer science practical file

elif choice==3:
insert()
elif choice==4:
display()
elif choice==5:
increase()
elif choice==6:
rembgl()
elif choice==7:
discity()
elif choice==8:
width()
elif choice==0:
print('Program terminated.')
break
else:
print('Choose valid option')
continue

Aditya Singh Class XII-C Page: 51


Computer science practical file

Aditya Singh Class XII-C Page: 52


Computer science practical file

Aditya Singh Class XII-C Page: 53


Computer science practical file

Aditya Singh Class XII-C Page: 54


Computer science practical file

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. Write a menu driven program using functions
● to enter records
● to display all records
● to update the file with a new value of stock. The stock and the product_code,
whose stock is to be updated, are to be input during the execution of the
function.

Code:-

import pickle
def enter_data():
f=open('PRODUCT.DAT','ab')
d={}
vsl1=input('enter product code')
vsl2=input('enter product desc')
vsl3=input('stock')
d['prod_code']=vsl1
d['prod_desc']=vsl2
d['stock']=vsl3
pickle.dump(d,f)
f.close()
print('record inserted')
def display_rec():
f=open('PRODUCT.DAT','rb')
while True:
try:
obj=pickle.load(f)
print(obj)
except EOFError:
f.close()
break
def update():
f=open('PRODUCT.DAT','rb')
l=[]
while True:
try:
obj=pickle.load(f)

Aditya Singh Class XII-C Page: 55


Computer science practical file

l.append(obj)
except EOFError:
f.close()
break
f=open('PRODUCT.DAT','wb')
prod_code=input('Enter the product whose stock is to be modified')
stock=input('enter the new stock')
for i in l:
if i['prod_code']==prod_code:
i['stock']=stock
for rec in l:
pickle.dump(rec,f)
while True:
n=int(input('What do u wanna do: \n1)Enter Data \n2)Display \n3)Update \
n'))
if n==1:
enter_data()
i=input('do u want to continue y/n')
if i.upper()=='Y':
continue
else:
break
elif n==2:
display_rec()
i=input('do u want to continue y/n')
if i.upper()=='Y':
continue
else:
break
elif n==3:
update()
i=input('do u want to continue y/n')
if i.upper()=='Y':
continue
else:
break
else:
print('Choose from 1,2 and 3')
break

Aditya Singh Class XII-C Page: 56


Computer science practical file

Aditya Singh Class XII-C Page: 57


Computer science practical file

Aditya Singh Class XII-C Page: 58


Computer science practical file

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

import pickle

def enter_records(filename):
records = []
while True:
admno = input("Enter Admission Number (or 'exit' to stop): ")
if admno.lower() == 'exit':
break
name = input("Enter Name: ")
percentage = float(input("Enter Percentage: "))

# Append the new record to the list


records.append((admno, name, percentage))

# Write all records to the file


with open(filename, 'ab') as file:
pickle.dump(records, file)

def display_all_records(filename):
try:
with open(filename, 'rb') as file:
while True:
try:
records = pickle.load(file)
for admno, name, percentage in records:
print(f"Admission Number: {admno}, Name: {name},
Percentage: {percentage}")
except EOFError:
break

Aditya Singh Class XII-C Page: 59


Computer science practical file

except FileNotFoundError
print("No records found.")

def display_above_75(filename):
try:
with open(filename, 'rb') as file:
found = False
while True:
try:
records = pickle.load(file)
for admno, name, percentage in records:
if percentage > 75:
found = True
print(f"Admission Number: {admno}, Name: {name},
Percentage: {percentage}")
except EOFError:
break
if not found:
print("No students with percentage above 75.")
except FileNotFoundError:
print("No records found.")

def menu():
filename = "STUQ2.DAT"
while True:
print("\nMenu:")
print("1. Enter Records")
print("2. Display All Records")
print("3. Display Students with Percentage > 75")
print("4. Exit")
choice = input("Enter your choice: ")

if choice == '1':
enter_records(filename)
elif choice == '2':
display_all_records(filename)
elif choice == '3':
display_above_75(filename)

Aditya Singh Class XII-C Page: 60


Computer science practical file

elif choice == '4':


print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
menu()

Aditya Singh Class XII-C Page: 61


Computer science practical file

Aditya Singh Class XII-C Page: 62


Computer science practical file

19) Assuming the tuple Vehicle as follows: ( vehicletype, no_of_wheels) where


vehicletype is a string and no_of_wheels is an integer. Write a menu driven
program using functions
● to enter records
● to display all records
● to count and display the number of records present in the file.

Code:-

import pickle

def enter_records(filename):
records = []
while True:
vehicle_type = input("Enter Vehicle Type (or 'exit' to stop): ")
if vehicle_type.lower() == 'exit':
break
no_of_wheels = int(input("Enter Number of Wheels: "))

# Create a tuple and append it to the records list


records.append((vehicle_type, no_of_wheels))

# Write all records to the file


with open(filename, 'ab') as file:
pickle.dump(records, file)

def display_all_records(filename):
try:
with open(filename, 'rb') as file:
while True:
try:
records = pickle.load(file)
for vehicle in records:
print(f"Vehicle Type: {vehicle[0]}, Number of Wheels:
{vehicle[1]}")
except EOFError:
break
except FileNotFoundError:
print("No records found.")

Aditya Singh Class XII-C Page: 63


Computer science practical file

def count_records(filename):
count = 0
try:
with open(filename, 'rb') as file:
while True:
try:
records = pickle.load(file)
count += len(records)
except EOFError:
break
print(f"Total number of records: {count}")
except FileNotFoundError:
print("No records found.")

def menu():
filename = "vehicles.dat"
while True:
print("\nMenu:")
print("1. Enter Records")
print("2. Display All Records")
print("3. Count Records")
print("4. Exit")
choice = input("Enter your choice: ")

if choice == '1':
enter_records(filename)
elif choice == '2':
display_all_records(filename)
elif choice == '3':
count_records(filename)
elif choice == '4':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
menu()

Aditya Singh Class XII-C Page: 64


Computer science practical file

Aditya Singh Class XII-C Page: 65


Computer science practical file

20) Create a file PRODUCT.CSV. Sample data of the file is as follows: Write a
menu driven program using functions
● to add sample data to the file
● to display all the records
● to copy/transfer only those records from the file PRODUCT.CSV to another
file “PRO1.CSV” whose quantity is more than 150. Also include the first row
with headings.
● To display the total cost of all the products of the file PRODUCT.CSV
● To search and display the record of that product from the file product.csv
which has maximum cost.

Code:-

import csv

def add_sample_data(filename):
sample_data = [
["PID", "PNAME", "QUANTITY", "COST"],
['P1', "Brush", 200, 50],
['P2', "ToothPaste", 150, 120],
['P3', "Comb", 300, 40],
['P4', "Sheets", 500, 100],
['P5', "Pens", 250, 10]
]

with open(filename, 'w', newline='') as file:


writer = csv.writer(file)
writer.writerows(sample_data)

def display_all_records(filename):
try:
with open(filename, 'r') as file:
reader = csv.reader(file)
for row in reader:
print(", ".join(row))
except FileNotFoundError:
print("The file does not exist.")

def copy_records(filename, new_filename):


try:

Aditya Singh Class XII-C Page: 66


Computer science practical file

with open(filename, 'r') as file:


reader = csv.reader(file)
with open(new_filename, 'w', newline='') as new_file:
writer = csv.writer(new_file)
# Write the header row
header = next(reader)
writer.writerow(header)
for row in reader:
if int(row[2]) > 150: # Check quantity
writer.writerow(row)
print(f"Records with quantity greater than 150 copied to
{new_filename}.")
except FileNotFoundError:
print("The source file does not exist.")

def total_cost(filename):
total = 0
try:
with open(filename, 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header
for row in reader:
total += float(row[3]) * int(row[2]) # Cost * Quantity
print(f"Total cost of all products: {total:.2f}")
except FileNotFoundError:
print("The file does not exist.")

def product_with_max_cost(filename):
max_cost = 0
max_product = None
try:
with open(filename, 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header
for row in reader:
cost = float(row[3])
if cost > max_cost:
max_cost = cost
max_product = row
if max_product:

Aditya Singh Class XII-C Page: 67


Computer science practical file

print(f"Product with maximum cost: {max_product}")


else:
print("No products found.")
except FileNotFoundError:
print("The file does not exist.")

def menu():
filename = "PRODUCT.CSV"
while True:
print("\nMenu:")
print("1. Add Sample Data")
print("2. Display All Records")
print("3. Copy Records with Quantity > 150")
print("4. Calculate Total Cost")
print("5. Display Product with Maximum Cost")
print("6. Exit")
choice = input("Enter your choice: ")

if choice == '1':
add_sample_data(filename)
print("Sample data added.")
elif choice == '2':
display_all_records(filename)
elif choice == '3':
copy_records(filename, "PRO1.CSV")
elif choice == '4':
total_cost(filename)
elif choice == '5':
product_with_max_cost(filename)
elif choice == '6':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
menu()

Aditya Singh Class XII-C Page: 68


Computer science practical file

Aditya Singh Class XII-C Page: 69


Computer science practical file

Aditya Singh Class XII-C Page: 70


Computer science practical file

21) Create a file Tour.csv having headings as follows


TID,DESTINATION,DAYS,FARE. Sample data of file is as follows: Write a
menu driven program using functions
● to add sample data to the file
● to display all the records
● to read the file tour.csv and display the records where fare is between 500 and
750. If no such record is found in the file then display an appropriate message
on the screen.

Code:-

import csv

def add_sample_data(filename):
sample_data = [
["TID", "DESTINATION", "DAYS", "FARE"],
["T10", "Australia", 10, 300],
["T11", "Austria", 15, 750],
["T12", "Rajasthan", 10, 700],
["T13", "France", 12, 650]
]

with open(filename, 'w', newline='') as file:


writer = csv.writer(file)
writer.writerows(sample_data)

def display_all_records(filename):
try:
with open(filename, 'r') as file:
reader = csv.reader(file)
for row in reader:
print(", ".join(row))
except FileNotFoundError:
print("The file does not exist.")

def display_fare_between(filename, lower, upper):


found = False
try:
with open(filename, 'r') as file:
reader = csv.reader(file)

Aditya Singh Class XII-C Page: 71


Computer science practical file

next(reader) # Skip header


for row in reader:
fare = float(row[3])
if lower <= fare <= upper:
print(", ".join(row))
found = True
if not found:
print(f"No records found with fare between {lower} and {upper}.")
except FileNotFoundError:
print("The file does not exist.")

def menu():
filename = "Tour.csv"
while True:
print("\nMenu:")
print("1. Add Sample Data")
print("2. Display All Records")
print("3. Display Records with Fare between 500 and 750")
print("4. Exit")
choice = input("Enter your choice: ")

if choice == '1':
add_sample_data(filename)
print("Sample data added.")
elif choice == '2':
display_all_records(filename)
elif choice == '3':
display_fare_between(filename, 500, 750)
elif choice == '4':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
menu()

Aditya Singh Class XII-C Page: 72


Computer science practical file

Aditya Singh Class XII-C Page: 73


Computer science practical file

22) Write a function in python, MakePush(Package) and MakePop(Package) to


add a new Package and delete a Package from a List of Package Description,
considering them to act as push and pop operations of the Stack data structure.
Implement the complete menu driven program

Code:-

def MakePush(Package):
n=input('Enter the element to be added')
Package.append(n)
print("elemet pushed on to stack")
def MakePop(Package):
if (Package==[]):
print("Stack Empty-underflow")
else:
print("Deleted element is :",Package.pop())
Package=[]
while True:
i=int(input('Menu\n1)Add an element\n2) Delete the last item \n'))
if i==1:
MakePush(Package)
n=input('want to continue y/n \n')
if n.upper()=='Y':
continue
else:
break
elif i==2:
MakePop(Package)
n=input('want to continue y/n \n')
if n.upper()=='Y':
continue
else:
break

Aditya Singh Class XII-C Page: 74


Computer science practical file

Aditya Singh Class XII-C Page: 75


Computer science practical file

23) 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 display the
stack respectively. Implement the menu driven program
Code :-
def Push(stk,item):
stk.append(item)
print("elemet pushed on to stack")
def Pop(stk):
if (stk==[]):
print("Stack Empty-underflow")
else:
print("Deleted element is :",stk.pop())
print(stk)
stk=[]
while True:
i=int(input('Menu\n1)Add an element\n2) Delete the last item \n'))
if i==1:
item=input('enter the integer to be added')
Push(stk,item)
n=input('want to continue y/n \n')
if n.upper()=='Y':
continue
else:
break
elif i==2:
Pop(stk)
n=input('want to continue y/n \n')
if n.upper()=='Y':
continue
else:
break

Aditya Singh Class XII-C Page: 76


Computer science practical file

Aditya Singh Class XII-C Page: 77


Computer science practical file

24) Write a program to perform push operation on a stack to push all prime
numbers from a list entered by a user.
Code:-
def push(l,num):
for i in range(2,num):
if num%i==0:
break
else:
l.append(num)
print(l)
l=[]
while True:
num=int(input('enter the number'))
push(l,num)
n=input('Want to continue y/n ?\n')
if n.upper()=='Y':
continue
else:
print('Bye Have A Good day')
break

Aditya Singh Class XII-C Page: 78

You might also like