0% found this document useful (0 votes)
23 views

Practical File Questions

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

Practical File Questions

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

APEEJAY SCHOOL, PANCHSHEEL PARK

Class - XII Computer Science (083)


Practical File
(2024-2025)

CONTENT INDEX :

● FUNCTIONS
● DATA FILES
● STACKS
● SQL
● SQL CONNECTIVITY
● Functions
1. Write a function to generate Fibonacci series.
Source Code :
def fibo():
N = int(input("Enter the number of terms for the fibonacci series:
"))
a=0
b=1
for i in range(N):
print(a)
a, b = b, a+b
fibo()
Output :

2. Write a program using function to reverse a string


Source Code :
def reverse():
string = input("Enter the string to reverse: ")
print("this is the reversed string: ", string[::-1])

reverse()
Output :

3. Write a program to calculate the GCD and LCD of two numbers.


Source Code :
def gcd_lcm():
import math
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print("GCD:", math.gcd(num1, num2))
print("LCM:", math.lcm(num1, num2))
gcd_lcm()

Output :

4. Write a function to remove all the duplicate numbers in an array


Source Code :
def duplarray():
array = input("Enter the elements of the array seperated by spaces: ")
array2 = array.split()
unique_array = []
for i in array2:
if i not in unique_array:
unique_array.append(i)
print("The array with no duplicate elements is: ", unique_array)
duplarray()
Output :

5. Write a function that interchanges the value of two integers A and B


without using any extra variable.
Source Code :
def interchange():
A = int(input("Enter the first number: "))
B = int(input("Enter the second number: "))
A,B = B,A
print("The swapped numbers are: ", A, B)

interchange()
Output :

6. Write a function to find the sum of series: 1+3+5+7+9+11+ ………. upto


N terms
Source Code :
def oddsum():
N = int(input("Enter the number of terms: "))
print("Sum of first", N, "odd numbers is:", N**2)

oddsum()
Output :

● Data Files
7. Write a program to create a text file ‘test.txt’. Write a function to count
the number of characters from a file. (Don’t count white spaces)
Source Code :
def count_characters(filename):
with open(filename, 'r') as file:
return len(file.read().replace(" ", "").replace("\n", ""))

with open('test.txt', 'w') as file:


file.write("Hello, this is a test file.\nIt contains several lines of text.")

print("Number of characters (excluding white spaces):", count_characters('test.txt'))

Output :

8. Write a program to create a text file ‘test.txt’. Write a function to count


the number of words in a file
Source Code :
def count_words(filename):
with open(filename, 'r') as file:
return len(file.read().split())

with open('test.txt', 'w') as file:


file.write("Hello, this is a test file.\nIt contains several lines of text.")

print("Number of words in 'test.txt':", count_words('test.txt'))


Output :

9. Write a program to create a text file ‘test.txt’. Write a function to count


number of lines in a text file.
Source Code :
def count_lines(filename):
with open(filename, 'r') as file:
return len(file.readlines())

with open('test.txt', 'w') as file:


file.write("Hello, this is a test file.\nIt contains several lines of text.\nHere is
another line.")
print("Number of lines in 'test.txt':", count_lines('test.txt'))
Output :

10. Write a program to create a text file ‘test.txt’. Write a function to


Count the number of ‘is’ word in a text file.
Source Code :
def count_is_word(filename):
with open(filename, 'r') as file:
content = file.read().lower()
return content.split().count('is')
with open('test.txt', 'w') as file:
file.write("This is a test file. It is used to count the number of 'is' words.")

print("Number of times 'is' appears in 'test.txt':", count_is_word('test.txt'))


Output :

11. Write a program to create a text file ‘story.txt’. Write a method/


function DISPLAYWORDS() in python to read lines from a textfile
STORY.TXT, and display those words, which are less than 4 characters.
Source Code :
def DISPLAYWORDS(filename):
with open(filename, 'r') as file:
content = file.read().split()
short_words = [word for word in content if len(word) < 4]
print("Words with less than 4 characters:", short_words)

with open('story.txt', 'w') as file:


file.write("It was a sunny day. The sky is blue and the sun is bright. We all love
such days.")

DISPLAYWORDS('story.txt')
Output :
12. Create a CSV file by entering user- id and password, read and search
the password for given user-id.
Source Code :
import csv

with open("student.csv", "w", newline='') as f:


stuwriter = csv.writer(f)
stuwriter.writerow(["User Id", "Password"])

while True:
user_id = input("Enter ID: ")
password = input("Enter password: ")
stuwriter.writerow([user_id, password])
x = input("Press 'yes' to continue and 'no' to stop: ").strip().lower()
if x == "no":
break
search_id = input("Enter the user ID to be searched: ").strip()

with open("student.csv", "r") as f2:


stuwriter2 = csv.reader(f2)
next(stuwriter2) # Skip the header row
for row in stuwriter2:
if row[0] == search_id:
print(f"Password for user ID '{search_id}': {row[1]}")
break
else:
print("User ID not found.")
Output :

13. Write a program to create a csv file ‘student.csv’ to store roll no,
name, stream and marks. Write a function to perform read operation
and display.
Source Code :
import csv

def create_csv(filename):
with open(filename, "w", newline='') as f:
stuwriter = csv.writer(f)
stuwriter.writerow(['Rollno', 'Name', 'Stream', 'Marks'])
n = int(input("Enter number of students: "))
for i in range(n):
print(f"Student record {i + 1}")
rollno = int(input("Enter roll no: "))
name = input("Enter name: ")
stream = input("Enter stream: ")
marks = int(input("Enter marks: "))
stuwriter.writerow([rollno, name, stream, marks])

def read_csv(filename):
with open(filename, "r") as f:
stureader = csv.reader(f)
for row in stureader:
print(row)

create_csv("student.csv")

print("Displaying student records from 'student.csv':")


read_csv("student.csv")

Output :

14. Write a program to create a binary file ‘student.dat’ and search a


record from the binary file "student.dat" on the basis of roll number.
[RollNo, StName, Stream, Percentage].
Source Code :
import pickle

def write_records(filename):
with open(filename, "wb") as f:
while True:
rno = int(input("Enter your roll no: "))
Stname = input("Enter name: ")
stream = input("Enter your stream: ")
Percentage = float(input("Enter your percentage: "))
stu = {
'rollno': rno,
'Name': Stname,
'stream': stream,
'Percentage': Percentage
}
pickle.dump(stu, f)
ans = input("Want to enter more records? (y/n): ").strip().lower()
if ans != 'y':
break

def search_record(filename, search_rollno):


with open(filename, "rb") as f:
found = False
try:
while True:
stu = pickle.load(f)
if stu['rollno'] == search_rollno:
print(f"Name: {stu['Name']}")
found = True
break
except EOFError:
if not found:
print("Sorry, no such record found.")

write_records("student.dat")
search_rollno = int(input("Enter roll number to search for: "))
search_record("student.dat", search_rollno)
Output :

15. Write a program to create a binary file “emp.dat” having structure


(Emp_id, Emp_name, Emp_Salary). Write a function in Python
countsal()that would read contents of the file “emp.dat” and display the
details of those Employee whose salary is greater than 20000.
Source Code :
import pickle

def write_emp_records(filename):
with open(filename, "wb") as f:
while True:
emp_id = int(input("Enter Employee ID: "))
emp_name = input("Enter Employee Name: ")
emp_salary = float(input("Enter Employee Salary: "))
pickle.dump({'Emp_id': emp_id, 'Emp_name': emp_name, 'Emp_Salary': emp_salary}, f)
if input("Add another record? (y/n): ").strip().lower() == 'n':
break

def countsal(filename):
with open(filename, "rb") as f:
while True:
try:
record = pickle.load(f)
if record['Emp_Salary'] > 20000:
print(f"ID: {record['Emp_id']}, Name: {record['Emp_name']}, Salary:
{record['Emp_Salary']}")
except EOFError:
break

write_emp_records("emp.dat")
print("Employees with salary greater than 20,000:")
countsal("emp.dat")
Output :

16. Write a program to create a binary file “Stu.dat” has structure (rollno,
name, marks).
(i) Write a function in Python add_record() to input data for a record
and add to Stu.dat.
(ii) Write a function in python Search_record() to search a record from
binary file “Stu.dat” on the basis of roll number.
Source Code :
import pickle
def add_record(filename):
with open(filename, "ab") as f:
rollno = int(input("Enter roll number: "))
name = input("Enter name: ")
marks = float(input("Enter marks: "))
record = {'rollno': rollno, 'name': name, 'marks': marks}
pickle.dump(record, f)
def search_record(filename, search_rollno):
with open(filename, "rb") as f:
while True:
try:
record = pickle.load(f)
if record['rollno'] == search_rollno:
print(f"Roll No: {record['rollno']}, Name: {record['name']}, Marks:
{record['marks']}")
return
except EOFError:
print("Record not found.")
return
while True:
add_record("Stu.dat")
if input("Add another record? (y/n): ").strip().lower() == 'n':
break
search_rollno = int(input("Enter roll number to search: "))
search_record("Stu.dat", search_rollno)
Output :

17. Write a program to create a binary file ‘EMP.dat’ has structure


[Empno,Empname,Dept,Salary].
a. Write a user defined function Addcontents() to input data for a record
and add to “EMP.DAT”.
b. Write a user defined function Disp(dept) in Python which accepts the
Department name as the parameter and count and return the number of
employees who belong to that department as stored in the ‘EMP.DAT’
file
Source Code :
import pickle

def add_contents(filename):
with open(filename, "ab") as f:
empno = int(input("Enter employee number: "))
empname = input("Enter employee name: ")
dept = input("Enter department: ")
salary = float(input("Enter salary: "))
record = {'Empno': empno, 'Empname': empname, 'Dept': dept, 'Salary':
salary}
pickle.dump(record, f)

def disp(dept, filename):


count = 0
with open(filename, "rb") as f:
while True:
try:
record = pickle.load(f)
if record.get('Dept') == dept:
count += 1
except EOFError:
break
return count

while True:
add_contents("EMP.dat")
if input("Add another record? (y/n): ").strip().lower() != 'y':
break

dept = input("Enter department to count employees: ")


count = disp(dept, "EMP.dat")
print(f"Number of employees in department '{dept}': {count}")
Output :

● Stacks
18. Write a Python program to implement all basic operations of a Stack,
such as adding element, removing element and displaying the Stack
elements using lists.
Source Code :
def create_stack():
stack = []
return stack

def push(stack, element):


stack.append(element)

def pop(stack):
if not is_empty(stack):
return stack.pop()
else:
return None

def is_empty(stack):
return len(stack) == 0

def display(stack):
return stack

stack = create_stack()
push(stack, "xenon")
push(stack, "uranium")
push(stack, "thorium")

print("Stack elements:", display(stack))


print("Popped element:", pop(stack))
print("Stack elements after pop:", display(stack))
Output :

19. Write a program to display unique vowels present in the given word
using Stack.
Source Code :
def create_stack():
return []

def push(stack, item):


stack.append(item)

def display(stack):
return stack

def unique_vowels(word):
vowels = "aeiou"
stack = create_stack()
unique_vowels = set()

for char in word:


if char in vowels and char not in unique_vowels:
push(stack, char)
unique_vowels.add(char)

return display(stack)

# Example usage
word = input("Enter a word: ").lower()
result = unique_vowels(word)
print("Unique vowels in the word:", " ".join(result))
Output :

20. Write a program in Python to implement the following operation on


Stack containing employee code and name. 1. PUSH 2. POP 3. DISPLAY
Source Code :
def push_employee(stack, code, name):
employee = (code, name)
stack.append(employee)

def pop_employee(stack):
if is_empty(stack):
return None
return stack.pop()

def display_employees(stack):
if is_empty(stack):
print("Stack is empty.")
else:
for employee in reversed(stack):
print("Code:", employee[0], "Name:", employee[1])

def is_empty(stack):
return len(stack) == 0

employee_stack = []

push_employee(employee_stack, 1, "John Doe")


push_employee(employee_stack, 2, "Jane Doe")
push_employee(employee_stack, 3, "Jim Doe")

print("Employees in the stack:")


display_employees(employee_stack)

popped_employee = pop_employee(employee_stack)
if popped_employee:
print("Popped employee: Code:", popped_employee[0], "Name:",
popped_employee[1])
else:
print("No employee to pop.")

print("Employees in the stack after pop:")


display_employees(employee_stack)
Output :

● SQL
21. Write the SQL commands for the following , given the table:
A. To display the names of all students who are in Medical stream.
B. display the report of all the non-medical stream students from the
student table.
C. List all the names of the students of class 12 sorted by stipend.
D. List all the students sorted by Avgmark in descending order.
E. TO count the number of students with grade ‘A’.
F. To insert a new student in the table with your own data.
G. Give the output :
i. select Min(avgmark) from student where avgmark<75 ;
ii. select sum(stipend) from student where grade = “B” ;
iii. select avg(stipend) from student where class=”12A” ;
iv. select count(distinct stream) from student;
Commands :
A) Display the names of all students who are in Medical stream

B) Display the report of all the non-medical stream students from the
student table.

C) List all the names of the students of class 12 sorted by stipend


D) List all the students sorted by Avgmark in descending order.

E) To count the number of students with grade ‘A’. F. To insert a new


student in the table with your own data.

F) To insert a new student in the table with your own data.


G) i. select Min(avgmark) from student where avgmark<75 ;

ii. select sum(stipend) from student where grade = “B” ;

iii. select avg(stipend) from student where class=”12A” ;

iv. select count(distinct stream) from student;


22. Write SQL commands for the following:

a. Display data for all the items sorted by their names.


b. display the name and price for price between 3000 and 7000
c. List all names and prices in descending order of their stock.
d. write the command to set the price field of all products to 1200
corresponding to name=”KEYBOARD”
e. Write SQL command to delete rows with stock between 20 to 40.
f. To count the number of products with stock<25.
g. Give the output :
i. select sum(stock) from product ;
ii. select avg(stock) from product where stock>20 ;
iii. select count(distinct stock) from product ;
iv. select max(price) from product;
Commands :
A) select * from PRODUCT order by NAME;

B) select NAME,PRICE from PRODUCT where PRICE between 3000


and 7000;
C) select NAME, PRICE from PRODUCT order by stock desc;

D) update PRODUCT set PRICE=1200 where NAME='KEYBOARD';

E) delete from PRODUCT where STOCK between 20 and 40;


F) select count(NAME) from PRODUCT where stock<25;

G) i. select sum(stock) from product ;

ii. select avg(stock) from product where stock>20 ;

iii. select count(distinct stock) from product ;

iv. select max(price) from product;


23. Write SQL commands for the following:

a. to display the title of all books with price between 100 and 300.
b. to display title and author of all the books having type PROG and
publisher BPB.
c. to display list of all the books with price more than 130 in ascending
order of quantity.
d. to display a report with title, price for each book in the table.
e. to display the publishers and the number of books of each publisher in
the table.
f. to insert a new book with data: 11, “computer sc.”,”r.k.”,”bpb”,2,250
g. Give the output:
i. select min(price) from library ;
i. select sum(price*quantity) from library where quantity > 3 ;
iii. select avg(price) from library where quantity<4 ;
iv. select count(distinct publisher) from library;
Commands :
A) select title from Wrok where(Price between 100 and 300);

B) select title,author from Wrok where subject = 'PROG' and


publisher = 'BPB';

C) select title from Wrok where price > 130 order by quantity;

D) select title from Wrok where price > 130 order by quantity;
E) select publisher, sum(quantity) as total_books from Wrok group
by publisher;

F) insert into Wrok(no, title, author, subject, publisher, quantity,


price) values (11, 'computer sc.', 'r.k.', 'bpb', 2, 250);

G) i. select min(price) from Wrok;

ii. select sum(price*quantity) from Wrok where quantity > 3 ;

iii. select avg(price) from Wrok where quantity<4 ;


iv. select count(distinct publisher) from Wrok;

24. Write the SQL commands for the following:

a. display data for all customers whose transactions are between 8 and 11
b. display data for all customers sorted by their dtofopen
c. to count the number of customers with amount<30000
d. list the minimum and maximum amount from the bank
e. to list custname,bank name, amount for all the clients whose amount
<20000
f. to display accno, custname,bankname, total trans in descending order
of amount
g. give the output:
i. select avg(amount) from bank where amount<23000 ;
ii. select max(amount) from bank where amount>30000 ;
iii. select sum(totaltrans) from bank ;
iv. select count(distinct bankname) from bank;
Commands :
A) select * from bank where totaltrans > 8 and totaltrans < 11;

B) select * from bank order by dtfopen;

C) select count(*) from bank where amount > 30000;

D) select min(amount),max(amount) from bank;


E) select custname, bankname, amount from bank where amount <
20000;

F) select accno, custname, bankname, totaltrans from bank order by


amount desc;

G) i. select avg(amount) from bank where amount<23000 ;

ii. select max(amount) from bank where amount>30000 ;

iii. select sum(totaltrans) from bank ;


iv. select count(distinct bankname) from bank;

25. Consider the following table FLIGHT and FARES. Write the SQL
commands for the statements (i) to (iv) and output from (v) to (viii).

a. Display Flight No, No of Flights arriving to the DELHI


b. Display all the airlines that have maximum no of flights.
c. Display total fare of all the airlines.
d. To display departure and arrival points of flight no 1C302 and MU499.
e.Give the Output:
i. SELECT COUNT(DISTINCT FL_NO) FROM FLIGHT;
ii. SELECT MIN(NOOFSTOPS) FROM FLIGHT WHERE FL_NO =
‘IC899’;
iii. SELECT AVG(FARE) FROM FARE WHRE AIRLINES = ‘Indian
Airlines’;
iv. SELECT FL_NO, NO_FLIGHTS FROM FLIGHT WHERE
DEPARTURE=’MUMBAI’;
Commands :
A) select fl_no, no_flights from flight where arrival = 'DELHI';

B) select AIRLINES, count(AIRLINES) as value_count from FARE


group by AIRLINES order by value_count desc limit 1;

C) select AIRLINES, sum(FARE) as total_fare from FARE group by


AIRLINES;

D) select NO_FLIGHTS, DEPARTURE, ARRIVAL from FLIGHT


where NO_FLIGHTS in ('1C302', 'MU499');
E) i. SELECT COUNT(DISTINCT FL_NO) FROM FLIGHT;

ii. SELECT MIN(NOOFSTOPS) FROM FLIGHT WHERE FL_NO =


“IC899”;

iii. SELECT AVG(FARE) FROM FARE WHERE AIRLINES =


“Indian Airlines”;

iv. SELECT FL_NO, NO_FLIGHTS FROM FLIGHT WHERE


DEPARTURE=”MUMBA”’;

26. Consider the following tables CUSTOMER and MOBILE. Write SQL
commands for the statements (i) to (iv) and give outputs for SQL queries
(v) to (viii)
a. To display the records of those customer who take the connection of
Bsnl and Airtel in ascending order of Activation date.
b.To decrease the amount of all customers of Reliance connection by
500. c. Count the no. of companies giving connection from CUSTOMER
table whose name starts with ‘P’.
d. To display the ID and Cname from table Customer and Make from
table Mobile, with their corresponding matching ID.
e. Give Output:
i. select Cname , Make form Customer, Mobile where Customer.ID =
Mobile.ID;
ii. select Connection , sum(Amount) from Customer group by
Connection ;
iii. SELECT COUNT(DISTINCT Make) FROM Mobile; .
iv. SELECT AVG(Amount) FROM Customer where Validity >= 180;
Commands :
A) SELECT * FROM CUSTOMER WHERE Connection IN ('Bsnl',
'Airtel') ORDER BY Activation_date ASC;

B) UPDATE CUSTOMER SET Amount = Amount - 500 WHERE


Connection = 'Reliance';
C) SELECT COUNT(DISTINCT Connection) AS CompanyCount
FROM CUSTOMER WHERE Cname LIKE 'P%';

D) SELECT c.ID, c.Cname, m.Make FROM CUSTOMER c INNER


JOIN MOBILE m ON c.ID = m.ID;

E) i. select Cname , Make form Customer, Mobile where Customer.ID


= Mobile.ID;
ii. select Connection , sum(Amount) from Customer group by
Connection ;

iii. SELECT COUNT(DISTINCT Make) FROM Mobile;

iv. SELECT AVG(Amount) FROM Customer where Validity >=


180;

● SQL Connectivity
27. Write a small python program to insert a record in the table books
with attributes (Name, AdmissionNo).
Source Code :
import mysql.connector

conn = mysql.connector.connect(
host="localhost",
user="pranay",
password="149771",
database="prac_db"
)
cursor = conn.cursor()
cursor.execute("INSERT INTO books (Name, AdmissionNo) VALUES (%s, %s)",
("Python Programming", "12345"))
conn.commit()
conn.close()
Output :

28. Write a small python program to connect with MySQL and show the
name of the all the record from the table “semester” from the database
“college”.
Source Code :
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="pranay",
password="149771",
database="prac_db")
cursor = conn.cursor()
cursor.execute("INSERT INTO books (Name, AdmissionNo) VALUES (%s, %s)",
("Python Programming", "12345"))
conn.commit()
conn.close()
Output :

29. Write the Python code to update a record in the student table

Source Code :

import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="pranay",
password="149771",
database="prac_db"
)
cursor = conn.cursor()
cursor.execute("UPDATE STUDENT SET Name = 'ANJU' WHERE EMP_NO =
'2'")
conn.commit()
print("Record updated successfully.")
conn.close()
Output :

30. Write the Python code to delete a record from the student table.
Source Code :
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="pranay",
password="149771",
database="prac_db"
)
cursor = conn.cursor()
cursor.execute("DELETE FROM STUDENT WHERE EMP_NO = '3'")
conn.commit()
print("Record deleted successfully.")
conn.close()
Output :

You might also like