PYTHON PRACTICAL ASSIGNMENT
Complete Comprehensive Solutions, Complete Source Code, and Comprehensive Theory Answers
Question 1: Menu-Driven Character Analysis of String
Write a program to take a string from the user and print the following using independent functions and
string as the parameter (Menu Driven): (a) Number of capital letters, (b) Number of small letters, (c) Number
of spaces, (d) Number of vowels, (e) Number of digits.
Source Code:
def count_capitals(s):
count = sum(1 for ch in s if [Link]())
print(f"Number of capital letters: {count}")
def count_smalls(s):
count = sum(1 for ch in s if [Link]())
print(f"Number of small letters: {count}")
def count_spaces(s):
count = sum(1 for ch in s if [Link]())
print(f"Number of spaces: {count}")
def count_vowels(s):
vowels = "aeiouAEIOU"
count = sum(1 for ch in s if ch in vowels)
print(f"Number of vowels: {count}")
def count_digits(s):
count = sum(1 for ch in s if [Link]())
print(f"Number of digits: {count}")
def main():
user_string = input("Enter a string: ")
while True:
print("
--- STRING MENU ---")
print("1. Count Capital Letters")
print("2. Count Small Letters")
print("3. Count Spaces")
print("4. Count Vowels")
print("5. Count Digits")
print("6. Exit")
choice = input("Enter your choice (1-6): ")
if choice == '1': count_capitals(user_string)
elif choice == '2': count_smalls(user_string)
elif choice == '3': count_spaces(user_string)
elif choice == '4': count_vowels(user_string)
elif choice == '5': count_digits(user_string)
elif choice == '6': break
Computer Science Practical Assignment 1
else: print("Invalid choice! Please choose between 1 and 6.")
if __name__ == '__main__':
main()
Question 2: Menu-Driven List & Tuple Processing
Take a list of 10 numbers from the user and perform operations using independent functions for each: (a)
Sum of odd elements, (b) Square of smallest element, (c) Reverse order of input, (d) Generate a sorted Tuple
in descending order without altering the original list.
Source Code:
def sum_odd_elements(lst):
odd_sum = sum(x for x in lst if x % 2 != 0)
print(f"Sum of odd elements: {odd_sum}")
def square_of_smallest(lst):
smallest = min(lst)
print(f"Smallest element: {smallest}, Its square: {smallest ** 2}")
def print_reverse(lst):
print("Elements in reverse order:", lst[::-1])
def display_descending_tuple(lst):
sorted_lst = sorted(lst, reverse=True)
desc_tuple = tuple(sorted_lst)
print(f"Generated descending Tuple: {desc_tuple}")
print(f"Original list remains unaltered: {lst}")
def main():
print("Enter 10 numbers:")
numbers = []
for i in range(10):
num = int(input(f"Enter number {i+1}: "))
[Link](num)
while True:
print("
--- LIST MENU ---")
print("1. Sum of odd elements")
print("2. Square of the smallest element")
print("3. Print elements in reverse order")
print("4. Generate and display Tuple in descending order")
print("5. Exit")
choice = input("Enter your choice (1-5): ")
if choice == '1': sum_odd_elements(numbers)
elif choice == '2': square_of_smallest(numbers)
elif choice == '3': print_reverse(numbers)
elif choice == '4': display_descending_tuple(numbers)
elif choice == '5': break
Computer Science Practical Assignment 2
else: print("Invalid choice!")
if __name__ == '__main__':
main()
Question 3: Binary Serialization of Player Records
Create a function that takes a dictionary object of a Player (Name, Gender, Age, Game) and saves it to
[Link]. Create another function show() to display the details of female players only using a Menu-based
interface.
Source Code:
import pickle
import os
def save_player(player_dict):
with open("[Link]", "ab") as f:
[Link](player_dict, f)
print("Player record saved successfully.")
def show_female_players():
if not [Link]("[Link]"):
print("No records found ([Link] does not exist).")
return
print("
--- FEMALE PLAYER DETAILS ---")
count = 0
with open("[Link]", "rb") as f:
while True:
try:
player = [Link](f)
if [Link]('Gender', '').strip().lower() == 'female':
print(f"Name: {player['Name']}, Age: {player['Age']}, Game:
{player['Game']}")
count += 1
except EOFError:
break
if count == 0:
print("No female players found.")
def main():
while True:
print("
--- PLAYER RECORD SYSTEM ---")
print("1. Add Player Record")
print("2. Show Female Players Only")
print("3. Exit")
choice = input("Enter option (1-3): ")
if choice == '1':
Computer Science Practical Assignment 3
name = input("Enter Player Name: ")
gender = input("Enter Gender (Male/Female): ")
age = int(input("Enter Age: "))
game = input("Enter Game: ")
p_dict = {"Name": name, "Gender": gender, "Age": age, "Game": game}
save_player(p_dict)
elif choice == '2':
show_female_players()
elif choice == '3':
break
else:
print("Invalid input!")
if __name__ == '__main__':
main()
Question 4: Mathematical Operations & Number Analysis
Implement the following functions within a menu: (a) Show() to print the first 10 natural numbers, (b)
Prime() to generate and print a list of the first 10 prime numbers, (c) Check() which evaluates if a parameter
is an Armstrong number (returns 1 or 0).
Source Code:
def Show():
print("First 10 natural numbers:", list(range(1, 11)))
def Prime():
primes = []
num = 2
while len(primes) < 10:
is_prime = True
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
[Link](num)
num += 1
print("First 10 prime numbers:", primes)
def Check(n):
temp = n
digits = [int(d) for d in str(n)]
num_digits = len(digits)
# Armstrong formula implementation
cube_sum = sum(d ** 3 for d in digits)
return 1 if cube_sum == n else 0
def main():
while True:
print("
Computer Science Practical Assignment 4
--- MATH FUNCTIONS MENU ---")
print("1. Show First 10 Natural Numbers")
print("2. Generate First 10 Prime Numbers")
print("3. Check Armstrong Number")
print("4. Exit")
choice = input("Enter selection (1-4): ")
if choice == '1':
Show()
elif choice == '2':
Prime()
elif choice == '3':
num = int(input("Enter integer to check: "))
if Check(num) == 1:
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is NOT an Armstrong number.")
elif choice == '4':
break
else:
print("Invalid Choice!")
if __name__ == '__main__':
main()
Question 5: Advanced File-Based Text Manipulations
Write a program to process a text file named [Link] using distinct functions to: (a) Count total words, (b)
Interchange the first 3 characters of the text string with the last 3 characters, (c) Print alternate characters
from the text string.
Source Code:
import os
def create_sample_story():
with open("[Link]", "w") as f:
[Link]("A quick brown fox jumps over the lazy dog. Programming in Python is fun.")
def count_words():
if not [Link]("[Link]"): return
with open("[Link]", "r") as f:
content = [Link]()
words = [Link]()
print(f"Total number of words: {len(words)}")
def interchange_chars():
if not [Link]("[Link]"): return
with open("[Link]", "r") as f:
content = [Link]().strip()
if len(content) >= 6:
modified = content[-3:] + content[3:-3] + content[:3]
Computer Science Practical Assignment 5
print(f"Modified content string:
{modified}")
else:
print("String is too short to perform the interchange.")
def print_alternate():
if not [Link]("[Link]"): return
with open("[Link]", "r") as f:
content = [Link]()
print("Alternate characters from the text file:")
print(content[::2])
def main():
create_sample_story() # Ensure file exists for demonstration
while True:
print("
--- TEXT FILE PROCESSING MENU ---")
print("1. Count Words")
print("2. Interchange First 3 and Last 3 Characters")
print("3. Print Alternate Characters")
print("4. Exit")
choice = input("Enter choice: ")
if choice == '1': count_words()
elif choice == '2': interchange_chars()
elif choice == '3': print_alternate()
elif choice == '4': break
else: print("Invalid entry!")
if __name__ == '__main__':
main()
Question 6: Binary File Handling for Student Records
Create a binary file storing Roll Number (Rno), Name, and Marks of 3 subjects for 10 students. Write a
parsing function to calculate and print the total marks of each individual student along with the cumulative
total count of records stored in the file.
Source Code:
import pickle
def create_student_records():
# Simulating data insertion for 10 structural records
students_data = [
[101, "Amit", [85, 90, 88]], [102, "Siddharth", [78, 82, 80]],
[103, "Priya", [92, 95, 94]], [104, "Rohan", [65, 70, 72]],
[105, "Ananya", [88, 91, 89]], [106, "Rahul", [74, 76, 78]],
[107, "Neha", [90, 93, 91]], [108, "Vikram", [82, 85, 84]],
[109, "Sneha", [95, 97, 96]], [110, "Arjun", [60, 65, 68]]
]
with open("[Link]", "wb") as f:
for record in students_data:
Computer Science Practical Assignment 6
[Link](record, f)
print("Binary file '[Link]' initialized with 10 records.")
def display_student_report():
total_records = 0
print("
" + "="*45)
print(f"{'RNo':<6} {'Name':<15} {'Subject Marks':<15} {'Total':<6}")
print("="*45)
with open("[Link]", "rb") as f:
while True:
try:
rno, name, marks = [Link](f)
total_marks = sum(marks)
print(f"{rno:<6} {name:<15} {str(marks):<15} {total_marks:<6}")
total_records += 1
except EOFError:
break
print("="*45)
print(f"Total count of records in the file: {total_records}")
if __name__ == '__main__':
create_student_records()
display_student_report()
Question 7: CSV File Operations for Inventory Tracking
Write a program to generate a CSV file to manage store inventory records (ProductName, Price, Brand).
Provide functionality to parse and display items with a unit price exceeding 2,000 INR through a menu
interface.
Source Code:
import csv
import os
def initialize_stock():
records = [
["Laptop", 45000, "Dell"], ["Mouse", 800, "Logitech"],
["Keyboard", 1500, "HP"], ["Monitor", 12000, "Samsung"],
["USB Cable", 350, "Portronics"], ["Headphones", 2500, "Sony"]
]
with open("[Link]", "w", newline="") as f:
writer = [Link](f)
[Link](["ProductName", "Price", "Brand"])
[Link](records)
def display_high_value_stock():
if not [Link]("[Link]"): return
print("
--- PRODUCTS WITH PRICE > 2000 ---")
Computer Science Practical Assignment 7
print(f"{'Product Name':<15} {'Price':<10} {'Brand':<10}")
print("-"*38)
with open("[Link]", "r") as f:
reader = [Link](f)
header = next(reader) # skip headers
for row in reader:
if row:
name, price, brand = row[0], float(row[1]), row[2]
if price > 2000:
print(f"{name:<15} {price:<10.2f} {brand:<10}")
def main():
initialize_stock()
while True:
print("
--- INVENTORY SYSTEM ---")
print("1. Display Premium Stock (> 2000)")
print("2. Exit")
choice = input("Enter choice: ")
if choice == '1': display_high_value_stock()
elif choice == '2': break
if __name__ == '__main__':
main()
Question 8: CSV Grade-Based Record Filtering
Store 5 structural records in [Link] containing Name, Class, and Marks. Write a lookup function to filter
and display student details for individuals who scored greater than 90 marks.
Source Code:
import csv
def write_student_csv():
records = [
["Aarav", "12A", 95], ["Bhavna", "12B", 88],
["Charu", "12A", 92], ["Divya", "12C", 78], ["Eshwar", "12B", 91]
]
with open("[Link]", "w", newline="") as f:
writer = [Link](f)
[Link](["Name", "Class", "Marks"])
[Link](records)
print("[Link] generated successfully with 5 records.")
def display_excellent_students():
print("
--- STUDENTS SECURING MARKS > 90 ---")
print(f"{'Name':<12} {'Class':<8} {'Marks':<5}")
print("-"*27)
with open("[Link]", "r") as f:
reader = [Link](f)
Computer Science Practical Assignment 8
next(reader) # skip headers
for row in reader:
if row:
name, cls, marks = row[0], row[1], float(row[2])
if marks > 90:
print(f"{name:<12} {cls:<8} {marks:<5}")
if __name__ == '__main__':
write_student_csv()
display_excellent_students()
Question 9: Dynamic Text File Generation and Head-Reading
Create a text file [Link] populated via dynamic multi-line user inputs. Read the content stream back to
isolate and print only the first 4 sequential lines.
Source Code:
def create_and_read_text():
print("Enter 5 textual lines to save into the file:")
lines = []
for i in range(5):
line = input(f"Line {i+1}: ")
[Link](line + "
")
with open("[Link]", "w") as f:
[Link](lines)
print("
Reading the first 4 lines from '[Link]':")
with open("[Link]", "r") as f:
for idx in range(4):
line = [Link]()
if not line:
break
print(f"Line {idx+1}: {[Link]()}")
if __name__ == '__main__':
create_and_read_text()
Question 10: Binary Database Querying for Logistics
Store train schedule details in a binary file (Train Number, Name, Source, Destination, Fare). Query and
display all records matching a variable destination parameter dynamically passed into the lookup function
(e.g., 'Lucknow').
Source Code:
import pickle
Computer Science Practical Assignment 9
def initialize_train_data():
trains = [
(12004, "Shatabdi Exp", "New Delhi", "Lucknow", 1200),
(12420, "Gomti Exp", "New Delhi", "Lucknow", 450),
(12230, "Lucknow Mail", "New Delhi", "Lucknow", 950),
(12302, "Rajdhani Exp", "New Delhi", "Howrah", 2800),
(12952, "Mumbai Rajdhani", "New Delhi", "Mumbai", 2500)
]
with open("[Link]", "wb") as f:
for t in trains:
[Link](t, f)
def search_by_destination(dest_param):
print(f"
--- MATCHING TRAINS ROUTED TO: {dest_param.upper()} ---")
print(f"{'TNo':<7} {'Train Name':<18} {'Source':<12} {'Destination':<12} {'Fare':<5}")
print("-"*60)
count = 0
with open("[Link]", "rb") as f:
while True:
try:
tno, name, src, dest, fare = [Link](f)
if [Link]().lower() == dest_param.strip().lower():
print(f"{tno:<7} {name:<18} {src:<12} {dest:<12} {fare:<5}")
count += 1
except EOFError:
break
if count == 0:
print("No matching train schedules discovered for this route.")
if __name__ == '__main__':
initialize_train_data()
search_by_destination("Lucknow")
Computer Science Practical Assignment 10