Practical File Questions
Practical File Questions
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 :
reverse()
Output :
Output :
interchange()
Output :
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", ""))
Output :
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
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()
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")
Output :
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
write_records("student.dat")
search_rollno = int(input("Enter roll number to search for: "))
search_record("student.dat", search_rollno)
Output :
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 :
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)
while True:
add_contents("EMP.dat")
if input("Add another record? (y/n): ").strip().lower() != 'y':
break
● 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 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")
19. Write a program to display unique vowels present in the given word
using Stack.
Source Code :
def create_stack():
return []
def display(stack):
return stack
def unique_vowels(word):
vowels = "aeiou"
stack = create_stack()
unique_vowels = set()
return display(stack)
# Example usage
word = input("Enter a word: ").lower()
result = unique_vowels(word)
print("Unique vowels in the word:", " ".join(result))
Output :
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 = []
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.")
● 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.
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);
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;
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;
25. Consider the following table FLIGHT and FARES. Write the SQL
commands for the statements (i) to (iv) and output from (v) to (viii).
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;
● 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 :