Class 12 CS Code 083 Python Solved Practical File Programs

Get ready for your Class 12 Computer Science (Code 083) practical exams with our collection of Python Solved Practical File Programs. This resource includes a complete set of Python programs as per the latest CBSE guidelines, covering important topics like file handling, functions, data structures (lists, stacks, queues), and database connectivity using MySQL. Each program is explained with proper code, logic, and output to help you understand and learn effectively. Ideal for preparing your practical file, revising key concepts, and practicing for lab assessments, this collection ensures that you are fully prepared to perform confidently in your practical exams. Download the PDF and complete your practical file with ease.

Program 1: Write a program that counts vowels, consonents, uppercase and lowercase characters in a file.

def fileCount (filename):
	f open (filename, 'r')
	content f.read()
	countVowels = 0
	countConsonants = 0
	countUppercase = 0
	count Lowercase = 0
	print (content)
	for ch in content:
		if ch.isalpha():
			if ch in "aeiouAEIOU":
				countVowels += 1
			else:
				countConsonants += 1
			if ch.islower():
				countLowercase += 1
			else:
				countUppercase += 1
	print ("The number of vowels are:", count Vowels)
	print ("The number of consonants are: ", countConsonants)
	print ("The number of uppercase characters are:", countUppercase)
	print ("The number of lowercase characters are", countLowercase)
	f.close()
filename = input('Enter the filename: ')
fileCount (filename)

Program 2: Write a program to create a csv file by adding user id and password. It should also allow user to read and search the password for a user ID.

import csv
def enterData():
ch = 'y'
f = open("user.csv","a", newline="")
csvwriter cav.writer(۴)
while ch 'y':
	userld input ("Enter User Id: ")
	passwrd input ("Enter password: ")
	data [userId, passwrd)
	csvwriter.writerow(data)
	chinput ("Do you wish to enter more: ")
	if ch!'y':
	break
f.close()

enterData()
def searchData():
print(" Searching Data ")
userid input ("Enter the user id to be searched")
f = open("user.csv","r", newline="")
cnt = 0
datal cav.reader(f)
for r in datal:
	if 101 userld:
	print("The password for user id ", r[0], "is: ",r[1])
	cnt = 1
	break
If ent 0:
	print("Record not found")
f.closet)
searchData()

Program 3: Write a program that accepts a digit as an input from the user. If the digit is a positive number (1-9), then display it in words; otherwise, display the message, “Error: A positive digit is expected and less than 10”

# Dictionary to map digits to words
digit_words = {
    1: "One",
    2: "Two",
    3: "Three",
    4: "Four",
    5: "Five",
    6: "Six",
    7: "Seven",
    8: "Eight",
    9: "Nine"
}

# Accept input from user
try:
    digit = int(input("Enter a digit (1-9): "))

    if 1 <= digit <= 9:
        print("Digit in words:", digit_words[digit])
    else:
        print("Error: A positive digit is expected and less than 10")

except ValueError:
    print("Error: Please enter a valid integer digit")

Program 4: Write a program that accepts a number, n and displays the following pattern.
*
**
***
****
*****

n = int(input("Enter the number of rows: "))

for i in range(1, n + 1):
    print('*' * i)

Program 5: Write a program to accept a positive integer (n) and a floating point number (x) print sum of the following series:
x/1!+x2/2!+x3/3!+…+xn/n!
The program should keep adding the terms until the absolute difference between the two consecutive terms becomes less than 0.001

import math

# Input
n = int(input("Enter a positive integer (n): "))
x = float(input("Enter a floating point number (x): "))

sum_series = 0.0
prev_term = 0.0
i = 1

while i <= n:
    current_term = (x ** i) / math.factorial(i)
    sum_series += current_term
    
    if abs(current_term - prev_term) < 0.001:
        break

    prev_term = current_term
    i += 1

print("Sum of the series is:", round(sum_series, 4))

Program 6: Write a program to accept a decimal number and display its binary equivalent.

# Accept decimal number from user
try:
    decimal = int(input("Enter a decimal number: "))
    
    # Convert to binary using bin() and strip the '0b' prefix
    binary = bin(decimal)[2:]
    
    print("Binary equivalent is:", binary)

except ValueError:
    print("Error: Please enter a valid integer")

Program 7: Write a program to accept a positive integer (n) and a floating point number (x) print sum append: (Assume n<=10.)
x/1!+x2/2!+x3/3!+...+xn/n!

import math

# Input
n = int(input("Enter a positive integer (n ≤ 10): "))
x = float(input("Enter a floating point number (x): "))

sum_series = 0.0

for i in range(1, n + 1):
    power = 2 if i % 2 != 0 else 3  # alternate powers 2 and 3
    term = (x ** power) / math.factorial(i)
    sum_series += term

print("Sum of the series is:", round(sum_series, 4))

Program 8: Write a program that reads the test file myFile.txt and counts the number of words that end with a period (‘.’).

# Open and read the file
try:
    with open("myFile.txt", "r") as file:
        text = file.read()
        
        # Split the text into words
        words = text.split()
        
        # Count words that end with a period
        count = 0
        for word in words:
            if word.endswith('.'):
                count += 1

        print("Number of words ending with a period ('.'):", count)

except FileNotFoundError:
    print("Error: The file 'myFile.txt' was not found.")

Program 9: Write a program that removes all the lines that contain the character ‘a’ from a text file and writes it to another file.

# File names
input_file = "input.txt"
output_file = "output.txt"

try:
    # Open the input file in read mode and output file in write mode
    with open(input_file, "r") as infile, open(output_file, "w") as outfile:
        for line in infile:
            if 'a' not in line:  # Only write lines that don't contain 'a'
                outfile.write(line)

    print(f"Lines without 'a' have been written to '{output_file}'.")

except FileNotFoundError:
    print(f"Error: The file '{input_file}' was not found.")

Program 10: A binary file stores data of items in the form of dictionary objects as shown below:
Data = {ItemCode:[name,price]}
Write a menu driven program to add and display data to the binary file.

import pickle
import os

FILENAME = "items.dat"

def add_item():
    item_code = input("Enter Item Code: ")
    name = input("Enter Item Name: ")
    price = float(input("Enter Item Price: "))

    data = {item_code: [name, price]}

    # Append data to the binary file
    with open(FILENAME, "ab") as file:
        pickle.dump(data, file)
    print("Item added successfully.\n")

def display_items():
    if not os.path.exists(FILENAME):
        print("No data found. Add some items first.\n")
        return

    print("Items in the file:\n")
    with open(FILENAME, "rb") as file:
        try:
            while True:
                data = pickle.load(file)
                for code, details in data.items():
                    print(f"Item Code: {code}, Name: {details[0]}, Price: {details[1]}")
        except EOFError:
            pass
    print()

def menu():
    while True:
        print("=== Item Data Manager ===")
        print("1. Add Item")
        print("2. Display Items")
        print("3. Exit")
        choice = input("Enter your choice (1/2/3): ")

        if choice == '1':
            add_item()
        elif choice == '2':
            display_items()
        elif choice == '3':
            print("Exiting program.")
            break
        else:
            print("Invalid choice. Please try again.\n")

# Run the menu
menu()

Program 11: Write a program that accepts a string, and forms a new string that contains only three lettered words, with space between each word. Display both strings.

# Accept input string from the user
input_string = input("Enter a sentence: ")

# Split the string into words
words = input_string.split()

# Filter words with exactly 3 letters
three_letter_words = [word for word in words if len(word) == 3]

# Form a new string
new_string = ' '.join(three_letter_words)

# Display both strings
print("Original String: ", input_string)
print("New String with three-lettered words: ", new_string)

Program 12: Write a program to accept two numbers and print all prime numbers between those two numbers.

def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            return False
    return True

# Accept input from the user
start = int(input("Enter the first number: "))
end = int(input("Enter the second number: "))

# Ensure start is less than or equal to end
if start > end:
    start, end = end, start

print(f"Prime numbers between {start} and {end} are:")

for num in range(start, end + 1):
    if is_prime(num):
        print(num, end=' ')

Program 13: Write a function that reads a csv file, userData.csv, that stores user id and password of students in the form of list objects. The functions should display only those records whose user id ends with the digit.

Program 14: Write a program that create sub binary file with name and rollno. It should also allow you to search for a given roll number and display the name; if not found, display the appropriate message.

import pickle

filename = "students.dat"

def add_records():
    records = []
    n = int(input("How many records do you want to add? "))
    for _ in range(n):
        rollno = input("Enter roll number: ")
        name = input("Enter name: ")
        records.append({'rollno': rollno, 'name': name})
    
    # Write records to binary file
    with open(filename, 'wb') as file:
        pickle.dump(records, file)
    print(f"{n} records added successfully.\n")

def search_rollno():
    rollno_to_search = input("Enter roll number to search: ")
    try:
        with open(filename, 'rb') as file:
            records = pickle.load(file)
        for record in records:
            if record['rollno'] == rollno_to_search:
                print(f"Name corresponding to roll number {rollno_to_search} is {record['name']}.")
                return
        print(f"Roll number {rollno_to_search} not found.")
    except FileNotFoundError:
        print("No records found. Please add records first.")

def menu():
    while True:
        print("\nMenu:")
        print("1. Add Records")
        print("2. Search by Roll Number")
        print("3. Exit")
        choice = input("Enter your choice (1-3): ")
        
        if choice == '1':
            add_records()
        elif choice == '2':
            search_rollno()
        elif choice == '3':
            print("Exiting program.")
            break
        else:
            print("Invalid choice! Please try again.")

# Run the program
menu()

Program 15: Write a function in Python that takes a list as an argument and display the square of even numbers and square roots of odd numbers separately. For example, if the list is.
L=[4,49,10,2,25]
The output should be:

import math

def process_list(numbers):
    even_squares = []
    odd_roots = []

    for num in numbers:
        if num % 2 == 0:
            even_squares.append(num ** 2)
        else:
            odd_roots.append(round(math.sqrt(num), 2))  # rounded to 2 decimal places

    print("Squares of even numbers:", even_squares)
    print("Square roots of odd numbers:", odd_roots)

# Example usage
L = [4, 49, 10, 2, 25]
process_list(L)

Program 16: Write a program to implement a stack using list.

stack = []

def push():
    element = input("Enter element to push: ")
    stack.append(element)
    print(f"{element} pushed to stack.")

def pop():
    if len(stack) == 0:
        print("Stack is empty. Nothing to pop.")
    else:
        removed = stack.pop()
        print(f"Popped element: {removed}")

def display():
    if len(stack) == 0:
        print("Stack is empty.")
    else:
        print("Stack elements (top to bottom):")
        for elem in reversed(stack):
            print(elem)

def menu():
    while True:
        print("\nStack Operations Menu:")
        print("1. Push")
        print("2. Pop")
        print("3. Display")
        print("4. Exit")
        choice = input("Enter your choice (1-4): ")

        if choice == '1':
            push()
        elif choice == '2':
            pop()
        elif choice == '3':
            display()
        elif choice == '4':
            print("Exiting program.")
            break
        else:
            print("Invalid choice! Please enter a number between 1 and 4.")

# Run the program
menu()

Program 17: Write a program that accepts 10 numbers and adds them to a list. Thereafter, it displays the following menu:
1. Sort in ascending order
2. Sort in descending order
3. Largest number
4. Smallest number
5. Exit

stack = []

# Function to push elements onto the stack
def push_elements():
    n = int(input("How many elements do you want to push onto the stack? "))
    for _ in range(n):
        num = int(input("Enter a number: "))
        stack.append(num)
    print("Elements pushed to stack.\n")

def display_stack():
    if stack:
        print("Current stack (top -> bottom):", stack[::-1])
    else:
        print("Stack is empty.")

def sort_ascending():
    stack.sort()
    print("Stack sorted in ascending order.")

def sort_descending():
    stack.sort(reverse=True)
    print("Stack sorted in descending order.")

def largest_number():
    if stack:
        print("Largest number in the stack:", max(stack))
    else:
        print("Stack is empty.")

def smallest_number():
    if stack:
        print("Smallest number in the stack:", min(stack))
    else:
        print("Stack is empty.")

def menu():
    push_elements()
    while True:
        print("\nMenu:")
        print("1. Sort in ascending order")
        print("2. Sort in descending order")
        print("3. Largest number")
        print("4. Smallest number")
        print("5. Exit")
        choice = input("Enter your choice (1-5): ")

        if choice == '1':
            sort_ascending()
            display_stack()
        elif choice == '2':
            sort_descending()
            display_stack()
        elif choice == '3':
            largest_number()
        elif choice == '4':
            smallest_number()
        elif choice == '5':
            print("Exiting program.")
            break
        else:
            print("Invalid choice, please try again.")

# Run the menu
menu()

Program 18: Write a program that accept three colours from the user. If the user enters orange, red and green, respectively the message “Indian Flag” is displayed, otherwise, the message “ExamsMantra” is displayed.

# Accept three colors from the user
color1 = input("Enter first color: ").strip().lower()
color2 = input("Enter second color: ").strip().lower()
color3 = input("Enter third color: ").strip().lower()

# Check the colors and display message
if color1 == "orange" and color2 == "red" and color3 == "green":
    print("Indian Flag")
else:
    print("ExamsMantra")

Program 19: Write a program to check whether a number is palindrome or not.

# Accept number as input
num = input("Enter a number: ")

# Check if the number is palindrome
if num == num[::-1]:
    print(f"{num} is a palindrome.")
else:
    print(f"{num} is not a palindrome.")

Program 20: Write a program that reads a text file line by line and displays each words separated by a #.

filename = "myFile.txt"  # Change the filename as needed

try:
    with open(filename, 'r') as file:
        for line in file:
            words = line.strip().split()
            print('#'.join(words))
except FileNotFoundError:
    print(f"The file '{filename}' does not exist.")

Program 21: Write a program to accept a number and print sum of following series.
1/1! + 2/2! + 3/3! ... n/n!

import math

# Accept input from user
n = int(input("Enter a positive integer n: "))

sum_series = 0.0

for i in range(1, n + 1):
    term = i / math.factorial(i)
    sum_series += term

print(f"Sum of the series is: {sum_series}")

Program 22: Write a program that accept a number and displays sum of squares of all even numbers till that number.

# Accept number from the user
n = int(input("Enter a number: "))

# Initialize sum
sum_squares = 0

# Loop through numbers from 2 to n
for num in range(2, n + 1, 2):  # step 2 to consider only even numbers
    sum_squares += num ** 2

# Display the result
print(f"Sum of squares of all even numbers till {n} is: {sum_squares}")

Program 23: Write a random number generator that generates a random number between 1 and 6.

import random

random_number = random.randint(1, 6)
print("Random number between 1 and 6:", random_number)

Program 24: Write a menu driven program to save, display and search records using a csv file, furniture.csv that uses a list object to store following data:
furnitureId > int
fName > string
price > float

The program should also have an option to search for a record based on furnitureId.

import csv
import os

FILENAME = "furniture.csv"

def save_record():
    furnitureId = int(input("Enter Furniture ID: "))
    fName = input("Enter Furniture Name: ")
    price = float(input("Enter Price: "))
    
    with open(FILENAME, "a", newline='') as file:
        writer = csv.writer(file)
        writer.writerow([furnitureId, fName, price])
    
    print("Record saved successfully.\n")

def display_records():
    if not os.path.exists(FILENAME):
        print("No records found.\n")
        return
    
    print("\nFurniture Records:")
    with open(FILENAME, "r") as file:
        reader = csv.reader(file)
        found = False
        for row in reader:
            if row:  # Avoid blank lines
                print(f"Furniture ID: {row[0]}, Name: {row[1]}, Price: {row[2]}")
                found = True
        if not found:
            print("No records found.\n")
    print()

def search_record():
    if not os.path.exists(FILENAME):
        print("No records to search.\n")
        return
    
    search_id = input("Enter Furniture ID to search: ")
    found = False
    
    with open(FILENAME, "r") as file:
        reader = csv.reader(file)
        for row in reader:
            if row and row[0] == search_id:
                print(f"Record Found - Furniture ID: {row[0]}, Name: {row[1]}, Price: {row[2]}\n")
                found = True
                break
    if not found:
        print("Record not found.\n")

def menu():
    while True:
        print("=== Furniture Record Menu ===")
        print("1. Save Record")
        print("2. Display All Records")
        print("3. Search by Furniture ID")
        print("4. Exit")
        choice = input("Enter your choice (1-4): ")

        if choice == '1':
            save_record()
        elif choice == '2':
            display_records()
        elif choice == '3':
            search_record()
        elif choice == '4':
            print("Exiting program.")
            break
        else:
            print("Invalid choice. Try again.\n")

# Run the program
menu()

Program 25: Write a program to create a binary file with rollno, name and marks. It should also allow you to input a roll number and update the marks.

import pickle
import os

FILENAME = "students.dat"

def add_student():
    rollno = int(input("Enter Roll Number: "))
    name = input("Enter Name: ")
    marks = float(input("Enter Marks: "))
    record = {'rollno': rollno, 'name': name, 'marks': marks}

    # Append the record to the binary file
    with open(FILENAME, "ab") as file:
        pickle.dump(record, file)
    print("Student record added successfully.\n")

def update_marks():
    found = False
    rollno_to_update = int(input("Enter roll number to update marks: "))
    updated_records = []

    try:
        # Read all records
        with open(FILENAME, "rb") as file:
            while True:
                try:
                    record = pickle.load(file)
                    if record['rollno'] == rollno_to_update:
                        new_marks = float(input(f"Enter new marks for {record['name']}: "))
                        record['marks'] = new_marks
                        found = True
                    updated_records.append(record)
                except EOFError:
                    break

        # Write all updated records back to the file
        if found:
            with open(FILENAME, "wb") as file:
                for record in updated_records:
                    pickle.dump(record, file)
            print("Marks updated successfully.\n")
        else:
            print("Roll number not found.\n")
    except FileNotFoundError:
        print("Student file not found.\n")

def display_all():
    print("Student Records:")
    try:
        with open(FILENAME, "rb") as file:
            while True:
                try:
                    record = pickle.load(file)
                    print(f"Roll No: {record['rollno']}, Name: {record['name']}, Marks: {record['marks']}")
                except EOFError:
                    break
    except FileNotFoundError:
        print("No records to display.\n")

# Menu
def menu():
    while True:
        print("=== Student Record System ===")
        print("1. Add Student")
        print("2. Update Marks")
        print("3. Display All")
        print("4. Exit")
        choice = input("Enter your choice (1-4): ")

        if choice == '1':
            add_student()
        elif choice == '2':
            update_marks()
        elif choice == '3':
            display_all()
        elif choice == '4':
            print("Exiting program.")
            break
        else:
            print("Invalid choice. Try again.\n")

# Run the menu
menu()

Program 26: Write a program to accept a string and output a tuple comprising the length of each word of the string. Finally, the program should display the tuple elements in ascending order. For example, if the string entered by the user is ‘Hello what do you want from me today’, then the program should produce the following output:
(5 4 2 3 4 4 2 5)
2 2 3 4 4 4 5 5

# Accept a string from the user
input_string = input("Enter a sentence: ")

# Split the string into words
words = input_string.split()

# Create a tuple of word lengths
lengths = tuple(len(word) for word in words)

# Display the tuple
print("Tuple of word lengths:", lengths)

# Display the sorted elements in ascending order
sorted_lengths = sorted(lengths)
print("Sorted lengths in ascending order:", *sorted_lengths)

Program 27: Write a user defined function that except a character as an argument, and returns 0 if it is a digit, 1 if it is an alphabet and 2 if it is a special character. Display appropriate message according to the values return by the function.

def classify_character(ch):
    if ch.isdigit():
        return 0
    elif ch.isalpha():
        return 1
    else:
        return 2

# Accept a single character from the user
char = input("Enter a single character: ")

# Check if the input is exactly one character
if len(char) != 1:
    print("Error: Please enter exactly one character.")
else:
    result = classify_character(char)

    if result == 0:
        print("The character is a digit.")
    elif result == 1:
        print("The character is an alphabet.")
    else:
        print("The character is a special character.")

Leave a Comment

© 2025 ExamsMantra.in All rights reserved.