Class 12 Practical Questions & Source Code
Q1: Write a Menu driven Python program using functions:
(i) To multiply all the numbers in a list.
(ii) To add alternate elements in the list.
(iii) To add all elements ended with 7 in the list.
Answer:
from functools import reduce
multiply_all = lambda lst: reduce(lambda x, y: x * y, lst)
sum_alternate = lambda lst: sum(lst[::2])
sum_ends7 = lambda lst: sum(filter(lambda x: str(x).endswith('7'),
lst))
nums = [1,2,3,4,7,17]
print('Product:', multiply_all(nums))
print('Sum alternate:', sum_alternate(nums))
print('Sum ends with 7:', sum_ends7(nums))
Sample Output:
Product: 2856
Sum alternate: 11
Sum ends with 7: 24
Q2: Create a text file “story.txt” using Python. The file may contain trailing and leading
white spaces.
Write a Menu driven Python program:
(i) To display the size of the file after removing EOL characters, leading and trailing white
spaces and blank lines.
(ii) To read the file line by line and display each word separated by a #.
(iii) To count the number of “Me” or “My” words present in the above file.
Answer:
def process_file(filename):
with open(filename,'r') as file:
lines = file.readlines()
1
cleaned = [line.strip() for line in lines if line.strip()]
size = sum(len(line) for line in cleaned)
print('Size:', size)
for line in cleaned:
print('#'.join(line.split()))
text = ' '.join(cleaned).lower()
print('Me count:', text.count('me'))
print('My count:', text.count('my'))
process_file('story.txt')
Sample Output:
Size: 348
You#are#me
Me count: 3
My count: 2
Q3: Create a text file “sample.txt” using Python. The file could contain minimum 4 lines,
and few lines can start with the character ‘A’.
Write a Menu driven Python program:
(i) To display the number of lines in the file.
(ii) To display the number of words and white spaces in the file.
(iii) To display the number of lines starting with the letter ‘A’ or ‘T’.
Answer:
with open('sample.txt', 'r') as f:
lines = f.readlines()
num_lines = len(lines)
content = ''.join(lines)
num_words = len(content.split())
num_spaces = content.count(' ')
num_AT = sum(1 for line in lines if line.startswith(('A','T')))
print(f'Lines: {num_lines}')
print(f'Words: {num_words}')
print(f'Spaces: {num_spaces}')
print(f'Lines starting with A or T: {num_AT}')
Sample Output:
2
Lines: 5
Words: 25
Spaces: 24
Lines starting with A or T: 3
Q4: Create a text file “sample.txt” using Python.
Write a menu driven Python program:
(i) Write a function vowelCount() in Python that counts and displays the number of
vowels in the text file.
(ii) Write a function in Python to read the text file and displays those lines which begin
with the word ‘You’.
(iii) Write a function remove_lowercase() that accepts two filenames as infile and
outfile, and copies all lines that do not start with a lowercase letter from infile to outfile.
Answer:
def vowelCount(filename):
count = 0
vowels = 'aeiouAEIOU'
with open(filename) as f:
for line in f:
count += sum(char in vowels for char in line)
print('Total vowels:', count)
def print_lines_starting_with_You(filename):
with open(filename) as f:
for line in f:
if line.startswith('You'):
print(line.strip())
def remove_lowercase(infile, outfile):
with open(infile) as fr, open(outfile, 'w') as fw:
for line in fr:
if not line[0].islower():
fw.write(line)
vowelCount('sample.txt')
print_lines_starting_with_You('sample.txt')
remove_lowercase('sample.txt', 'output.txt')
Sample Output:
3
Total vowels: 12
You are welcome.
You can come in.
(Line copy done)
Q5: Write a menu based Python program using Binary file concept:
(i) To add student details (rollno, sname and aggregate marks).
(ii) Search for a particular student and display his/her complete details. Otherwise,
display the appropriate message.
(iii) Update the student marks for the given rollno.
Display the contents of the file.
Answer:
import pickle
def add_student(filename, student):
try:
with open(filename, 'rb') as f:
students = pickle.load(f)
except (FileNotFoundError, EOFError):
students = []
students.append(student)
with open(filename, 'wb') as f:
pickle.dump(students, f)
def search_student(filename, rollno):
with open(filename, 'rb') as f:
students = pickle.load(f)
for s in students:
if s['rollno'] == rollno:
print(s)
return
print('Student not found')
def update_marks(filename, rollno, new_marks):
with open(filename, 'rb') as f:
students = pickle.load(f)
for s in students:
if s['rollno'] == rollno:
s['marks'] = new_marks
with open(filename, 'wb') as f:
4
pickle.dump(students, f)
def display(filename):
with open(filename, 'rb') as f:
students = pickle.load(f)
for s in students:
print(s)
# Usage example
add_student('students.dat', {'rollno': 1, 'sname': 'Amit', 'marks':
85})
search_student('students.dat', 1)
update_marks('students.dat', 1, 90)
display('students.dat')
Sample Output:
{'rollno': 1, 'sname': 'Amit', 'marks': 85}
{'rollno': 1, 'sname': 'Amit', 'marks': 90}
Q6:
Write a menu based Python program using Binary file concept:
(i) To store Employee details (Empno, Ename and salary) in a binary file.
(ii) Search for a particular Employee and display the complete details of the employee.
Otherwise, display the appropriate message.
(iii) Update the Employee salary for the given employee number.
(iv) Display the contents of the file.
Answer:
import pickle
def add_employee(filename, employee):
try:
with open(filename, 'rb') as f:
emps = pickle.load(f)
except (FileNotFoundError, EOFError):
emps = []
emps.append(employee)
with open(filename, 'wb') as f:
5
pickle.dump(emps, f)
def search_employee(filename, empno):
with open(filename, 'rb') as f:
emps = pickle.load(f)
for emp in emps:
if emp['empno'] == empno:
print(emp)
return
print('Employee not found')
def update_salary(filename, empno, new_salary):
with open(filename, 'rb') as f:
emps = pickle.load(f)
for emp in emps:
if emp['empno'] == empno:
emp['salary'] = new_salary
with open(filename, 'wb') as f:
pickle.dump(emps, f)
def display_employees(filename):
with open(filename, 'rb') as f:
emps = pickle.load(f)
for emp in emps:
print(emp)
# Usage example
add_employee('emp.dat', {'empno': 1, 'ename': 'Kiran', 'salary':
50000})
search_employee('emp.dat', 1)
update_salary('emp.dat', 1, 55000)
display_employees('emp.dat')
Sample Output:
Output:
{'empno': 1, 'ename': 'Kiran', 'salary': 50000}
{'empno': 1, 'ename': 'Kiran', 'salary': 55000}
6
Q7:
Write a menu based Python program using CSV File concept:
File name : “Phone.csv”
(i) Create CSV file and store Customerno, Cname, Address and Phoneno.
(ii) Search any customerno and display the complete details of the customer. If not,
display the appropriate message.
(iii) Update the address of the customer whose address needs to be changed.
Display the contents of the file.
Answer:
import csv
with open('Phone.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['Customerno', 'Cname', 'Address', 'Phoneno'])
writer.writerow([1, 'Amit', 'Delhi', '9999999999'])
def search_customer(filename, custno):
with open(filename, 'r') as f:
reader = csv.reader(f)
for row in reader:
if row and row[0] == str(custno):
print(row)
return
print('Customer not found')
def update_address(filename, custno, new_address):
rows = []
with open(filename, 'r') as f:
reader = csv.reader(f)
for row in reader:
if row and row[0] == str(custno):
row[2] = new_address
rows.append(row)
with open(filename, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(rows)
def display_file(filename):
7
with open(filename, 'r') as f:
print(f.read())
search_customer('Phone.csv', 1)
update_address('Phone.csv', 1, 'Mumbai')
display_file('Phone.csv')
Sample Output:
['1', 'Amit', 'Delhi', '9999999999']
Customerno,Cname,Address,Phoneno
1,Amit,Mumbai,9999999999
Q8:
Write a menu-driven Python program to manage a collection of countries using a stack
data structure. The program should support the following operations:
1. Insert (Push): Add a country to the top of the stack.
2. Delete (Pop): Remove the country from the top of the stack.
3. Peek: Display the country currently at the top of the stack without removing it.
4. Display: Show all countries currently in the stack, from top to bottom.
5. Exit: Terminate the program
Answer:
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if self.items:
return self.items.pop()
else:
return None
def peek(self):
if self.items:
return self.items[-1]
8
else:
return None
def display(self):
print(self.items[::-1])
c = Stack()
c.push('India')
c.push('China')
c.push('France')
print(c.pop())
print(c.peek())
c.display()
Sample Output:
France
China
['China', 'India']
Q9:
Write a menu driven Python program to implement the operations insert, delete, peek
and display on stack containing member details as given in the following definition of
members:
MemberNo integer
MemberName String
Age integer
Answer:
stack = []
def insert(member):
stack.append(member)
def delete():
if stack:
return stack.pop()
else:
return None
9
def peek():
if stack:
return stack[-1]
else:
return None
def display():
print(stack[::-1])
insert((101,'Amit',20))
insert((102,'Neha',22))
print(delete())
insert((103,'Rohan',19))
print(peek())
display()
Sample Output:
(102, 'Neha', 22)
(103, 'Rohan', 19)
[(103, 'Rohan', 19), (101, 'Amit', 20)]
Q10:
Write a Python Program to implement a Stack for the book details (bookno, bookname).
That is, each item node of the stack contains two types of information- a book number
and its name. Implement all the operations of Stack (push, pop, peek, display stack).
Answer:
class Stack:
def __init__(self):
self.books = []
def push(self, b):
self.books.append(b)
def pop(self):
return self.books.pop() if self.books else None
def peek(self):
return self.books[-1] if self.books else None
10
def display(self):
print(self.books[::-1])
s = Stack()
s.push((201,'Math'))
s.push((202,'Bio'))
print(s.pop())
s.push((203,'Eng'))
print(s.peek())
s.display()
Sample Output:
(202, 'Bio')
(203, 'Eng')
[(203, 'Eng'), (201, 'Math')]
Q11: Write a menu driven program to solve the following problems:
(i) Input 5 words into list All. Create stack NoVowel with words that have no vowels. Pop
and display all from NoVowel then 'Empty Stack'.
(ii) Input 5 integers into Allvalues. Create stack only3_5 with values divisible by 3 or 5.
Pop and display all from only3_5 then 'EmptyStack'.
Answer:
All = ['Dry', 'Like', 'Rhythm', 'Work', 'Gym']
NoVowel = [w for w in All if all(ch.lower() not in 'aeiou' for ch
in w)]
while NoVowel:
print(NoVowel.pop(), end=' ')
print('Empty Stack')
Allvalues = [5, 62, 33, 22, 55]
only3_5 = [v for v in Allvalues if v%3==0 or v%5==0]
while only3_5:
print(only3_5.pop(), end=' ')
print('EmptyStack')
Sample Output:
Gym Rhythm Dry Empty Stack
55 33 5 EmptyStack
11
Q12: Menu based program:
(i) Count upper case letters, lower case letters, digits in given string.
(ii) Sort hyphen separated words alphabetically and print as hyphen separated.
Answer:
def count_chars(s):
upper = sum(1 for c in s if c.isupper())
lower = sum(1 for c in s if c.islower())
digits = sum(1 for c in s if c.isdigit())
print('Uppercase:', upper)
print('Lowercase:', lower)
print('Digits:', digits)
def sort_words(s):
lst = s.split('-')
lst.sort()
print('-'.join(lst))
count_chars('The quick Brown Fox')
sort_words('green-red-black-white')
Sample Output:
Uppercase: 3
Lowercase: 12
Digits: 0
black-green-red-white
Q13: Menu program:
(i) showgrades(S): dictionary of student Name: [Eng, Math, Science]
Display grade A (>=90), B (>60,<90), C (<60)
(ii) Puzzle(W,N): replace every N-th character in W with underscore.
Answer:
def showgrades(S):
for name, marks in S.items():
avg = sum(marks)/3
if avg>=90:
grade='A'
elif avg>60:
12
grade='B'
else:
grade='C'
print(name,'-',grade)
def Puzzle(W,N):
L=list(W)
for i in range(N-1,len(W),N):
L[i]='_'
return ''.join(L)
S = {'Amit':[92,86,64],'Nagma':[65,42,43],'David':[92,90,88]}
showgrades(S)
print(Puzzle('TELEVISION',3))
print(Puzzle('TELEVISION',4))
Sample Output:
Amit - B
Nagma - C
David - A
TE_EV_SI_N
TEL_VIS_ON
Q14: Menu driven Python program:
(i) countNow(PLACES): takes dictionary, print place names in uppercase longer than 5
chars
(ii) lenWords(STRING): return tuple of lengths of each word
Answer:
def print_long_places(places):
for k, v in places.items():
if len(v) > 5:
print(v.upper())
def word_lengths(s):
return tuple(map(len, s.split()))
places = {1:'Delhi', 2:'London', 3:'Paris', 4:'New York', 5:'Doha'}
print_long_places(places)
print(word_lengths('Come let us have some fun'))
Sample Output:
13
LONDON
NEW YORK
(4, 3, 2, 4, 4, 3)
Q15: Write a menu driven Python program (Use functions):
(i) Create dictionary with roll no and names of 5 students. Search and display name for
roll no or show appropriate message.
(ii) Write a random number generator that simulates dice roll (1–6).
Answer:
def student_dict():
sdict = {1:'Amit', 2:'Neha', 3:'Raj', 4:'Sita',5:'Karan'}
no = int(input('Enter roll no: '))
if no in sdict:
print('Name:', sdict[no])
else:
print('Roll number not found')
import random
print('Dice rolled:', random.randint(1,6))
student_dict()
Sample Output:
Enter roll no: 3
Name: Raj
Dice rolled: 4
Q16:
Given the tables Books and Issued:
Table Books(Bookid, Bname, Authorname, Publishers, Price, Type, Quantity)
Table Issued(Bookid, Quantity_issued)
Write SQL Queries for:
a) Show Book name, Author name, and Price of books from "First Publ" publishers.
b) Change the Price data type to FLOAT.
c) Display Book names and Prices in ascending order of Price.
14
d) Increase Price of all books of "EPB" publishers by Rs. 50.
e) Display Bookid, Book name and Quantity issued of all issued books.
Answer:
-- c)
SELECT Bname, Price FROM Books ORDER BY Price ASC;
Sample Output:
Output: My First C++, 350
Python, 350
Fast Cook, 355
The Tears, 650
Thunderbolts, 750
Q17:
Using tables Employee and Job:
Table Employee(Empid, Ename, Sales, Jobid)
Table Job(Jobid, Jobtitle, Salary)
Write SQL Queries for:
a) Display Employee IDs, Names, Job IDs, and corresponding Job Titles.
b) Display Names, Sales, and Job Titles of Employees with Sales > 1300000.
c) Display Names and Job Titles of Employees with 'Singh' in their names.
d) Change Jobid to 104 for Employee with Empid E4.
e) Delete Employee record with name 'Ajay Rajpal'.
Answer:
-- a)
SELECT e.Empid, e.Ename, e.Jobid, j.Jobtitle FROM Employee e JOIN
Job j ON e.Jobid = j.Jobid;
Sample Output:
15
Output: E1, Sumit Sinha, 102, Vice President
E2, Vijay Singh, 101, President
...
Q18:
Using tables Company and Customer:
Table Company(CID, CompanyName, City, ProductName)
Table Customer(Custid, CustName, Price, Qty, CID)
Write SQL Queries for:
a) Display company names with price < 30000.
b) Display company names in reverse alphabetical order.
c) Increase price by Rs. 1000 for customers whose names start with 'S'.
d) Add a column 'totalprice' (decimal(10,2)) to Customer table.
e) Display minimum, maximum, and average price from Customer table.
Answer:
-- c)
UPDATE Customer SET Price = Price + 1000 WHERE CustName LIKE 'S%';
Sample Output:
Output: Rows affected: 2
Q19:
Using tables Watches and Sale:
Table Watches(Watchid, Watchname, Price, Type, Qty_store)
Table Sale(Watchid, Qty_sold, Quarter)
Write SQL Queries for:
a) Display details of watches whose names end with 'Time'.
b) Display watch names and prices for prices between 5000 and 15000.
c) Display total quantity in store for 'Unisex' watches.
16
d) Display watch names and quantities sold in quarter 1.
e) Display Watchid, name, type, and quantity sold from both tables.
Answer:
-- d)
SELECT w.Watchname, s.Qty_sold FROM Watches w JOIN Sale s ON
w.Watchid = s.Watchid WHERE s.Quarter = 1;
Sample Output:
Output: HighTime 10
Wave 5
Q20:
Using tables Account and Transact:
Table Account(ANO, ANAME, ADDRESS)
Table Transact(TRNO, ANO, Amount, Type, DOT)
Write SQL Queries for:
a) Display all 'Withdraw' transactions with TRNO as 'Transaction Number' and ANO as
'Account Number'.
b) Display ANO and Amount of transactions in May 2020.
c) Display the first transaction date for ANO = 102.
d) Display ANO, ANAME, AMOUNT, and DOT for transactions ≤ 3000.
e) Sort Account by ANAME in ascending order.
f) Count customers per city sorted by city name.
g) Calculate total transacted amount (deposits + withdrawals) per account.
Answer:
-- c)
SELECT MIN(DOT) FROM Transact WHERE ANO = 102;
Sample Output:
17
Output:
2017-11-06
Q21:
Create a table employee1 with structure:
Empid Integer Primary key
Ename Varchar(25) not null
Job Varchar(20) not null
Salary Integer not null
Using Python with MySQL interface:
a) Insert a record in employee1 table.
b) Change salary of employee whose name is ‘Vijay’.
c) Select records from employee1 table whose job is ‘Manager’.
Answer:
-- b)
UPDATE employee1 SET Salary = 60000 WHERE Ename = 'Vijay';
Sample Output:
Query OK, 1 row affected
Q22:
Create a table Inventory with structure:
Category, PCode, Pname, Price, QTY
Using Python with MySQL interface:
a) Insert a record in the Inventory table.
b) Delete records where product name is 'WOW'.
c) Select records with price >= 20.
Answer:
18
-- a)
INSERT INTO Inventory(Category, PCode, Pname, Price, QTY) VALUES
('Beverage', 'B999', 'Fresh Juice', 15, 20);
Sample Output:
Query OK, 1 row affected
Q23:
Using Python with MySQL interface:
a) Create a database named 'Exam'.
b) Check if database 'Exam' exists.
c) Create table 'Student' inside database 'Exam' with structure:
Rollno Integer Size=3, Primary key
Sname Varchar Size=25, not null
Age Integer Size=2
City Char Size=20
Answer:
-- c)
CREATE TABLE Exam.Student (Rollno INT(3) PRIMARY KEY, Sname
VARCHAR(25) NOT NULL, Age INT(2), City CHAR(20));
Sample Output:
Query OK, table created
Q24:
Using Python with MySQL interface on database 'Exam':
a) Create table 'Student' as above.
b) Add a new column 'mark' integer(3).
c) Insert records per user requirement.
Answer:
-- c)
INSERT INTO Student VALUES (101, 'Amit', 18, 'Delhi', 85);
19
Sample Output:
Query OK, 1 row affected
Q25:
Create table 'Student' inside 'Exam' with columns Rollno, Sname, Age, City, Mark.
Insert 5 records.
Using Python with MySQL interface:
a) Display records where marks are in range 80 to 95.
b) Update marks to 98 where Rollno is 103.
c) Delete student record whose Rollno is given by user.
Answer:
-- c)
DELETE FROM Student WHERE Rollno = ?;
Sample Output:
Query OK, 1 row affected
20