CBSE 2026
Important CS Programs
Master your practical exams with our curated list of essential Python and SQL programs for Class 12. Click on any question to view the code, copy it, or run it instantly.
Python 3
def greet():
print("Hello, Student!")
print("Welcome to Python Functions.")
# Function Call
greet()
Python 3
def add_numbers(a, b):
sum_val = a + b
print("The sum is:", sum_val)
# Passing arguments 10 and 20
add_numbers(10, 20)
Python 3
def square(num):
return num * num
result = square(5)
print("Square of 5 is:", result)
Python 3
def arithmetic(a, b):
add = a + b
sub = a - b
return add, sub
s, d = arithmetic(10, 5)
print("Sum:", s)
print("Difference:", d)
Python 3
def introduce(name, age):
print("Name:", name)
print("Age:", age)
# Order matters here
introduce("Rahul", 17)
Python 3
def introduce(name, age):
print("Name:", name)
print("Age:", age)
# Order does not matter
introduce(age=18, name="Simran")
Python 3
def greet(name, msg="Good Morning"):
print("Hello", name, msg)
greet("Amit") # Uses default msg
greet("Sita", "Good Night") # Overrides default
Python 3
def my_func():
x = 10 # Local variable
print("Inside:", x)
my_func()
# print(x) # This would cause an Error: name 'x' is not defined
Python 3
x = 50 # Global variable
def my_func():
print("Inside function:", x) # Accessing global
my_func()
print("Outside function:", x)
Python 3
count = 0
def increment():
global count # Declare we are using the global variable
count = count + 1
increment()
print("Count is now:", count)
Python 3
# abs(), len(), max() are built-in
print(abs(-10))
print(max(5, 10, 2))
print(len("Python"))
Python 3
import random
# Generates random integer between 1 and 6
dice = random.randint(1, 6)
print("You rolled:", dice)
Python 3
print("1. Program Start")
def func():
print("3. Inside Function")
print("2. Before Call")
func()
print("4. After Call")
Python 3
def display():
print("I return nothing")
result = display()
print("Result is:", result) # Output: None
Python 3
def append_item(my_list):
my_list.append(100)
data = [1, 2, 3]
append_item(data)
print("List outside:", data) # [1, 2, 3, 100]
Python 3
def change_val(x):
x = 100 # Creates a new local x
num = 5
change_val(num)
print("Num outside:", num) # Still 5
Python 3
try:
a = 10
b = 0
print(a / b)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
Python 3
try:
num = int(input("Enter a number: "))
print("You entered:", num)
except ValueError:
print("Invalid! Please enter digits only.")
Python 3
try:
a = int(input("Enter A: "))
b = int(input("Enter B: "))
print(a / b)
except ValueError:
print("Please enter integers.")
except ZeroDivisionError:
print("Divisor cannot be zero.")
Python 3
try:
# Some risky code
x = 1 / 0
except Exception as e:
print("Something went wrong:", e)
Python 3
try:
print("Trying code...")
# x = 1/0
except:
print("Error occurred")
finally:
print("This runs always (Cleanup).")
Python 3
try:
val = 10
except:
print("Error")
else:
print("No error occurred, success!")
Python 3
# 'w' mode creates/overwrites file
f = open("sample.txt", "w")
f.write("Hello World")
f.close() # Always close the file!
Python 3
with open("sample.txt", "w") as f:
f.write("Python is great.")
# File is closed automatically here
Python 3
with open("sample.txt", "r") as f:
content = f.read()
print(content)
Python 3
with open("sample.txt", "r") as f:
data = f.read(5) # Read first 5 chars
print(data)
Python 3
with open("sample.txt", "r") as f:
line1 = f.readline()
line2 = f.readline()
print("Line 1:", line1, end='')
print("Line 2:", line2, end='')
Python 3
with open("sample.txt", "r") as f:
lines = f.readlines()
print(lines) # Output: ['line1\n', 'line2\n']
Python 3
with open("sample.txt", "a") as f:
f.write("\nThis is a new line.")
Python 3
lines = ["Apple\n", "Banana\n", "Cherry\n"]
with open("fruits.txt", "w") as f:
f.writelines(lines)
Python 3
with open("fruits.txt", "r") as f:
for line in f:
print(line.strip()) # strip() removes newline char
Python 3
with open("sample.txt", "r") as f:
print("Start Pos:", f.tell())
f.read(5)
print("Current Pos:", f.tell())
f.seek(0) # Go back to start
print("Reset Pos:", f.tell())
Python 3
count = 0
with open("sample.txt", "r") as f:
data = f.read()
words = data.split()
count = len(words)
print("Total words:", count)
Python 3
count = 0
with open("sample.txt", "r") as f:
for line in f:
count += 1
print("Total lines:", count)
Python 3
with open("source.txt", "r") as f1:
with open("dest.txt", "w") as f2:
f2.write(f1.read())
print("File copied.")
Python 3
target = "the"
count = 0
with open("story.txt", "r") as f:
words = f.read().split()
for w in words:
if w.lower() == target:
count += 1
print("'the' appears:", count, "times")
Python 3
with open("story.txt", "r") as f:
for line in f:
if line.startswith("A"):
print(line)
Python 3
with open("data.txt", "r") as f:
lines = [line.rstrip() for line in f]
print(lines)
Python 3
f = open("log.txt", "w")
f.write("Critical Data")
f.flush() # Data is written even if file isn't closed yet
f.close()
Python 3
with open("data.txt", "r+") as f:
content = f.read()
f.write("New Data") # Appends to end if read() finished
Python 3
with open("data.txt", "w+") as f:
f.write("Fresh Start")
f.seek(0) # Go back to read what we wrote
print(f.read())
Python 3
import pickle
print("Pickle module imported.")
Python 3
import pickle
data = [10, 20, 30, 40]
# Use 'wb' for write binary
with open("list.dat", "wb") as f:
pickle.dump(data, f)
print("List dumped.")
Python 3
import pickle
# Use 'rb' for read binary
with open("list.dat", "rb") as f:
data = pickle.load(f)
print("Loaded data:", data)
Python 3
import pickle
f = open("students.dat", "wb")
while True:
r = int(input("Roll: "))
n = input("Name: ")
stu = {"Roll": r, "Name": n}
pickle.dump(stu, f)
ans = input("More? (y/n): ")
if ans == 'n': break
f.close()
Python 3
import pickle
f = open("students.dat", "rb")
try:
while True:
stu = pickle.load(f)
print(stu)
except EOFError:
print("End of file reached.")
f.close()
Python 3
import pickle
# 'ab' stands for Append Binary
with open("students.dat", "ab") as f:
stu = {"Roll": 99, "Name": "New Student"}
pickle.dump(stu, f)
Python 3
import pickle
search_roll = 2
found = False
f = open("students.dat", "rb")
try:
while True:
s = pickle.load(f)
if s["Roll"] == search_roll:
print("Found:", s)
found = True
except EOFError:
pass
f.close()
Python 3
import pickle
all_data = []
# 1. Read all
with open("students.dat", "rb") as f:
try:
while True:
all_data.append(pickle.load(f))
except EOFError: pass
# 2. Modify in memory
for s in all_data:
if s["Roll"] == 1:
s["Name"] = "Updated Name"
# 3. Write back
with open("students.dat", "wb") as f:
for s in all_data:
pickle.dump(s, f)
Python 3
import pickle
count = 0
with open("students.dat", "rb") as f:
try:
while True:
pickle.load(f)
count += 1
except EOFError: pass
print("Total Records:", count)
Python 3
import csv
data = ["Roll", "Name", "Marks"]
with open("marks.csv", "w", newline="") as f:
w = csv.writer(f)
w.writerow(data) # Write header
w.writerow([1, "Amit", 90])
Python 3
import csv
rows = [
[2, "Sumit", 85],
[3, "Tina", 95]
]
with open("marks.csv", "a", newline="") as f:
w = csv.writer(f)
w.writerows(rows)
Python 3
import csv
with open("marks.csv", "r") as f:
r = csv.reader(f)
for row in r:
print(row) # row is a list of strings
Python 3
import csv
with open("data.csv", "r") as f:
r = csv.reader(f, delimiter='|')
for row in r:
print(row)
Python 3
import csv
target_roll = "2" # CSV data is string
with open("marks.csv", "r") as f:
r = csv.reader(f)
for row in r:
if row[0] == target_roll:
print("Found:", row)
Python 3
stack = []
def push(stk, item):
stk.append(item)
print(item, "pushed.")
push(stack, 10)
push(stack, 20)
print(stack) # [10, 20]
Python 3
def pop(stk):
if len(stk) == 0:
return "Underflow! Stack is empty."
else:
return stk.pop()
s = [10, 20]
print(pop(s)) # 20
print(pop(s)) # 10
print(pop(s)) # Underflow
Python 3
def peek(stk):
if not stk:
return "Empty"
else:
return stk[-1] # Last element
s = [5, 10, 15]
print("Top element:", peek(s))
Python 3
def display(stk):
if not stk:
print("Empty Stack")
else:
# Loop backwards
for i in range(len(stk)-1, -1, -1):
print(stk[i])
s = [1, 2, 3]
display(s)
Python 3
stack = []
while True:
print("\n1. Push 2. Pop 3. Display 4. Exit")
ch = int(input("Choice: "))
if ch == 1:
v = int(input("Val: "))
stack.append(v)
elif ch == 2:
if not stack: print("Underflow")
else: print("Popped:", stack.pop())
elif ch == 3:
print(stack[::-1])
elif ch == 4:
break
Python 3
with open("sample.txt", "r") as f:
f.seek(5) # Skip first 5 bytes
data = f.read(3) # Read next 3 bytes
print(data)
Python 3
f = open("image.jpg", "rb")
f.seek(0, 2) # Move to end (2 means end relative to 0)
size = f.tell()
print("Size in bytes:", size)
f.close()
Python 3
string = "Hello"
stack = []
for char in string:
stack.append(char)
rev = ""
while stack:
rev += stack.pop()
print("Reversed:", rev)
Python 3
try:
print("Outer Try")
try:
val = int("abc")
except ValueError:
print("Inner Catch: Value Error")
except:
print("Outer Catch")
Python 3
square = lambda x: x * x
print(square(5))
Python 3
import csv
data = {"Name": "Ali", "Age": 17}
with open("names.csv", "w", newline="") as f:
fields = ["Name", "Age"]
w = csv.DictWriter(f, fieldnames=fields)
w.writeheader()
w.writerow(data)
Python 3
with open("img.png", "rb") as f1:
with open("copy.png", "wb") as f2:
f2.write(f1.read())
Python 3
def shout(text):
return text.upper()
yell = shout
print(yell("hello"))
Python 3
def divide(a, b):
assert b != 0, "Divisor cannot be zero"
return a / b
print(divide(10, 2))
# print(divide(10, 0)) # Raises AssertionError
Python 3
text_var = ""
with open("poem.txt", "r") as f:
text_var = f.read()
print(text_var)
Python 3
count = 0
with open("data.txt", "r") as f:
text = f.read()
for char in text:
if char.isupper():
count += 1
print("Uppercase count:", count)
Python 3
def area(r):
"""Calculates area of circle."""
return 3.14 * r * r
print(area.__doc__)
Python 3
def future_feature():
pass # To be implemented later
future_feature()
Python 3
# Windows example path
path = "C:\\Users\\Student\\Desktop\\file.txt"
# f = open(path, "r")
print("Use double backslash in paths.")
Python 3
import os
if os.path.exists("sample.txt"):
print("File exists")
else:
print("File not found")
Python 3
import os
# os.remove("useless.txt")
print("Code commented for safety")
Python 3
import os
# os.rename("old.txt", "new.txt")
print("Renaming logic")
Python 3
import pickle
x = 999
with open("int.dat", "wb") as f:
pickle.dump(x, f)
Python 3
def add_all(*args):
return sum(args)
print(add_all(1, 2, 3, 4))
Python 3
s = []
if len(s) == 0:
print("Stack Empty")