0% found this document useful (0 votes)
3 views

CS Practical file PDF

The document contains a series of Python programming exercises focused on user-defined functions (UDFs) and file manipulation. It includes tasks such as counting prime numbers, calculating series sums, processing lists and tuples, manipulating strings, creating a book dictionary, and performing various operations on a text file. Each exercise is accompanied by code snippets demonstrating the implementation of the required functionality.

Uploaded by

pratyush.0190
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

CS Practical file PDF

The document contains a series of Python programming exercises focused on user-defined functions (UDFs) and file manipulation. It includes tasks such as counting prime numbers, calculating series sums, processing lists and tuples, manipulating strings, creating a book dictionary, and performing various operations on a text file. Each exercise is accompanied by code snippets demonstrating the implementation of the required functionality.

Uploaded by

pratyush.0190
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

COMPUTER SCIENCE

PRACTICAL FILE

NAME: PRATYUSH CHOUDHARY


CLASS: XII-C
ROLL NO: 14634217
USER DEFINED
FUCNTIONS
Q-1) Write a Python program to input two integers n1 and n2
and Write a menu driven program using UDFs to do
the following :
a. Count the number of prime numbers present between n1
and n2
b. Count the number of perfect numbers between n1 and n2
c. Count the number of palindromes between n1 and n2
Write user defined function for each option of the menu. The
function should take both integers as parameters and return
the processed results.
CODE: def is_prime(num):
"""Checks if a number is prime."""
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True

def count_primes(n1, n2):


"""Counts the number of prime numbers between n1 and n2."""
count = 0
for num in range(n1, n2 + 1):
if is_prime(num):
count += 1
return count

def is_perfect(num):
"""Checks if a number is perfect."""
sum_of_factors = 1 # Include 1 as a factor
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
sum_of_factors += i + num // i # Add both divisor and its complement
return sum_of_factors == num

def count_perfect_numbers(n1, n2):


"""Counts the number of perfect numbers between n1 and n2."""
count = 0
for num in range(n1, n2 + 1):
if is_perfect(num):
count += 1
return count

def is_palindrome(num):
"""Checks if a number is a palindrome."""
return str(num) == str(num)[::-1]

def count_palindromes(n1, n2):


"""Counts the number of palindromes between n1 and n2."""
count = 0
for num in range(n1, n2 + 1):
if is_palindrome(num):
count += 1
return count

def main():
"""Main function to handle user input and menu choices."""
while True:
try:
n1 = int(input("Enter the first integer (n1): "))
n2 = int(input("Enter the second integer (n2): "))
break
except ValueError:
print("Invalid input. Please enter integers only.")

while True:
print("\nMenu:")
print("a. Count prime numbers")
print("b. Count perfect numbers")
print("c. Count palindromes")
print("d. Exit")

choice = input("Enter your choice: ").lower()

if choice == 'a':
count = count_primes(n1, n2)
print("Number of prime numbers:", count)
elif choice == 'b':
count = count_perfect_numbers(n1, n2)
print("Number of perfect numbers:", count)
elif choice == 'c':
count = count_palindromes(n1, n2)
print("Number of palindromes:", count)
elif choice == 'd':
break
else:
print("Invalid choice. Please try again.")
OUTPUT:

Q-2) Write a Python program to input x and n from user and


calculate the sum of the following series using function
sum_series():
-3!/X + 5!/X^2 – 7!/X^3 + 9!/X^4 ……… (2*n+1)!/X^n
Write function factorial() to calculate factorial and
sum_series() which will call factorial() to calculate the sum.
CODE: def factorial(n):
"""Calculates the factorial of a non-negative integer."""
if n < 0:
raise ValueError("Factorial is not defined for negative numbers.")
elif n == 0:
return 1
else:
fact = 1
for i in range(1, n + 1):
fact *= i
return fact

def sum_series(x, n):


"""Calculates the sum of the series -3!/X + 5!/X^2 - 7!/X^3 + 9!/X^4 ...
(2*n+1)!/X^n."""
if x == 0:
raise ValueError("Division by zero is not allowed.")

sum = 0
for i in range(1, n + 1):
term = factorial(2 * i + 1) / (x**i) # Calculate each term
sign = (-1)**i # Alternate the sign
sum += sign * term
return sum

def main():
"""Prompts the user for input and calls the sum_series function."""
try:
x = float(input("Enter the value of x: "))
n = int(input("Enter the value of n: "))
sum = sum_series(x, n)
print("Sum of the series:", sum)
except ValueError as e:
print("Invalid input. Please enter a numeric value for x and a non-negative
integer for n.")
print(e)

OUTPUT :

Q-3) Write a menu driven program to input a list with numeric


data and using UDFs to do the following :
a. A function to return largest and smallest element
b. A function to interchange first half side elements of the list
with second half side elements
c. A function to reverse each element of the list
The above functions should take a list as parameter
CODE: def find_largest_smallest(list1):
"""Returns the largest and smallest elements in a list."""
largest = max(list1)
smallest = min(list1)
return largest, smallest

def interchange_halves(list1):
"""Interchanges the first half and second half of a list."""
mid = len(list1) // 2
list1[:mid], list1[mid:] = list1[mid:], list1[:mid]

def reverse_elements(list1):
"""Reverses each element in a list."""
list1 = [str(x)[::-1] for x in list1] # Convert numbers to strings for reversing

def main():
"""Main function to handle user input and menu choices."""
while True:
try:
list1 = list(map(int, input("Enter a list of numeric data (separated by spaces):
").split()))
break
except ValueError:
print("Invalid input. Please enter only numeric values.")

while True:
print("\nMenu:")
print("a. Find largest and smallest elements")
print("b. Interchange halves of the list")
print("c. Reverse each element of the list")
print("d. Exit")

choice = input("Enter your choice: ").lower()

if choice == 'a':
largest, smallest = find_largest_smallest(list1.copy()) # Use a copy to avoid
modifying the original list
print("Largest element:", largest)
print("Smallest element:", smallest)
elif choice == 'b':
interchange_halves(list1)
print("List after interchanging halves:", list1)
elif choice == 'c':
reverse_elements(list1)
print("List after reversing elements:", list1)
elif choice == 'd':
break
else:
print("Invalid choice. Please try again.")
OUTPUT:

Q-4) Write a program using UDF which takes a tuple as


parameter to do the following:
a. If the element is an integer, print maximum digit of it.
b. If the element is a string, count number of vowels in it.
c. If the element is Boolean, print 1 if true otherwise print 0.
d. If the element is float, print square of integer part of it
CODE: def process_tuple_element(element):
if isinstance(element, int):
# If the element is an integer, print the maximum digit
max_digit = max(map(int, str(abs(element))))
print(f"Maximum digit of {element}: {max_digit}")

elif isinstance(element, str):


# If the element is a string, count the number of vowels
vowel_count = sum(1 for char in element.lower() if char in 'aeiou')
print(f"Number of vowels in '{element}': {vowel_count}")

elif isinstance(element, bool):


# If the element is a boolean, print 1 for True and 0 for False
print(f"{int(element)}")

elif isinstance(element, float):


# If the element is a float, print the square of the integer part
integer_part = int(element)
square_integer_part = integer_part ** 2
print(f"Square of integer part of {element}: {square_integer_part}")

else:
# Handle other types or unsupported types
print(f"Unsupported type: {type(element)}")

OUTPUT:

Q-5) Write a program using UDF which takes a string as


parameter to do the following:
a. Replace each alphabet except z/Z with next alphabet .z/Z
should be replaced with a/A.
b. Replace each digit except 9 with next digit .9 should be
replaced with 0.
c. Replace all special characters with *
CODE: def process_string(input_string):
result = ''
for char in input_string:
if char.isalpha():
# Replace each alphabet except z/Z with the next alphabet
if char.lower() == 'z':
result += 'a' if char.islower() else 'A'
else:
result += chr(ord(char) + 1) if char.islower() else chr(ord(char) + 1).upper()
elif char.isdigit():
# Replace each digit except 9 with the next digit
result += '0' if char == '9' else str(int(char) + 1)
else:
# Replace all special characters with '*'
result += '*'

return result
OUTPUT:

Q-6) Create a dictionary with Book with bookno as key field and
name, price, qty, category and amount as values in form of a
list. The amount to calculated as qty * price.
Write a menu driven program using UDFs to do the
following:
a. A function to search and display details according to
user given book no.
b. A function to count all records with amount >5000
c. A function to count all books with user given category
The above functions should take a dictionary as parameter
CODE: def create_book_dictionary():
"""Creates a dictionary of books with calculated amount."""
books = {}
while True:
bookno = input("Enter book number (or 'done' to finish): ")
if bookno == 'done':
break
name = input("Enter book name: ")
price = float(input("Enter book price: "))
qty = int(input("Enter book quantity: "))
category = input("Enter book category: ")
amount = qty * price
books[bookno] = [name, price, qty, category, amount]
return books

def search_book(books, bookno):


"""Searches for a book by bookno and displays its details."""
if bookno in books:
name, price, qty, category, amount = books[bookno]
print("Book details:")
print("Book number:", bookno)
print("Book name:", name)
print("Book price:", price)
print("Book quantity:", qty)
print("Book category:", category)
print("Total amount:", amount)
else:
print("Book not found.")
def count_records_with_amount_greater_than(books, amount):
"""Counts the number of records with amount greater than a given value."""
count = 0
for _, book_details in books.items():
if book_details[-1] > amount:
count += 1
return count

def count_books_by_category(books, category):


"""Counts the number of books in a given category."""
count = 0
for _, book_details in books.items():
if book_details[3] == category:
count += 1
return count

def main():
"""Main function to handle user input and menu choices."""
books = create_book_dictionary()

while True:
print("\nMenu:")
print("a. Search book by number")
print("b. Count records with amount > 5000")
print("c. Count books by category")
print("d. Exit")

choice = input("Enter your choice: ").lower()

if choice == 'a':
bookno = input("Enter book number to search: ")
search_book(books, bookno)
elif choice == 'b':
count = count_records_with_amount_greater_than(books, 5000)
print("Number of records with amount > 5000:", count)
elif choice == 'c':
category = input("Enter category to count books: ")
count = count_books_by_category(books, category)
print("Number of books in category", category + ":", count)
elif choice == 'd':
break
else:
print("Invalid choice. Please try again.")
OUTPUT:
TEXT FILE
MANIPULATION
Q-1) Write a Python program to create a text file “sample.txt” by
taking contents from the user and perform the following
operations:
a. Count the number of digits, alphabets, special characters
and vowels each line. Also display the line number.
b. Count all lines which starting with a vowel.
c. Display all lines whose size is less than n no. characters.
Accept n from user.
d. Count the occurrence of “The/the” in the file.
e. Count all lines begin with the letter “T/t” to another file.
Display the content of the new file.
f. Display the average word size.
Average word size = sum of size of each word / no. of
words the file.
g. Transfer all alternate words to another file.
h. Transfer all lines not starting with a vowel to another file.
CODE: import string
def count_characters(line):
num_digits = sum(1 for char in line if char.isdigit())
num_alphabets = sum(1 for char in line if char.isalpha())
num_special_chars = sum(1 for char in line if char in string.punctuation)
num_vowels = sum(1 for char in line if char.lower() in 'aeiou')
return num_digits, num_alphabets, num_special_chars, num_vowels

def count_lines_starting_with_vowel(file_content):
return sum(1 for line in file_content if line.strip() and line[0].lower() in 'aeiou')

def lines_less_than_n_characters(file_content, n):


return [line for line in file_content if len(line.strip()) < n]

def count_occurrence_of_word(file_content, word):


return sum(1 for line in file_content for word in line.lower().split() if word == "the")

def lines_starting_with_t_to_file(file_content, output_filename):


lines_with_t = [line for line in file_content if line.strip() and line[0].lower() == 't']
with open(output_filename, 'w') as output_file:
output_file.writelines(lines_with_t)

def average_word_size(file_content):
words = [word.strip(string.punctuation) for line in file_content for word in
line.split()]
total_word_size = sum(len(word) for word in words)
total_words = len(words)
return total_word_size / total_words if total_words > 0 else 0

def alternate_words_to_file(file_content, output_filename):


alternate_words = [word.strip(string.punctuation) for line in file_content for word in
line.split()[::2]]
with open(output_filename, 'w') as output_file:
output_file.write('\n'.join(alternate_words))

def lines_not_starting_with_vowel_to_file(file_content, output_filename):


lines_not_starting_with_vowel = [line for line in file_content if not line.strip() or
line[0].lower() not in 'aeiou']
with open(output_filename, 'w') as output_file:
output_file.writelines(lines_not_starting_with_vowel)

# Get input from user and create the sample.txt file


user_input = input("Enter the content for the 'sample.txt' file:\n")
with open("sample.txt", 'w') as sample_file:
sample_file.write(user_input)

# Read the content from the sample.txt file


with open("sample.txt", 'r') as sample_file:
file_content = sample_file.readlines()

# a. Count characters in each line


for i, line in enumerate(file_content, start=1):
num_digits, num_alphabets, num_special_chars, num_vowels =
count_characters(line)
print(f"Line {i}: Digits={num_digits}, Alphabets={num_alphabets}, Special
Characters={num_special_chars}, Vowels={num_vowels}")

# b. Count lines starting with a vowel


count_vowel_starting_lines = count_lines_starting_with_vowel(file_content)
print(f"Number of lines starting with a vowel: {count_vowel_starting_lines}")

# c. Display lines with size less than n characters


n = int(input("Enter the value of n for lines less than n characters: "))
lines_less_than_n = lines_less_than_n_characters(file_content, n)
print(f"Lines with size less than {n} characters:\n{lines_less_than_n}")

# d. Count occurrence of "The/the" in the file


count_the_occurrence = count_occurrence_of_word(file_content, "the")
print(f"Number of occurrences of 'The/the' in the file: {count_the_occurrence}")
# e. Lines starting with T/t to another file
lines_starting_with_t_to_file(file_content, "lines_starting_with_t.txt")
with open("lines_starting_with_t.txt", 'r') as t_file:
print("\nContent of lines_starting_with_t.txt file:\n" + t_file.read())

# f. Display average word size


avg_word_size = average_word_size(file_content)
print(f"Average word size in the file: {avg_word_size:.2f}")

# g. Transfer alternate words to another file


alternate_words_to_file(file_content, "alternate_words.txt")
with open("alternate_words.txt", 'r') as alternate_file:
print("\nContent of alternate_words.txt file:\n" + alternate_file.read())

# h. Transfer lines not starting with a vowel to another file


lines_not_starting_with_vowel_to_file(file_content, "lines_not_starting_with_vowel.txt")
with open("lines_not_starting_with_vowel.txt", 'r') as not_vowel_file:
print("\nContent of lines_not_starting_with_vowel.txt file:\n" + not_vowel_file.read())

OUTPUT:

Q-2) Write a Python program to create a text file “first.txt” by


taking contents from the user. Read the contents from the first
file ad transfer the contents in another file “second.txt” as
follows:
Replace all vowels with the next alphabet. All digits except 0
should be replaced with the previous digit and 0 to be replaced
with 9. In addition to this, all Special characters should be
replaced with @@. Display the contents of both the files.
CODE: def replace_characters(text):
result = ""
for char in text:
if char.isalpha():
# Replace vowels with the next alphabet
if char.lower() in 'aeiou':
result += chr(ord(char) + 1) if char.islower() else chr(ord(char) + 1).upper()
else:
result += char
elif char.isdigit():
# Replace digits with the previous digit (except 0 which is replaced with 9)
result += str(int(char) - 1) if char != '0' else '9'
else:
# Replace special characters with @@
result += '@@'
return result

# Get input from user and create the first.txt file


user_input = input("Enter the content for the 'first.txt' file:\n")
with open("first.txt", 'w') as first_file:
first_file.write(user_input)

# Read the content from the first.txt file


with open("first.txt", 'r') as first_file:
content_first_file = first_file.read()

# Perform replacements on the content


modified_content = replace_characters(content_first_file)

# Transfer modified content to the second.txt file


with open("second.txt", 'w') as second_file:
second_file.write(modified_content)

# Display contents of both files


print("\nContents of first.txt file:")
print(content_first_file)

print("\nContents of second.txt file:")


with open("second.txt", 'r') as second_file:
content_second_file = second_file.read()
print(content_second_file)

OUTPUT:
CSV FILE
MANIPULATION
Q-1) Write a program to create a csv file by accepting
itemno, item name, category, price and quantity from
user till user wants. Also Calculate Amount as price*
quantity. Write a menu driven program to do the
following operations:
a.Display the contents of the file
b.Count number of records for pulses category of item.
c. Search and display the records based on user given item
no.
d.Search and display the records based on user given item
name.
e.Count the number of records for amount >1000.
CODE: while True:
item_no = input("Enter ItemNo (or 'exit' to finish): ")
if item_no.lower() == 'exit':
break

item_name = input("Enter ItemName: ")


category = input("Enter Category: ")
price = float(input("Enter Price: "))
quantity = int(input("Enter Quantity: "))

amount = price * quantity


data.append([item_no, item_name, category, price, quantity, amount])

write_to_csv(csv_file_name, header, data)


# Menu-driven program
while True:
print("\nMenu:")
print("1. Display the contents of the file")
print("2. Count number of records for pulses category")
print("3. Search and display records based on user given item no.")
print("4. Search and display records based on user given item name")
print("5. Count number of records for amount > 1000")
print("6. Exit")

choice = input("Enter your choice (1-6): ")

if choice == '1':
display_contents(csv_file_name)
elif choice == '2':
count_pulses_category = count_records_pulses_category(csv_file_name)
print(f"Number of records for 'Pulses' category: {count_pulses_category}")
elif choice == '3':
user_item_no = input("Enter the item no. to search: ")
search_and_display_by_item_no(csv_file_name, user_item_no)
elif choice == '4':
user_item_name = input("Enter the item name to search: ")
search_and_display_by_item_name(csv_file_name, user_item_name)
elif choice == '5':
count_amount_gt_1000 = count_records_amount_gt_1000(csv_file_name)
print(f"Number of records with amount > 1000: {count_amount_gt_1000}")
elif choice == '6':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a valid option.")
OUTPUT:

Q-2) Write a menu driven


program to create a CSV file
storing details of students as
Rollno, name, class, stream,
percentage and grade.
Create a menu to
perform the following operations:
a. Display all records
b. Count students with perc between 85-90
c. Count and display details of students of a particular stream.
d. Count and display details of students with a particular grade
e. Copy all the student records to another file whose perc>95
CODE: import csv
def write_to_csv(file_name, header, data):
with open(file_name, 'w', newline='') as csv_file:
csv_writer = csv.writer(csv_file)
csv_writer.writerow(header)
csv_writer.writerows(data)

def read_from_csv(file_name):
with open(file_name, 'r') as csv_file:
csv_reader = csv.reader(csv_file)
header = next(csv_reader)
data = [row for row in csv_reader]
return header, data

def display_all_records(file_name):
header, data = read_from_csv(file_name)
print("\nAll Records:")
print(','.join(header))
for row in data:
print(','.join(row))

def count_students_percentage_between(file_name, min_percentage,


max_percentage):
_, data = read_from_csv(file_name)
count = sum(1 for row in data if min_percentage <= float(row[4]) <=
max_percentage)
return count

def display_students_of_stream(file_name, stream):


_, data = read_from_csv(file_name)
stream_students = [row for row in data if row[3].lower() == stream.lower()]
print(f"\nDetails of students in the '{stream}' stream:")
for row in stream_students:
print(','.join(row))

def display_students_with_grade(file_name, grade):


_, data = read_from_csv(file_name)
grade_students = [row for row in data if row[5].lower() == grade.lower()]
print(f"\nDetails of students with grade '{grade}':")
for row in grade_students:
print(','.join(row))

def copy_students_to_another_file(file_name, output_file_name, min_percentage):


_, data = read_from_csv(file_name)
high_percentage_students = [row for row in data if float(row[4]) >
min_percentage]
header = data[0]
write_to_csv(output_file_name, header, high_percentage_students)
print(f"\nCopied students with percentage > {min_percentage} to
{output_file_name}")

# Create a CSV file with student details


csv_file_name = "student_details.csv"
header = ["RollNo", "Name", "Class", "Stream", "Percentage", "Grade"]
data = [
["1", "John Doe", "12", "Science", "89.5", "A"],
["2", "Jane Smith", "12", "Commerce", "92.3", "A+"],
["3", "Bob Johnson", "12", "Arts", "78.2", "B"],
# Add more student details as needed
]
write_to_csv(csv_file_name, header, data)

# Menu-driven program
while True:
print("\nMenu:")
print("a. Display all records")
print("b. Count students with percentage between 85-90")
print("c. Display details of students of a particular stream")
print("d. Display details of students with a particular grade")
print("e. Copy students with percentage >95 to another file")
print("f. Exit")

choice = input("Enter your choice (a-f): ")

if choice == 'a':
display_all_records(csv_file_name)
elif choice == 'b':
count = count_students_percentage_between(csv_file_name, 85, 90)
print(f"Number of students with percentage between 85-90: {count}")
elif choice == 'c':
user_stream = input("Enter the stream to display details: ")
display_students_of_stream(csv_file_name, user_stream)
elif choice == 'd':
user_grade = input("Enter the grade to display details: ")
display_students_with_grade(csv_file_name, user_grade)
elif choice == 'e':
min_percentage = float(input("Enter the minimum percentage to copy records:
"))
output_file_name = "high_percentage_students.csv"
copy_students_to_another_file(csv_file_name, output_file_name,
min_percentage)
elif choice == 'f':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a valid option.")
OUTPUT:
BINARY FILE
MANIPULATION
Q-1) Write a menu driven program to create a list by taking
bookno, name, price, quantity, category from user.
a. Create binary file storing the contents of the list.
b. Display all Also calculate Amount which should be
calculated by multiplying price* quantity.
c. Search and display record on Bookno.
d. Search and display record on name.
e. Count all records of a user given category.
f. Delete a records matching the user given record number
g. Edit the nth record. Input n from user
CODE: import pickle
class Book:
def __init__(self, bookno, name, price, quantity, category):
self.bookno = bookno
self.name = name
self.price = price
self.quantity = quantity
self.category = category

def calculate_amount(self):
return self.price * self.quantity

def write_to_binary_file(file_name, book_list):


with open(file_name, 'wb') as binary_file:
pickle.dump(book_list, binary_file)

def read_from_binary_file(file_name):
try:
with open(file_name, 'rb') as binary_file:
book_list = pickle.load(binary_file)
return book_list
except FileNotFoundError:
return []

def display_all_books(book_list):
print("\nAll Books:")
for book in book_list:
amount = book.calculate_amount()
print(f"BookNo: {book.bookno}, Name: {book.name}, Price: {book.price},
Quantity: {book.quantity}, Category: {book.category}, Amount: {amount}")

def search_and_display_by_bookno(book_list, user_bookno):


for book in book_list:
if book.bookno == user_bookno:
amount = book.calculate_amount()
print("\nRecord Found:")
print(f"BookNo: {book.bookno}, Name: {book.name}, Price: {book.price},
Quantity: {book.quantity}, Category: {book.category}, Amount: {amount}")
return
print(f"No record found for BookNo {user_bookno}.")

def search_and_display_by_name(book_list, user_name):


for book in book_list:
if book.name.lower() == user_name.lower():
amount = book.calculate_amount()
print("\nRecord Found:")
print(f"BookNo: {book.bookno}, Name: {book.name}, Price: {book.price},
Quantity: {book.quantity}, Category: {book.category}, Amount: {amount}")
return
print(f"No record found for book with name '{user_name}'.")

def count_records_by_category(book_list, user_category):


count = sum(1 for book in book_list if book.category.lower() ==
user_category.lower())
return count

def delete_record_by_bookno(book_list, user_bookno):


book_list[:] = [book for book in book_list if book.bookno != user_bookno]
print(f"Record with BookNo {user_bookno} deleted.")

def edit_nth_record(book_list, n):


if n < 1 or n > len(book_list):
print("Invalid record number.")
return

book = book_list[n - 1]

print(f"\nEditing Record {n}:")


print(f"BookNo: {book.bookno}, Name: {book.name}, Price: {book.price},
Quantity: {book.quantity}, Category: {book.category}")

bookno = input("Enter new BookNo: ")


name = input("Enter new Name: ")
price = float(input("Enter new Price: "))
quantity = int(input("Enter new Quantity: "))
category = input("Enter new Category: ")
book.bookno = bookno
book.name = name
book.price = price
book.quantity = quantity
book.category = category

print(f"Record {n} edited successfully.")

# Main program
book_list = []

while True:
print("\nMenu:")
print("a. Create binary file storing the contents of the list")
print("b. Display all books and calculate Amount")
print("c. Search and display record on BookNo")
print("d. Search and display record on Name")
print("e. Count all records of a user given category")
print("f. Delete a record matching the user given record number")
print("g. Edit the nth record. Input n from the user")
print("h. Exit")

choice = input("Enter your choice (a-h): ")

if choice == 'a':
# Taking input from the user to create the list
book_list = []
while True:
bookno = input("Enter BookNo (or 'exit' to finish): ")
if bookno.lower() == 'exit':
break
name = input("Enter Name: ")
price = float(input("Enter Price: "))
quantity = int(input("Enter Quantity: "))
category = input("Enter Category: ")

book = Book(bookno, name, price, quantity, category)


book_list.append(book)

file_name = input("Enter the binary file name to create: ")


write_to_binary_file(file_name, book_list)
print(f"Binary file '{file_name}' created successfully.")
elif choice == 'b':
display_all_books(book_list)
elif choice == 'c':
user_bookno = input("Enter the BookNo to search: ")
search_and_display_by_bookno(book_list, user_bookno)
elif choice == 'd':
user_name = input("Enter the Name to search: ")
search_and_display_by_name(book_list, user_name)
elif choice == 'e':
user_category = input("Enter the category to count: ")
count = count_records_by_category(book_list, user_category)
print(f"Number of records in category '{user_category}': {count}")
elif choice == 'f':
user_bookno = input("Enter the BookNo to delete: ")
delete_record_by_bookno(book_list, user_bookno)
elif choice == 'g':
n = int(input("Enter the record number to edit: "))
edit_nth_record(book_list, n)
elif choice == 'h':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a valid option.")

OUTPUT:

Q-2)
Write
a

program to create a
binary file to store records of a shop having details as itemno,
Name, QOH (OtyOnhand), Price. Create a menu driven program
to:
a. Create above binary file(Where record is represented as
Nested List)
b. Display all records
c. Display all records whose Price is more than 500
d. Transfer all records whose QOH <200 to another file
CODE: import pickle
class ShopItem:
def __init__(self, itemno, name, qoh, price):
self.itemno = itemno
self.name = name
self.qoh = qoh
self.price = price

def create_binary_file(file_name):
item_list = []

while True:
itemno = input("Enter ItemNo (or 'exit' to finish): ")
if itemno.lower() == 'exit':
break
name = input("Enter Name: ")
qoh = int(input("Enter QOH (Quantity On Hand): "))
price = float(input("Enter Price: "))

item = ShopItem(itemno, name, qoh, price)


item_list.append([item.itemno, item.name, item.qoh, item.price])

with open(file_name, 'wb') as binary_file:


pickle.dump(item_list, binary_file)

print(f"Binary file '{file_name}' created successfully.")

def display_all_records(file_name):
try:
with open(file_name, 'rb') as binary_file:
item_list = pickle.load(binary_file)

print("\nAll Records:")
for item in item_list:
print(f"ItemNo: {item[0]}, Name: {item[1]}, QOH: {item[2]}, Price:
{item[3]}")
except FileNotFoundError:
print("File not found. Please create the file first.")

def display_records_above_price(file_name, threshold_price):


try:
with open(file_name, 'rb') as binary_file:
item_list = pickle.load(binary_file)

print(f"\nRecords with Price > {threshold_price}:")


for item in item_list:
if item[3] > threshold_price:
print(f"ItemNo: {item[0]}, Name: {item[1]}, QOH: {item[2]}, Price:
{item[3]}")
except FileNotFoundError:
print("File not found. Please create the file first.")

def transfer_records_below_qoh(file_name, threshold_qoh, new_file_name):


try:
with open(file_name, 'rb') as binary_file:
item_list = pickle.load(binary_file)

below_qoh_list = [item for item in item_list if item[2] < threshold_qoh]

with open(new_file_name, 'wb') as new_binary_file:


pickle.dump(below_qoh_list, new_binary_file)

print(f"Records with QOH < {threshold_qoh} transferred to '{new_file_name}'.")


except FileNotFoundError:
print("File not found. Please create the file first.")

# Main program
while True:
print("\nMenu:")
print("a. Create binary file")
print("b. Display all records")
print("c. Display records whose Price is more than 500")
print("d. Transfer records whose QOH < 200 to another file")
print("e. Exit")

choice = input("Enter your choice (a-e): ")

if choice == 'a':
file_name = input("Enter the binary file name to create: ")
create_binary_file(file_name)
elif choice == 'b':
file_name = input("Enter the binary file name to display: ")
display_all_records(file_name)
elif choice == 'c':
file_name = input("Enter the binary file name to display records: ")
display_records_above_price(file_name, 500)
elif choice == 'd':
file_name = input("Enter the binary file name to transfer records from: ")
new_file_name = input("Enter the new binary file name to store transferred
records: ")
transfer_records_below_qoh(file_name, 200, new_file_name)
elif choice == 'e':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a valid option.")

OUTPUT:

Q-3) Write a program to create a


binary file account.dat to store
bank account records. Each record
is represented as dictionary with
Accno as the key and name,
type_of_account (Saving, Fixed
and Recurring) and balance as
fields. Create a menu driven
program to:
a. Create above binary file by taking as many records from
the user.
b. Display and count the number of records present in the file
c. Search and edit the record of a user given Accno
d. Search and display all Records based on user given name
e. Count all Records having balance >500000
f. Count all records matching with a user given Type of
account
CODE: import pickle
def create_binary_file(file_name):
account_records = []

while True:
accno = input("Enter Account Number (or 'exit' to finish): ")
if accno.lower() == 'exit':
break
name = input("Enter Name: ")
type_of_account = input("Enter Type of Account (Saving/Fixed/Recurring):
").capitalize()
balance = float(input("Enter Balance: "))

record = {
"Accno": accno,
"Name": name,
"Type_of_Account": type_of_account,
"Balance": balance
}

account_records.append(record)

with open(file_name, 'wb') as binary_file:


pickle.dump(account_records, binary_file)

print(f"Binary file '{file_name}' created successfully.")

def display_and_count_records(file_name):
try:
with open(file_name, 'rb') as binary_file:
account_records = pickle.load(binary_file)

print("\nAll Records:")
count = 0
for record in account_records:
print(record)
count += 1

print(f"\nNumber of Records: {count}")

except FileNotFoundError:
print("File not found. Please create the file first.")

def search_and_edit_record(file_name, user_accno):


try:
with open(file_name, 'rb') as binary_file:
account_records = pickle.load(binary_file)

for record in account_records:


if record["Accno"] == user_accno:
print("\nRecord Found:")
print(record)
# Edit the record
record["Name"] = input("Enter new Name: ")
record["Type_of_Account"] = input("Enter new Type of Account
(Saving/Fixed/Recurring): ").capitalize()
record["Balance"] = float(input("Enter new Balance: "))

with open(file_name, 'wb') as binary_file:


pickle.dump(account_records, binary_file)

print(f"Record with Accno {user_accno} edited successfully.")


return

print(f"No record found for Accno {user_accno}.")

except FileNotFoundError:
print("File not found. Please create the file first.")

def search_and_display_by_name(file_name, user_name):


try:
with open(file_name, 'rb') as binary_file:
account_records = pickle.load(binary_file)

print(f"\nRecords matching Name '{user_name}':")


count = 0
for record in account_records:
if record["Name"].lower() == user_name.lower():
print(record)
count += 1

print(f"\nNumber of Records matching Name '{user_name}': {count}")

except FileNotFoundError:
print("File not found. Please create the file first.")

def count_records_above_balance(file_name, threshold_balance):


try:
with open(file_name, 'rb') as binary_file:
account_records = pickle.load(binary_file)

count = sum(1 for record in account_records if record["Balance"] >


threshold_balance)
print(f"\nNumber of Records with Balance > {threshold_balance}: {count}")

except FileNotFoundError:
print("File not found. Please create the file first.")

def count_records_by_account_type(file_name, user_account_type):


try:
with open(file_name, 'rb') as binary_file:
account_records = pickle.load(binary_file)

count = sum(1 for record in account_records if record["Type_of_Account"] ==


user_account_type.capitalize())
print(f"\nNumber of Records with Type of Account '{user_account_type}':
{count}")
except FileNotFoundError:
print("File not found. Please create the file first.")

# Main program
file_name = "account.dat"

while True:
print("\nMenu:")
print("a. Create binary file")
print("b. Display and count all records")
print("c. Search and edit record based on Accno")
print("d. Search and display all records based on Name")
print("e. Count all records with balance > 500000")
print("f. Count all records matching with a user given Type of account")
print("g. Exit")

choice = input("Enter your choice (a-g): ")

if choice == 'a':
create_binary_file(file_name)
elif choice == 'b':
display_and_count_records(file_name)
elif choice == 'c':
user_accno = input("Enter the Accno to edit: ")
search_and_edit_record(file_name, user_accno)
elif choice == 'd':
user_name = input("Enter the Name to search: ")
search_and_display_by_name(file_name, user_name)
elif choice == 'e':
threshold_balance = float(input("Enter the threshold balance: "))
count_records_above_balance(file_name, threshold_balance)
elif choice == 'f':
user_account_type = input("Enter the Type of Account to count: ")
count_records_by_account_type(file_name, user_account_type)
elif choice == 'g':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a valid option.")
OUTPUT:

DATA STRUCTURE-
STACK
Q-1) Write a program to create a stackA with each element as
an integer. Write a menu driven programs to include functions
to:
1. Push() – push the integer element into the stackA
2. Pop() – pop the integer element from the stackA
3. isempty() – check whether the stackA is empty or not
4. dispstack() – display stack contents
5. Transfer all perfect numbers from stackA to stackB and
Display
6. Transfer all palindrome numbers from stackA to stackB and
Display
7. Transfer all prime numbers from stackA to stackB and
Display
CODE: class Stack:
def __init__(self):
self.items = []

def push(self, item):


self.items.append(item)
print(f"{item} pushed into the stack.")

def pop(self):
if not self.isempty():
item = self.items.pop()
print(f"{item} popped from the stack.")
return item
else:
print("Stack is empty. Cannot pop from an empty stack.")
return None

def isempty(self):
return len(self.items) == 0

def dispstack(self):
if not self.isempty():
print("Stack contents:")
print(self.items)
else:
print("Stack is empty.")

def transfer_perfect_numbers(self, other_stack):


perfect_numbers = [num for num in self.items if self.is_perfect(num)]
self.items = [num for num in self.items if num not in perfect_numbers]
other_stack.items.extend(perfect_numbers)

def transfer_palindrome_numbers(self, other_stack):


palindrome_numbers = [num for num in self.items if self.is_palindrome(num)]
self.items = [num for num in self.items if num not in palindrome_numbers]
other_stack.items.extend(palindrome_numbers)

def transfer_prime_numbers(self, other_stack):


prime_numbers = [num for num in self.items if self.is_prime(num)]
self.items = [num for num in self.items if num not in prime_numbers]
other_stack.items.extend(prime_numbers)

@staticmethod
def is_perfect(num):
return num > 1 and sum(i for i in range(1, num) if num % i == 0) == num

@staticmethod
def is_palindrome(num):
return str(num) == str(num)[::-1]

@staticmethod
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

# Main program
stackA = Stack()
stackB = Stack()

while True:
print("\nMenu:")
print("1. Push")
print("2. Pop")
print("3. Check if stackA is empty")
print("4. Display stackA")
print("5. Transfer perfect numbers from stackA to stackB and Display")
print("6. Transfer palindrome numbers from stackA to stackB and Display")
print("7. Transfer prime numbers from stackA to stackB and Display")
print("8. Exit")

choice = input("Enter your choice (1-8): ")

if choice == '1':
element = int(input("Enter the integer element to push: "))
stackA.push(element)
elif choice == '2':
stackA.pop()
elif choice == '3':
if stackA.isempty():
print("stackA is empty.")
else:
print("stackA is not empty.")
elif choice == '4':
stackA.dispstack()
elif choice == '5':
stackA.transfer_perfect_numbers(stackB)
print("Perfect numbers transferred from stackA to stackB.")
print("stackA:")
stackA.dispstack()
print("stackB:")
stackB.dispstack()
elif choice == '6':
stackA.transfer_palindrome_numbers(stackB)
print("Palindrome numbers transferred from stackA to stackB.")
print("stackA:")
stackA.dispstack()
print("stackB:")
stackB.dispstack()
elif choice == '7':
stackA.transfer_prime_numbers(stackB)
print("Prime numbers transferred from stackA to stackB.")
print("stackA:")
stackA.dispstack()
print("stackB:")
stackB.dispstack()
elif choice == '8':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a

OUTPUT:
Q-2) Write a program to create
a stack, containing student
data, consisting of
Admissionno, Name and
Percentage represented as a
list. Include functions to:
1. Push() – Push the student
record into the stack
2. Pop() – Pop the student
record from the stack
3. isempty() – Check whether
the stack is empty or not
4. dispstack() – Display all
the student records of the
stack
5. dispperc() – Display all
student records scoring a
user given percentage
CODE: class StudentStack:
def __init__(self):
self.stack = []

def push(self, admission_no, name,


percentage):
student_record = {
"AdmissionNo": admission_no,
"Name": name,
"Percentage": percentage
}
self.stack.append(student_record)

def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
print("Stack is empty. Cannot pop.")
return None

def is_empty(self):
return len(self.stack) == 0

def display_all(self):
print("All Student Records in the Stack:")
for record in self.stack:
print(f"AdmissionNo: {record['AdmissionNo']}, Name: {record['Name']},
Percentage: {record['Percentage']}")

def display_by_percentage(self, user_percentage):


matching_records = [record for record in self.stack if record["Percentage"] ==
user_percentage]
if matching_records:
print(f"Student Records with Percentage {user_percentage}:")
for record in matching_records:
print(f"AdmissionNo: {record['AdmissionNo']}, Name: {record['Name']},
Percentage: {record['Percentage']}")
else:
print(f"No student records found with Percentage {user_percentage}.")

# Main program
student_stack = StudentStack()

while True:
print("\nMenu:")
print("1. Push student record")
print("2. Pop student record")
print("3. Check if the stack is empty")
print("4. Display all student records in the stack")
print("5. Display student records with a given percentage")
print("6. Exit")

choice = input("Enter your choice (1-6): ")

if choice == '1':
admission_no = input("Enter Admission Number: ")
name = input("Enter Name: ")
percentage = float(input("Enter Percentage: "))
student_stack.push(admission_no, name, percentage)
print("Student record pushed into the stack.")
elif choice == '2':
popped_record = student_stack.pop()
if popped_record is not None:
print("Student record popped from the stack:")
print(f"AdmissionNo: {popped_record['AdmissionNo']}, Name:
{popped_record['Name']}, Percentage: {popped_record['Percentage']}")
elif choice == '3':
if student_stack.is_empty():
print("Stack is empty.")
else:
print("Stack is not empty.")
elif choice == '4':
student_stack.display_all()
elif choice == '5':
user_percentage = float(input("Enter the percentage to display matching
records: "))
student_stack.display_by_percentage(user_percentage)
elif choice == '6':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a valid option.")

OUTPUT:
COMPUTER SCIENCE

MY SQL COMMANDS
Q-1) Create a Table Empl to store employee details as shown
below and write statements for following queries based on the
table.
empno ename job mgr hiredate sal comm deptno
8369 SMITH CLERK 8902 18-12-1990 800 NULL 20
8499 ANYA SALESMAN 8698 20-02-1991 1600 300 30
8521 SETH SALESMAN 8698 22-02-1991 1250 500 30
8566 MAHADEVAN MANAGER 8839 02-04-1991 2985 NULL 20
8654 MOMIN SALESMAN 8698 28-09-1991 1250 1400 30
8698 BINA MANAGER 8839 01-05-1991 2850 NULL 30
8882 SHIVANSH MANAGER 8839 09-06-1991 2450 NULL 10
8888 SCOTT ANALYST 8566 09-12-1992 3000 NULL 20
8839 AMIR PRESIDENT NULL 18-11-1991 5000 NULL 10
8844 KULDEEP SALESMAN 8698 08-09-1991 1500 0 30
a. Write a query to display EName and Sal of the employees
whose salary are greater than or equal to 2200?
b. Write a query to display details of employs who are not
getting commission?
c. Write a query to display employee name and salary of
those employees who don’t have their salary in range of
2500 to 4000?
d. Write a query to display the name, job title and salary of
employees who don’t have manager and joined after 1990?
e. Write a query to display the name of employee whose
name contains “A” as third alphabet?
f. Write a query to display the name of employee whose
name contains “T” as last alphabet and dept. no is 30?
g. Write a query to display the name of employee whose
name contains “M” as First and “L” as third alphabet?
h. Write a query to display details of employees with the text
“Not given”, if commission is null?
i. Display name and salary of all the employees in the
decreasing order of name.
j. Increase the salary of all employees by 5% who are
Manager and joined before 1991.
k. Delete the records of all employees whose dept. is 20 and
designation is clerk.
l. Display all the records arranged in ascending order of Dept.
no and within it descending order of salary.
m. Display the designations given by the company. The
designation should appear only once.
n. Add another column Status (varchar(10)) in the table.
o. Replace the column Status with permanent for those
employees who have joined before 1991
ANSWER:
a. SELECT EName, Sal FROM Empl WHERE Sal >= 2200;
b. SELECT * FROM Empl WHERE Comm IS NULL;
c. SELECT EName, Sal FROM Empl WHERE Sal NOT BETWEEN 2500 AND 4000;
d. SELECT EName, job, Sal FROM Empl WHERE mgr IS NULL AND hiredate=>31-12-
1990;
e. SELECT Ename FROM Empl WHERE SUBSTR(EName, 3, 1) = 'A';
f. SELECT Ename FROM Empl WHERE SUBSTR(EName, -1) = 'T' AND deptno = 30;
g. SELECT Ename FROM Empl WHERE SUBSTR(EName, 1, 1) = 'M' AND
SUBSTR(EName, 3, 1) = 'L';
h. SELECT *, COALESCE(commission, 'Not given') AS commission FROM employees
WHERE commission IS NULL
i. SELECT EName, Sal FROM Empl ORDER BY EName DESC;
j. UPDATE Empl SET Sal = Sal * 1.05 WHERE job = 'MANAGER' AND hiredate=>1-
1-1991;
k. DELETE FROM Empl WHERE deptno = 20 AND job = 'CLERK';
l. SELECT * FROM Empl ORDER BY deptno ASC, Sal DESC;
m. SELECT DISTINCT job FROM Empl;
n. ALTER TABLE Empl ADD Status VARCHAR(10);
o. UPDATE Empl SET Status = 'Permanent' WHERE hire=>1-1-1991;

Q-2) for the following table answer the following questions


TABLE: SchoolBus
Rtno Area_covered Capacity Noofstudents Distance Transporter Charges
1 Vasant Kunj 100 120 10 Shivantravels 100000
a. 2 Hauz Khas 80 80 10 Anand travels 85000
3 Pitampura 60 55 30 Anand travels 60000
4 Rohini 100 90 35 Anand travels 100000
5 Yamuna Vihar 50 60 20 Bhalla Co. 55000
6 Krishna Nagar 70 80 30 Yadav Co. 80000
7 Vasundhara 100 110 20 Yadav Co. 100000
8 Paschim Vihar 40 40 20 Speed travels 55000
9 Saket 120 120 10 Speed travels 100000
10 Jankpuri 100 100 20 Kisan Tours 95000

Display all the Bus details of those bus where no of students


travelled is more than 100.
b. Display route no and Area of those bus whose charges is
more than 50000.
c. Reduce the charges of all those buses by 12% whose area
covered starts with the letter V.
d. Display the details of the Anand travels and Bhalla co.
transporters
e. Delete all the records in which no of students travelled are
less than 50
f. Display all the records arranged in descending order of No
of students
g. Display the name of transporters who are providing service
h. Increase the charges by 5% of those transporters whose
charges are between 40000 and 50000
i. Add another column comment (varchar(10)) in the table
j. Change the contents of comment column with “satisfactory
“for those routes whose distance is more than 30.
ANSWER:
a. SELECT * FROM SchoolBus WHERE Noofstudents > 100;
b. SELECT Rtno, Area_covered FROM SchoolBus WHERE
Charges > 50000;
c. UPDATE SchoolBus SET Charges = Charges * 0.88 WHERE
Area_covered LIKE 'V%';
d. SELECT * FROM SchoolBus WHERE Transporter IN ('Anand
travels', 'Bhalla Co.');
e. DELETE FROM SchoolBus WHERE Noofstudents < 50;
f. SELECT * FROM SchoolBus ORDER BY Noofstudents DESC;
g. SELECT DISTINCT Transporter FROM SchoolBus;
h. UPDATE SchoolBus SET Charges = Charges * 1.05 WHERE
Charges BETWEEN 40000 AND 50000;
i. ALTER TABLE SchoolBus ADD Comment VARCHAR(10);
j. UPDATE SchoolBus SET Comment = 'satisfactory' WHERE
Distance > 30;
Q-3) Write an SQL command for the queries given from based on
relation BOOK and issued as shown below:
Table--BOOK
TABLE issued
Book_Id
Book_Id Quantity_Issues
Book_Name Publishers Price TypeDate _of_IssueQuantity
T0001 4 12-12-1999
C0001
F0001 The Tears 5
First publishers 450 Fiction 12-10-19995
F0001
T0001 My First C++ 2
EPB 600 Text 11-11-1999 12
F0001 Thunder Bolts First publishers 1200 Fiction 15
T0001 Data structure TDH 230 Text 12
C0001 Fast Cook EPB 100 Cookery 13

i. To show Book_name, price and val(=price*quantity) of


first publisher form the table book
ii. To count records of ‘Text’ type whose quantity is more
than 10.
iii. To display the names and price from books in ascending
order of their price.
iv. To increase the price of all books of EPB publishers by
10%.
v. To insert a new row in the table issued having the
following data (“F0003”, 1,’1999-12-10’).
vi. Count the no. of books in each type from the table book.
vii. To display the Book_Id, Book_Name and Quantity_Issues
for all books which have been issued (Use Both Table).
viii. To include a new column date_of_purchase of date type
in table book.
ANSWER:
i. SELECT Book_Name, Price, Price * Quantity AS val FROM BOOK WHERE
Publishers = 'First publishers';
ii. SELECT COUNT(*)FROM BOOK WHERE Type = 'Text' AND Quantity > 10;
iii. SELECT Book_Name, Price FROM BOOK ORDER BY Price ASC;
iv. UPDATE BOOK SET Price = Price * 1.1 WHERE Publishers = 'EPB';
v. INSERT INTO issued (Book_Id, Quantity_Issues, Date_of_Issue)VALUES ('F0003',
1, '1999-12-10');
vi. SELECT Type, COUNT(*) AS No_of_Books FROM BOOK GROUP BY Type;
vii. SELECT i.Book_Id, b.Book_Name, i.Quantity_Issues FROM issued i JOIN BOOK b
ON i.Book_Id = b.Book_Id;
viii. ALTER TABLE BOOK ADD COLUMN date_of_purchase DATE;

Q-4) Write SQL queries from (i) to (iv) and find outputs for SQL
queries (v) to (viii), which are based on the tables
Table: VEHICILE
VCOD
E CEHICLETYPE PERKM

V01 VOLVO BUS 150

V02 AC DELUXE BUS 125

V03 ORDINARY BUS 80

V05 SUV 30

V04 CAR 18

TABLE: TRAVEL
NO
CNO CNAME TRAVELDATE KM VCODE P
20
101 K.Niwal 13-12-2015 0 V01 32
12
103 Fredrick Sym 21-03-2016 0 V03 45
45
105 Hitesh Jain 23-04-2016 0 V02 42
102 Ravi Anish 13-01-2016 80 V02 40
107 John Malina 10-02-2015 65 V04 2
104 Sahanubhuti 28-01-2016 90 V05 4

i. To display CNO, CNAME from the table TRAVEL in


descending order of CNO.
ii. To display the CNAME of all the customers from the
table TRAVEL who are travelling by vehicle with CNAME
starting with R.
iii. To increase the NOP by 10 of those customers from the
table TRAVEL who travelled between ‘2015-12-31’ and
‘2015-05-01’.
iv. To display VEHICLETYPE, CNAME, NOP for the
customers, who have travelled distance more than 120
KM.
v. To display maximum NOP in each VCODE whose
traveldate is after 2016-01-13
ANSWER:
i. SELECT CNO, CNAME FROM TRAVEL ORDER BY CNO
DESC;
ii. SELECT CNAME FROM TRAVEL WHERE VCODE IN
(SELECT VCODE FROM VEHICLE WHERE CEHICLETYPE
LIKE 'R%');
iii. UPDATE TRAVEL SET NOP = NOP + 10 WHERE
TRAVELDATE BETWEEN '2015-05-01' AND '2015-12-31';
iv. SELECT VEHICLE.CEHICLETYPE, TRAVEL.CNAME,
TRAVEL.NOP FROM TRAVEL JOIN VEHICLE ON
TRAVEL.VCODE = VEHICLE.VCODE WHERE TRAVEL.KM
> 120;
v. SELECT VCODE, MAX(NOP) AS Max_NOP FROM TRAVEL
WHERE TRAVELDATE > '2016-01-13' GROUP BY VCODE;
VCODE Max_NOP
V01 32
V02 42
V05 4
MYSQL DATABASE
Q-1) Write menu driven application is using MySQL Database
Connectivity using Python. In a menu driven interface, it is
providing the following features
1. Create the table
2. Insert new records
3. Display all records
4. Search and display
5. Count and display
6. Delete record
7. Edit record
8. Arrange records in ascending and descending order
The table item has item no (int (4), Name(Varchar(25)), price
decimal(12,2), type(varchar(5))
CODE: import mysql.connector
# Function to create the table
def create_table(cursor):
cursor.execute("CREATE TABLE IF NOT EXISTS item (item_no INT(4), Name
VARCHAR(25), price DECIMAL(12,2), type VARCHAR(5))")

# Function to insert new records


def insert_record(cursor):
item_no = int(input("Enter Item No: "))
name = input("Enter Name: ")
price = float(input("Enter Price: "))
item_type = input("Enter Type: ")

cursor.execute("INSERT INTO item VALUES (%s, %s, %s, %s)", (item_no, name,
price, item_type))
print("Record inserted successfully.")

# Function to display all records


def display_all_records(cursor):
cursor.execute("SELECT * FROM item")
records = cursor.fetchall()

for record in records:


print(record)

# Function to search and display


def search_and_display(cursor):
item_no = int(input("Enter Item No to search: "))
cursor.execute("SELECT * FROM item WHERE item_no = %s", (item_no,))
record = cursor.fetchone()

if record:
print(record)
else:
print("Record not found.")

# Function to count and display


def count_and_display(cursor):
item_type = input("Enter Type to count: ")
cursor.execute("SELECT COUNT(*) FROM item WHERE type = %s", (item_type,))
count = cursor.fetchone()[0]

print(f"Number of items with type '{item_type}': {count}")

# Function to delete record


def delete_record(cursor):
item_no = int(input("Enter Item No to delete: "))
cursor.execute("DELETE FROM item WHERE item_no = %s", (item_no,))
print("Record deleted successfully.")

# Function to edit record


def edit_record(cursor):
item_no = int(input("Enter Item No to edit: "))
name = input("Enter new Name: ")
price = float(input("Enter new Price: "))
item_type = input("Enter new Type: ")

cursor.execute("UPDATE item SET Name = %s, price = %s, type = %s WHERE


item_no = %s",
(name, price, item_type, item_no))
print("Record updated successfully.")

# Function to arrange records in ascending and descending order


def arrange_records(cursor, order):
cursor.execute(f"SELECT * FROM item ORDER BY item_no {order}")
records = cursor.fetchall()

for record in records:


print(record)

# Main function
def main():
connection = mysql.connector.connect(
host="your_host",
user="your_user",
password="your_password",
database="your_database"
)

cursor = connection.cursor()

create_table(cursor)

while True:
print("\nMenu:")
print("1. Create Table")
print("2. Insert New Records")
print("3. Display All Records")
print("4. Search and Display")
print("5. Count and Display")
print("6. Delete Record")
print("7. Edit Record")
print("8. Arrange Records (Ascending)")
print("9. Arrange Records (Descending)")
print("0. Exit")

choice = input("Enter your choice: ")

if choice == '1':
create_table(cursor)
elif choice == '2':
insert_record(cursor)
elif choice == '3':
display_all_records(cursor)
elif choice == '4':
search_and_display(cursor)
elif choice == '5':
count_and_display(cursor)
elif choice == '6':
delete_record(cursor)
elif choice == '7':
edit_record(cursor)
elif choice == '8':
arrange_records(cursor, "ASC")
elif choice == '9':
arrange_records(cursor, "DESC")
elif choice == '0':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a valid option.")
cursor.close()
connection.close()

You might also like