0% found this document useful (0 votes)
24 views25 pages

Class12 Python Practice Questions Large

The document contains a series of Python practical questions and their corresponding solutions for Class 12 Computer Science. It covers various topics including list manipulation, file handling, CSV operations, and SQL commands. Each question is accompanied by sample code and expected output, demonstrating key programming concepts and functionalities.

Uploaded by

nitinkumar321555
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views25 pages

Class12 Python Practice Questions Large

The document contains a series of Python practical questions and their corresponding solutions for Class 12 Computer Science. It covers various topics including list manipulation, file handling, CSV operations, and SQL commands. Each question is accompanied by sample code and expected output, demonstrating key programming concepts and functionalities.

Uploaded by

nitinkumar321555
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Class 12 Computer Science — Python Practical Questions

Question 1
Write a Python function which accepts a list of numbers and a number to search. If the
number exists, it is replaced by zero. Otherwise, display an appropriate message.

Python Code:

def replace_number(lst, num):


if num in lst:
index = lst.index(num)
lst[index] = 0
print("Updated List:", lst)
else:
print("Number not found in the list!")

# Example
nums = [2, 5, 7, 10, 5]
search_num = int(input("Enter number to search: "))
replace_number(nums, search_num)

Sample Output:
Enter number to search: 5
Updated List: [2, 0, 7, 10, 5]
Question 2
Write a Python function to count and return the number of vowels in a given string entered
by the user.

Python Code:

def count_vowels(text):
vowels = 'aeiouAEIOU'
count = 0
for ch in text:
if ch in vowels:
count += 1
return count

string = input("Enter a string: ")


print("Total vowels:", count_vowels(string))

Sample Output:
Enter a string: Computer Science
Total vowels: 6
Question 3
Write a Python function that accepts a list of numbers and returns the average of even
numbers only.

Python Code:

def average_of_even(lst):
evens = [n for n in lst if n % 2 == 0]
if evens:
return sum(evens) / len(evens)
else:
return 0

nums = [10, 15, 20, 25, 30]


print("Average of even numbers:", average_of_even(nums))

Sample Output:
Average of even numbers: 20.0
Question 4
Write a Python function that accepts a string and displays the string in reverse order
without using slicing.

Python Code:

def reverse_string(s):
rev = ''
for ch in s:
rev = ch + rev
print("Reversed string:", rev)

text = input("Enter text: ")


reverse_string(text)

Sample Output:
Enter text: Python
Reversed string: nohtyP
Question 5
Write a Python program to create a binary file named 'students.dat' to store student roll
number and name using pickle.

Python Code:

import pickle

def write_data():
with open("students.dat", "ab") as f:
roll = int(input("Enter roll number: "))
name = input("Enter name: ")
record = [roll, name]
pickle.dump(record, f)
print("Record added successfully!")

write_data()

Sample Output:
Enter roll number: 101
Enter name: Ayush
Record added successfully!
Question 6
Write a Python program to read and display all student records from 'students.dat' binary
file.

Python Code:

import pickle

def read_data():
with open("students.dat", "rb") as f:
try:
while True:
record = pickle.load(f)
print(record)
except EOFError:
pass

read_data()

Sample Output:
[101, 'Ayush']
[102, 'Riya']
[103, 'Karan']
Question 7
Write a Python program to search for a student by roll number in 'students.dat'. Display
message if not found.

Python Code:

import pickle

def search_student(rno):
found = False
with open("students.dat", "rb") as f:
try:
while True:
rec = pickle.load(f)
if rec[0] == rno:
print("Record found:", rec)
found = True
except EOFError:
if not found:
print("Record not found.")

search_student(102)

Sample Output:
Record found: [102, 'Riya']
Question 8
Write a Python program to count and display total number of records in 'students.dat'
binary file.

Python Code:

import pickle

def count_records():
count = 0
with open("students.dat", "rb") as f:
try:
while True:
pickle.load(f)
count += 1
except EOFError:
pass
print("Total Records:", count)

count_records()

Sample Output:
Total Records: 3
Question 9
Raj is the manager of a medical store. To keep track of sales, he created a CSV file 'Sales.csv'
with columns: Product_ID, Product_Name, Quantity_Sold, Price_Per_Unit. Write a program
with functions: Accept() to add records, and CalculateTotalSales() to display total sales.

Python Code:

import csv

def Accept():
with open("Sales.csv", "a", newline="") as f:
w = csv.writer(f)
pid = input("Enter Product ID: ")
pname = input("Enter Product Name: ")
qty = int(input("Enter Quantity Sold: "))
price = float(input("Enter Price Per Unit: "))
w.writerow([pid, pname, qty, price])

def CalculateTotalSales():
total = 0
with open("Sales.csv", "r") as f:
r = csv.reader(f)
for rec in r:
total += int(rec[2]) * float(rec[3])
print("Total Sales:", total)

Accept()
CalculateTotalSales()

Sample Output:
Enter Product ID: P01
Enter Product Name: Paracetamol
Enter Quantity Sold: 5
Enter Price Per Unit: 20
Total Sales: 100.0
Question 10
A list containing records of products as

L = [("Laptop", 90000), ("Mobile", 30000), ("Pen", 50), ("Headphones", 1500)]

Write the following user-defined functions to perform operations on a stack named

Product to:

*Please note that the assessment scheme of the Academic Session 2024-25 will continue in
the current session i.e.

2025-26.

Page 5

I. Push_element() – To push an item containing the product name and price of

products costing more than 50 into the stack.

Output: [('Laptop', 90000), ('Mobile', 30000), ('Headphones', 1500)]

II. Pop_element() – To pop the items from the stack and display them. Also, display

"Stack Empty" when there are no elements in the stack.

Python Code:

# Program to perform stack operations on product list

L = [("Laptop", 90000), ("Mobile", 30000), ("Pen", 50), ("Headphones", 1500)]

Product = [] # Stack

def Push_element():

"""Push products costing more than 50 into stack"""

for item in L:

if item[1] > 50:


Product.append(item)

print("Stack after pushing:", Product)

def Pop_element():

"""Pop elements from stack and display"""

while Product:

print(Product.pop())

print("Stack Empty")

# Function calls

Push_element()

Pop_element()

Sample Output:
Stack after pushing: [('Laptop', 90000), ('Mobile', 30000), ('Headphones', 1500)]

('Headphones', 1500)

('Mobile', 30000)

('Laptop', 90000)

Stack Empty
Question 11
Write a Python program to count the total number of records in a CSV file named 'Sales.csv'.

Python Code:

import csv

with open("Sales.csv", "r") as f:


r = csv.reader(f)
count = sum(1 for _ in r)
print("Total records:", count)

Sample Output:
Total records: 3
Question 12
Write a Python program to search and display a product name entered by user from
'Sales.csv'.

Python Code:

import csv

search = input("Enter product name: ")


found = False
with open("Sales.csv", "r") as f:
r = csv.reader(f)
for row in r:
if row[1].lower() == search.lower():
print("Product found:", row)
found = True
if not found:
print("Product not found!")

Sample Output:
Enter product name: Paracetamol
Product found: ['P01', 'Paracetamol', '5', '20']
Question 13
Write a Python program to read a text file and display the total number of lines and words
in it.

Python Code:

f = open("story.txt", "r")
lines = f.readlines()
print("Total Lines:", len(lines))
count = 0
for line in lines:
count += len(line.split())
print("Total Words:", count)
f.close()

Sample Output:
Total Lines: 4
Total Words: 35
Question 14
Write a Python program to read a text file and display the number of times 'the' appears
(case insensitive).

Python Code:

f = open("data.txt", "r")
text = f.read().lower()
count = text.count("the")
print("Word 'the' occurs", count, "times")
f.close()

Sample Output:
Word 'the' occurs 5 times
Question 15
Write a Python program to read each character in a text file and display total number of
occurrences of letters 'a' and 'c' (case-insensitive).

Python Code:

f = open("sample.txt", "r")
text = f.read().lower()
a_count = text.count('a')
c_count = text.count('c')
print("Total 'a':", a_count)
print("Total 'c':", c_count)
f.close()

Sample Output:
Total 'a': 12
Total 'c': 7
Question 16
Write a Python program to copy contents from 'source.txt' to 'destination.txt'.

Python Code:

with open("source.txt", "r") as src:


with open("destination.txt", "w") as dest:
for line in src:
dest.write(line)
print("File copied successfully.")

Sample Output:
File copied successfully.
Question 17
Write SQL commands to create a table named EMPLOYEE with columns (EmpID, Name,
Department, Salary).

Python Code:

CREATE TABLE EMPLOYEE (


EmpID INT PRIMARY KEY,
Name VARCHAR(50),
Department VARCHAR(30),
Salary INT
);

Sample Output:
Table created successfully.
Question 18
Write SQL commands to insert 3 records into the EMPLOYEE table.

Python Code:

INSERT INTO EMPLOYEE VALUES (1, 'Ayush', 'HR', 30000);


INSERT INTO EMPLOYEE VALUES (2, 'Riya', 'IT', 40000);
INSERT INTO EMPLOYEE VALUES (3, 'Karan', 'Sales', 35000);

Sample Output:
3 rows inserted successfully.
Question 19
MySQL database named WarehouseDB has a product_inventory table in MySQL which

contains the following attributes:

• Item_code: Item code (Integer)

• Product_name: Name of product (String)

• Quantity: Quantity of product (Integer)

• Cost: Cost of product (Integer)

Consider the following details to establish Python-MySQL connectivity:

• Username: admin_user

• Password: warehouse2024

• Host: localhost

Write a Python program to change the Quantity of the product to 91 whose Item_code is

208 in the product_inventory table.

Python Code:

import mysql.connector

def update_quantity():

try:

# Step 1: Connect to MySQL database

mydb = mysql.connector.connect(

host="localhost",

user="admin_user",

password="warehouse2024",

database="WarehouseDB"

)
# Step 2: Create a cursor object

cursor = mydb.cursor()

# Step 3: Define the SQL UPDATE query

query = "UPDATE product_inventory SET Quantity = 91 WHERE Item_code = 208"

# Step 4: Execute the query

cursor.execute(query)

# Step 5: Commit the changes to make the update permanent

mydb.commit()

# Step 6: Check if any record was affected

if cursor.rowcount > 0:

print("Quantity updated successfully!")

else:

print("Item with Item_code 208 not found.")

except mysql.connector.Error as err:

print("Error:", err)

finally:

# Step 7: Close the connection

if mydb.is_connected():

cursor.close()
mydb.close()

print("MySQL connection closed.")

# Call the function

update_quantity()

Sample Output:
Quantity updated successfully!

MySQL connection closed.


Question 20
Write the definition of a user-defined function `push_even(N)` which

accepts a list of integers in a parameter `N` and pushes all those integers

which are even from the list `N` into a Stack named `EvenNumbers`.

Write function pop_even() to pop the topmost number from the stack and

returns it. If the stack is already empty, the function should display "Empty".

Write function Disp_even() to display all element of the stack without

deleting them. If the stack is empty, the function should display 'None'.
Python Code:

# Program to perform stack operations for even numbers

EvenNumbers = [] # Stack declaration

def push_even(N):

"""Pushes even numbers from list N into stack EvenNumbers"""

for num in N:

if num % 2 == 0:

EvenNumbers.append(num)

print("Stack after pushing even numbers:", EvenNumbers)

def pop_even():

"""Pops the topmost element from stack"""

if len(EvenNumbers) == 0:

print("Empty")

else:

print("Popped element:", EvenNumbers.pop())


def Disp_even():

"""Displays all elements of stack without deleting"""

if len(EvenNumbers) == 0:

print("None")

else:

print("Stack elements:", EvenNumbers)

# Example usage

nums = [23, 12, 45, 60, 71, 90]

push_even(nums)

Disp_even()

pop_even()

Disp_even()

Sample Output:
Stack after pushing even numbers: [12, 60, 90]

Stack elements: [12, 60, 90]

Popped element: 90

Stack elements: [12, 60]

You might also like