0% found this document useful (0 votes)
14 views85 pages

Lucknow Public College Computer Science Report

This document is a report file for a student named Anushka Yadav from Lucknow Public College for the academic year 2025-26. It includes various programming assignments in Computer Science, such as a basic calculator, series summation, pattern printing, ticketing system, list modification, and stock management using functions. Each program is accompanied by code snippets and example outputs demonstrating their functionality.

Uploaded by

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

Lucknow Public College Computer Science Report

This document is a report file for a student named Anushka Yadav from Lucknow Public College for the academic year 2025-26. It includes various programming assignments in Computer Science, such as a basic calculator, series summation, pattern printing, ticketing system, list modification, and stock management using functions. Each program is accompanied by code snippets and example outputs demonstrating their functionality.

Uploaded by

anushkayadav1267
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

LUCKNOW PUBLIC COLLEGE

LUCKNOW GOMTI NAGAR


ACADEMIC YEAR : 2025-26

REPORT FILE

ROLL NO : 32671477

NAME : ANUSHKA YADAV

CLASS : XII-A

SUBJECT : COMPUTER SCIENCE

SUB CODE : 083


CERTIFICATE

THIS IS CERTIFIED TO BE THE BONAFIED WORK OF THE


STUDENT IN THE COMPUTER LABORATORY DURING
COMPUTER PRACTICALS FOR THE AISSCE AS PRESCRIBED
BY CBSE IN THE YEAR 2025-26.

……………………………………… ……..……………………………

INTERNAL EXAMINER EXTERNAL EXAMINER


acknowledgement

I would like to express my special thanks of gratitude to my


computer science teacher "[Link] Menghani”sir for their
able guidance and support in completing my Project.
I would also like to extend my gratitude to my parents and
friends for their encouragement and help, which made this
work possible.
Report file

1. Write a menu driven program to perform mathematical calculations like


Addition, Subtraction, Division, Multiplication between two integers. The program
should continue running until user gives the choice to quit.

Code
def main():
while True:
print("\n--- Basic Calculator Menu ---")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Quit")

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

if choice == '5':
print("Exiting the program. Goodbye!")
break

if choice in ('1', '2', '3', '4'):


try:
num1 = int(input("Enter first integer: "))
num2 = int(input("Enter second integer: "))

if choice == '1':
print(f"Result: {num1} + {num2} = {num1 + num2}")
elif choice == '2':
print(f"Result: {num1} - {num2} = {num1 - num2}")
elif choice == '3':
print(f"Result: {num1} * {num2} = {num1 * num2}")
elif choice == '4':
if num2 == 0:
print("Error: Division by zero is not allowed.")
else:
print(f"Result: {num1} / {num2} = {num1 / num2}")
except ValueError:
print("Invalid input. Please enter integer values.")
else:
print("Invalid choice. Please select a number between 1 and 5.")

if __name__ == "__main__":
main()
Output
--- Basic Calculator Menu ---
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Quit
Enter your choice (1-5): 1
Enter first integer: 10
Enter second integer: 5
Result: 10 + 5 = 15

--- Basic Calculator Menu ---


1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Quit
Enter your choice (1-5): 4
Enter first integer: 20
Enter second integer: 4
Result: 20 / 4 = 5.0

--- Basic Calculator Menu ---


1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Quit
Enter your choice (1-5): 5
Exiting the program. Goodbye!
2. Write a program to find sum of series

S=1+x1/2!+x2/3!+…..+xn/(n+1)!

Code
def sum_of_series(x, n):
total = 1.0 # Initial term is 1
term = 1.0

# Calculate each term: (x^i) / (i+1)!


# Each new term is (previous_term * x) / (i + 1)
for i in range(1, n + 1):
term = (term * x) / (i + 1)
total += term
return total

# Input values
x_val = float(input("Enter value of x: "))
n_val = int(input("Enter number of terms (n): "))

# Output result
result = sum_of_series(x_val, n_val)
print(f"The sum of the series for x={x_val} and n={n_val} is:
{result:.4f}")

Output:
text
Enter value of x: 5
Enter number of terms (n): 4
The sum of the series for x=5.0 and n=4 is: 29.8000
[Link] a program to print following pattern:

1
10
1 0 10
1010
10101
Code
# Number of rows in the pattern
rows = 5

for i in range(1, rows + 1):


for j in range(1, i + 1):
# Print 1 for odd columns and 0 for even columns
if j % 2 != 0:
print("1", end=" ")
else:
print("0", end=" ")
print() # New line after each row

output
1

10

101

1010

10101
4. Write a program which takes the number of people of various age groups as
input and prints a ticket. At the end of the journey, the program states the
number of passengers of different age groups who travelled and the total amount
received as collection of fares.

Code
def ticketing_system():

total_fare = 0

# Categories for summary

categories = {"Infant": 0, "Child": 0, "Adult": 0, "Senior": 0}

try:

num_passengers = int(input("Enter total number of passengers: "))

except ValueError:

print("Invalid input. Please enter a number.")

return

print("\n--- Generating Tickets ---")

for i in range(1, num_passengers + 1):

try:

age = int(input(f"Enter age for passenger {i}: "))

# Fare Rules

if age < 3:

fare = 0

categories["Infant"] += 1
elif 3 <= age <= 12:

fare = 200

categories["Child"] += 1

elif 13 <= age < 60:

fare = 500

categories["Adult"] += 1

else:

fare = 300

categories["Senior"] += 1

total_fare += fare

print(f"Ticket {i}: Age {age}, Fare: Rs. {fare}")

except ValueError:

print("Invalid age entered. Skipping this passenger.")

# End of Journey Summary

print("\n--- Final Journey Summary ---")

for group, count in [Link]():

print(f"{group}s: {count}")

print(f"Total Passengers: {num_passengers}")

print(f"Total Collection of Fares: Rs. {total_fare}")

# Run the program


ticketing_system()

output
Enter total number of passengers: 4

--- Generating Tickets ---

Enter age for passenger 1: 2

Ticket 1: Age 2, Fare: Rs. 0

Enter age for passenger 2: 10

Ticket 2: Age 10, Fare: Rs. 200

Enter age for passenger 3: 25

Ticket 3: Age 25, Fare: Rs. 500

Enter age for passenger 4: 65

Ticket 4: Age 65, Fare: Rs. 300

--- Final Journey Summary ---

Infants: 1

Children: 1

Adults: 1

Seniors: 1

Total Passengers: 4

Total Collection of Fares: Rs. 1000


[Link] a program that defines a function ModifyList(L) which receives a list of
integers , updates all those elements which have 5 as the last digit with 1 and rest
by 0.

Code
def ModifyList(L):

# Iterate through the list using its length to modify in place

for i in range(len(L)):

# Check if the last digit of the number is 5

# We use abs() to handle negative numbers correctly

if abs(L[i]) % 10 == 5:

L[i] = 1

else:

L[i] = 0

# Test the function

my_list = [15, 22, 35, 40, 5, -25, 107]

print("Original List:", my_list)

ModifyList(my_list)

print("Modified List:", my_list)

output
Original List: [15, 22, 35, 40, 5, -25, 107]

Modified List: [1, 0, 1, 0, 1, 1, 0]


6. Write a program that defines a function MinMax(T) which receives a tuple of
integers and returns the maximum and minimum value stored in tuple.

Output
def MinMax(T):

"""

Receives a tuple of integers T and returns its maximum and minimum values.

"""

if not T:

return None, None # Handle empty tuple case

maximum = max(T)

minimum = min(T)

return maximum, minimum

# Example usage

numbers = (45, 12, 89, 3, 67, 23)

max_val, min_val = MinMax(numbers)

# Output the results

print("Original Tuple:", numbers)

print("Maximum Value:", max_val)

print("Minimum Value:", min_val)


output
Original Tuple: (45, 12, 89, 3, 67, 23)

Maximum Value: 89

Minimum Value: 3
[Link] a program with function INDEX_LIST(L), where L is the list of elements
passed as argument to the function. The function returns another list named
‘indexlist’ that stores the indices of all Non-Zero elements of L. For e.g. if L
contains [12,4,0,11,0,56] then after execution indexlist will have[0,1,3,5].

Code
def INDEX_LIST(L):

"""

Receives a list L and returns a list of indices

where the elements are non-zero.

"""

indexlist = []

# Iterate through the list using the index

for i in range(len(L)):

# Check if the element at index i is non-zero

if L[i] != 0:

[Link](i)

return indexlist

# Example usage

L = [12, 4, 0, 11, 0, 56]

result = INDEX_LIST(L)

# Output the results


print("Original List:", L)

print("Indices of Non-Zero Elements:", result)

output
Original List: [12, 4, 0, 11, 0, 56]

Indices of Non-Zero Elements: [0, 1, 3, 5]


8. Write a python program to create a list to store [icode, iname,qty, ppu,tprice]
to maintain a stock of a shop .

Following functions are given to adding, displaying , searching and modifying a


icode and updating the quantity of stock(using list whereas list declared globally).

def additems(stock): to accept icode, iname, qty, ppu, compute


tprice and add it to list lst

def display(stock) : to display the stock items from lst

def search(icode, stock) function to search for a icode from the lst and
display the other detais
of the icode if present otherwise display an
appropriate message
def modify(icode stock) update the stock and tprice
code

# Global list to store stock items


lst = []

def additems():
"""Accepts item details, computes tprice, and adds to global list lst."""
icode = int(input("Enter Item Code: "))
iname = input("Enter Item Name: ")
qty = int(input("Enter Quantity: "))
ppu = float(input("Enter Price Per Unit: "))

# Compute Total Price


tprice = qty * ppu

# Store as a list [icode, iname, qty, ppu, tprice]


item = [icode, iname, qty, ppu, tprice]
[Link](item)
print("Item added successfully!")

def display():
"""Displays all stock items from the global list lst."""
if not lst:
print("Stock is currently empty.")
return

print("\n--- Current Stock ---")


print(f"{'ICode':<10} {'IName':<15} {'Qty':<10} {'PPU':<10} {'TPrice':<10}")
for item in lst:
print(f"{item[0]:<10} {item[1]:<15} {item[2]:<10} {item[3]:<10.2f} {item[4]:<10.2f}")

def search(icode):
"""Searches for an icode and displays its details if found."""
found = False
for item in lst:
if item[0] == icode:
print("\nItem Found:")
print(f"Name: {item[1]}, Qty: {item[2]}, PPU: {item[3]}, Total Price: {item[4]}")
found = True
break
if not found:
print(f"Error: Item with code {icode} not found.")

def modify(icode):
"""Updates the quantity and recalculates tprice for a specific icode."""
found = False
for item in lst:
if item[0] == icode:
new_qty = int(input(f"Enter new quantity for {item[1]}: "))
item[2] = new_qty
item[4] = item[2] * item[3] # Update tprice based on new quantity
print("Stock updated successfully!")
found = True
break
if not found:
print(f"Error: Cannot modify. Item {icode} not found.")

# Simple Menu to drive the program


while True:
print("\n1. Add Item\n2. Display Stock\n3. Search Item\n4. Modify Stock\n5. Exit")
choice = input("Enter your choice (1-5): ")

if choice == '1':
additems()
elif choice == '2':
display()
elif choice == '3':
code = int(input("Enter Item Code to search: "))
search(code)
elif choice == '4':
code = int(input("Enter Item Code to modify: "))
modify(code)
elif choice == '5':
break
else:
print("Invalid choice, try again.")

output
1. Add Item
2. Display Stock
3. Search Item
4. Modify Stock
5. Exit
Enter your choice (1-5): 1
Enter Item Code: 101
Enter Item Name: Notebook
Enter Quantity: 50
Enter Price Per Unit: 40
Item added successfully!

Enter your choice (1-5): 2


--- Current Stock ---
ICode IName Qty PPU TPrice
101 Notebook 50 40.00 2000.00

Enter your choice (1-5): 4


Enter Item Code to modify: 101
Enter new quantity for Notebook: 60
Stock updated successfully!

Enter your choice (1-5): 2


--- Current Stock ---
ICode IName Qty PPU TPrice
101 Notebook 60 40.00 2400.00
9. Write a menu driven program with user defined functions to create a text file
[Link], where choices are:

1-Create text file 2- Generate a frequency list of all the words resent in it

3-Print the line having maximum number of words.4-Quit

Code
def create_file():

"""Choice 1: Create or overwrite [Link] with user input."""

filename = "[Link]"

print("Enter text to save to the file (type 'END' on a new line to finish):")

lines = []

while True:

line = input()

if [Link]().upper() == "END":

break

[Link](line + "\n")

with open(filename, "w") as f:

[Link](lines)

print(f"File '{filename}' created successfully!\n")

def word_frequency():

"""Choice 2: Generate and display the frequency of every word in the file."""

try:
counts = {}

with open("[Link]", "r") as f:

for line in f:

# Split line into words and strip punctuation/whitespace

words = [Link]().split()

for word in words:

# Remove basic punctuation like . , !

clean_word = [Link](".,!?;:()[]\"'")

if clean_word:

counts[clean_word] = [Link](clean_word, 0) + 1

print("\n--- Word Frequency List ---")

for word, freq in sorted([Link]()):

print(f"{word}: {freq}")

print("---------------------------\n")

except FileNotFoundError:

print("Error: [Link] not found. Create it first.\n")

def max_words_line():

"""Choice 3: Identify and print the line containing the highest number of words."""

try:

max_count = -1

target_line = ""

with open("[Link]", "r") as f:

for line in f:
word_count = len([Link]())

if word_count > max_count:

max_count = word_count

target_line = [Link]()

if target_line:

print(f"\nLine with most words ({max_count} words):")

print(f"\"{target_line}\"\n")

else:

print("The file is empty.\n")

except FileNotFoundError:

print("Error: [Link] not found. Create it first.\n")

# Main Menu Loop

while True:

print("--- MENU ---")

print("1 - Create text file")

print("2 - Generate word frequency list")

print("3 - Print line with maximum words")

print("4 - Quit")

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

if choice == '1':

create_file()
elif choice == '2':

word_frequency()

elif choice == '3':

max_words_line()

elif choice == '4':

print("Exiting program.")

break

else:

print("Invalid selection. Please try again.\n")


Output
--- MENU ---

1 - Create text file

2 - Generate word frequency list

3 - Print line with maximum words

4 - Quit

Enter your choice (1-4): 1

Enter text to save to the file (type 'END' on a new line to finish):

Python is a great language.

It is fun to code in Python.

Python is versatile.

END

File '[Link]' created successfully!

Enter your choice (1-4): 2

--- Word Frequency List ---

a: 1

code: 1

fun: 1

great: 1

in: 1

is: 3

it: 1

language: 1
python: 3

to: 1

versatile: 1

Enter your choice (1-4): 3

Line with most words (7 words):

"It is fun to code in Python."


[Link] a program to remove all the lines that contains character ‘a’ in a file and
write them to another file.

Code
def filter_lines_with_a(source_file, target_file):

try:

# Step 1: Read all lines from the source file

with open(source_file, 'r') as f:

lines = [Link]()

remaining_lines = []

removed_count = 0

# Step 2: Open target file to write lines containing 'a'

with open(target_file, 'w') as target:

for line in lines:

# Check for 'a' (case-insensitive check: 'a' or 'A')

if 'a' in [Link]():

[Link](line)

removed_count += 1

else:

remaining_lines.append(line)

# Step 3: Overwrite the source file with lines that did NOT contain 'a'

with open(source_file, 'w') as f:


[Link](remaining_lines)

print(f"Process complete.")

print(f"Lines moved to '{target_file}': {removed_count}")

print(f"Remaining lines in '{source_file}': {len(remaining_lines)}")

except FileNotFoundError:

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

# Create a sample file for demonstration

with open("[Link]", "w") as f:

[Link]("Apple is red.\nSky is blue.\nBanana is yellow.\nTree is green.\n")

# Run the function

filter_lines_with_a("[Link]", "removed_lines.txt")
Output
Process complete.

Lines moved to 'removed_lines.txt': 2

Remaining lines in '[Link]': 2

Apple is red.

Banana is yellow.

Sky is blue.

Tree is green.
11. Write a program to create a menu driven program using user defined
functions to manage details of Applicants in a binary file .DAT . Applicant details
include(AppID,AName,Qualification)

Code
import pickle

import os

# Function to add a new applicant record

def add_record():

with open("[Link]", "ab") as f:

app_id = int(input("Enter Applicant ID: "))

name = input("Enter Applicant Name: ")

qualification = input("Enter Qualification: ")

record = [app_id, name, qualification]

[Link](record, f)

print("Record added successfully!")

# Function to display all applicant records

def display_records():

if not [Link]("[Link]"):

print("No records found.")

return

with open("[Link]", "rb") as f:


print("\n--- Applicant Details ---")

print(f"{'AppID':<10} {'Name':<20} {'Qualification':<20}")

try:

while True:

record = [Link](f)

print(f"{record[0]:<10} {record[1]:<20} {record[2]:<20}")

except EOFError:

pass

# Function to search for an applicant by ID

def search_record():

found = False

search_id = int(input("Enter AppID to search: "))

with open("[Link]", "rb") as f:

try:

while True:

record = [Link](f)

if record[0] == search_id:

print(f"Record Found: {record}")

found = True

break

except EOFError:

pass

if not found:

print("Record not found.")


# Main Menu Driven Program

def menu():

while True:

print("\n--- Applicant Management System ---")

print("1. Add Applicant Record")

print("2. Display All Records")

print("3. Search Applicant by ID")

print("4. Exit")

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

if choice == '1':

add_record()

elif choice == '2':

display_records()

elif choice == '3':

search_record()

elif choice == '4':

print("Exiting...")

break

else:

print("Invalid choice! Please try again.")

if __name__ == "__main__":

menu()
output
--- Applicant Management System ---

1. Add Applicant Record

2. Display All Records

3. Search Applicant by ID

4. Exit

Enter your choice (1-4): 1

Enter Applicant ID: 101

Enter Applicant Name: John Doe

Enter Qualification: [Link]

Record added successfully!

--- Applicant Management System ---

1. Add Applicant Record

2. Display All Records

3. Search Applicant by ID

4. Exit

Enter your choice (1-4): 2

--- Applicant Details ---

AppID Name Qualification

101 John Doe [Link]

--- Applicant Management System ---


1. Add Applicant Record

2. Display All Records

3. Search Applicant by ID

4. Exit

Enter your choice (1-4): 4

Exiting...
12. Write a menu driven program to implement stack data structure using list to
Push and Pop Book details(BookID,BTitle,Author,Publisher,Price). The available
choices are:

1-PUSH 2-POP 3-PEEK 4-TRAVERSE

5-QUIT

Code
# Initialize an empty list to act as the stack

stack = []

def push_book():

"""Adds a new book details dictionary to the stack."""

book_id = input("Enter Book ID: ")

title = input("Enter Title: ")

author = input("Enter Author: ")

publisher = input("Enter Publisher: ")

try:

price = float(input("Enter Price: "))

except ValueError:

print("Invalid price entered. Price must be a number.")

return

book_details = {

"BookID": book_id,

"BTitle": title,
"Author": author,

"Publisher": publisher,

"Price": price

[Link](book_details)

print(f"Book '{title}' pushed to the stack.")

def pop_book():

"""Removes and returns the top element from the stack."""

if not stack:

print("Error: Stack is empty. Cannot pop a book.")

else:

popped_book = [Link]()

print("\n--- Popped Book Details ---")

for key, value in popped_book.items():

print(f"* {key}: {value}")

def peek_book():

"""Displays the top element of the stack without removing it."""

if not stack:

print("Error: Stack is empty.")

else:

top_book = stack[-1]

print("\n--- Top Book Details (Peek) ---")

for key, value in top_book.items():


print(f"* {key}: {value}")

def traverse_stack():

"""Displays all elements in the stack from top to bottom."""

if not stack:

print("Stack is empty.")

else:

print("\n--- Current Stack (Top to Bottom) ---")

# Iterate backwards to display from top (end of list) to bottom

for i in range(len(stack) - 1, -1, -1):

print(f"--- Position {i} ---")

for key, value in stack[i].items():

print(f"* {key}: {value}")

def menu():

"""The main menu-driven function to interact with the stack."""

while True:

print("\n*** Book Stack Menu ***")

print("1-PUSH")

print("2-POP")

print("3-PEEK")

print("4-TRAVERSE")

print("5-QUIT")

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


if choice == '1':

push_book()

elif choice == '2':

pop_book()

elif choice == '3':

peek_book()

elif choice == '4':

traverse_stack()

elif choice == '5':

print("Exiting program.")

break

else:

print("Invalid choice. Please enter a number from 1 to 5.")

if __name__ == "__main__":

menu()
Output
*** Book Stack Menu ***

1-PUSH

2-POP

3-PEEK

4-TRAVERSE

5-QUIT

Enter your choice (1-5): 1

Enter Book ID: 001

Enter Title: Python Programming

Enter Author: John Smith

Enter Publisher: Tech Press

Enter Price: 29.99

Book 'Python Programming' pushed to the stack.

*** Book Stack Menu ***

1-PUSH

2-POP

3-PEEK

4-TRAVERSE

5-QUIT

Enter your choice (1-5): 1

Enter Book ID: 002

Enter Title: Data Structures


Enter Author: Jane Doe

Enter Publisher: Edu Books

Enter Price: 45.50

Book 'Data Structures' pushed to the stack.

*** Book Stack Menu ***

1-PUSH

2-POP

3-PEEK

4-TRAVERSE

5-QUIT

Enter your choice (1-5): 3

--- Top Book Details (Peek) ---

* BookID: 002

* BTitle: Data Structures

* Author: Jane Doe

* Publisher: Edu Books

* Price: 45.5

*** Book Stack Menu ***

1-PUSH

2-POP

3-PEEK

4-TRAVERSE
5-QUIT

Enter your choice (1-5): 4

--- Current Stack (Top to Bottom) ---

--- Position 1 ---

* BookID: 002

* BTitle: Data Structures

* Author: Jane Doe

* Publisher: Edu Books

* Price: 45.5

--- Position 0 ---

* BookID: 001

* BTitle: Python Programming

* Author: John Smith

* Publisher: Tech Press

* Price: 29.99

*** Book Stack Menu ***

1-PUSH

2-POP

3-PEEK

4-TRAVERSE

5-QUIT

Enter your choice (1-5): 2


--- Popped Book Details ---

* BookID: 002

* BTitle: Data Structures

* Author: Jane Doe

* Publisher: Edu Books

* Price: 45.5

*** Book Stack Menu ***

1-PUSH

2-POP

3-PEEK

4-TRAVERSE

5-QUIT

Enter your choice (1-5): 5

Exiting program.
13 .Write definition of a user defined function PUSHNV(N) which receives a list of
strings in the parameter N and pushes all strings which have no vowels present in
it , into a list named NoVowel.

Write a program to input 10 words and push them on to a list ALL.

The program then use the function PUSHNV() to create a stack of words in the list
NoVowel so that it stores only those words which do not have any vowel present
in it, from the list ALL. Thereafter pop each word from the list NoVowel and
display all popped words. When the stack is empty display the message “Empty
Stack”.

Code
# User-defined function to filter words and push to NoVowel stack

def PUSHNV(N):

NoVowel = []

vowels = "AEIOUaeiou"

for word in N:

# Check if the word contains any character from the vowel string

has_vowel = False

for char in word:

if char in vowels:

has_vowel = True

break

# If no vowels were found, push the word to the NoVowel stack

if not has_vowel:

[Link](word)
return NoVowel

# Main Program

ALL = []

print("Enter 10 words:")

for i in range(10):

word = input(f"Word {i+1}: ")

[Link](word)

# Create the NoVowel stack using the user-defined function

NoVowel = PUSHNV(ALL)

# Pop and display each word from the NoVowel stack

print("\nPopped words from NoVowel stack:")

if len(NoVowel) == 0:

print("Empty Stack")

else:

while len(NoVowel) > 0:

print([Link]())

# After popping all, confirm it is empty

if len(NoVowel) == 0:

print("Empty Stack")
output
Enter 10 words:

Word 1: Apple

Word 2: Sky

Word 3: Rhythm

Word 4: Orange

Word 5: Fly

Word 6: Gym

Word 7: Hello

Word 8: Crypt

Word 9: Dry

Word 10: Python

Popped words from NoVowel stack:

Dry

Crypt

Gym

Fly

Rhythm

Sky

Empty Stack
14. Write a program in Python using a user defined function Push(SItem) where
SItem is a dictionary containing the details of stationary items {Sname:Price}.

The function should push the names of those items in the stack who have price
greater than 75, also display the count of elements pushed onto the stack.

Code
def Push(SItem):

"""

Pushes stationary item names with price > 75 into a stack.

"""

stack = []

count = 0

# Iterate through the dictionary items

for name, price in [Link]():

if price > 75:

[Link](name)

count += 1

print(f"Items pushed onto the stack: {stack}")

print(f"Total count of elements pushed: {count}")

return stack

# Example usage:

stationary_data = {
"Pencil": 10,

"Notebook": 85,

"Calculator": 500,

"Eraser": 5,

"Marker": 90

Push(stationary_data)
Output
Items pushed onto the stack: ['Notebook', 'Calculator', 'Marker']

Total count of elements pushed: 3


15. Create a table named as CLUB in database GAMES with appropriate data type
using SQL command of following structure and constraints: CoachID Primary Key,
CoachName Not Null, Age Not Null, Sports,DateOfApp,Pay,Sex.

Code
-- Step 1: Create the database

CREATE DATABASE GAMES;

-- Step 2: Use the database

USE GAMES;

-- Step 3: Create the table with specified constraints

CREATE TABLE CLUB (

CoachID INT PRIMARY KEY,

CoachName VARCHAR(50) NOT NULL,

Age INT NOT NULL,

Sports VARCHAR(30),

DateOfApp DATE,

Pay DECIMAL(10, 2),

Sex CHAR(1)

);

-- Step 4: Verify the table structure

DESCRIBE CLUB;
Output
After running the DESCRIBE CLUB; command, you will see a table structure similar to
this:
Field Type Null Key Default Extra

CoachID int NO PRI NULL

CoachName varchar(50) NO NULL

Age int NO NULL

Sports varchar(30) YES NULL

DateOfApp date YES NULL

Pay decimal(10,2) YES NULL

Sex char(1) YES NULL


16 Write Python interface program using MySQL to insert rows in table CLUB in
database GAMES

1, 'Kukreja',35,'Karate','1996/03/27',10000,'M';

2, 'Ravina',34,'Karate','1998-01-20',12000,'F';

3, 'Karan',32,'Squash','2000-02-19',20000,'M';

4,'Tarun',33,'Basket Ball','2005-01-01',15000,'M';

5 ,'Zubin',36,'Swimming','1998-02-24',7500,'M')

6 'Ketaki',33,'Swimming','2001-12-23',8000,'F'

Code
import [Link]

def insert_coaches_into_club():

"""

Connects to MySQL and inserts predefined data into the CLUB table.

"""

conn = None

cursor = None

try:

# Establish the connection to the MySQL server

# You will need to replace 'your_username' and 'your_password'

# with your actual MySQL credentials.

conn = [Link](
host="localhost",

user="your_username",

password="your_password",

database="GAMES" # Connect directly to the GAMES database

if conn.is_connected():

print("Successfully connected to the GAMES database.")

cursor = [Link]()

# SQL query for insertion

insert_query = """

INSERT INTO CLUB (CoachID, CoachName, Age, Sports, DateOfApp, Pay, Sex)

VALUES (%s, %s, %s, %s, %s, %s, %s)

"""

# Data to be inserted (List of tuples)

coaches_data = [

(1, 'Kukreja', 35, 'Karate', '1996-03-27', 10000, 'M'),

(2, 'Ravina', 34, 'Karate', '1998-01-20', 12000, 'F'),

(3, 'Karan', 32, 'Squash', '2000-02-19', 20000, 'M'),

(4, 'Tarun', 33, 'Basket Ball', '2005-01-01', 15000, 'M'),

(5, 'Zubin', 36, 'Swimming', '1998-02-24', 7500, 'M'),

(6, 'Ketaki', 33, 'Swimming', '2001-12-23', 8000, 'F')

]
# Execute the query for all rows at once using executemany

[Link](insert_query, coaches_data)

# Commit the changes to the database

[Link]()

print(f"Successfully inserted {[Link]} rows into the CLUB table.")

# Optional: Verify the insertions by fetching all data

[Link]("SELECT * FROM CLUB")

records = [Link]()

print("\nData currently in the CLUB table:")

for row in records:

print(row)

except [Link] as e:

print(f"Error connecting to MySQL: {e}")

finally:

# Close the cursor and connection

if cursor:

[Link]()

if conn and conn.is_connected():

[Link]()

print("\nMySQL connection is closed.")


# Run the function

if __name__ == "__main__":

insert_coaches_into_club()
Output
Successfully connected to the GAMES database.

Successfully inserted 6 rows into the CLUB table.

Data currently in the CLUB table:

(1, 'Kukreja', 35, 'Karate', [Link](1996, 3, 27), 10000.00, 'M')

(2, 'Ravina', 34, 'Karate', [Link](1998, 1, 20), 12000.00, 'F')

(3, 'Karan', 32, 'Squash', [Link](2000, 2, 19), 20000.00, 'M')

(4, 'Tarun', 33, 'Basket Ball', [Link](2005, 1, 1), 15000.00, 'M')

(5, 'Zubin', 36, 'Swimming', [Link](1998, 2, 24), 7500.00, 'M')

(6, 'Ketaki', 33, 'Swimming', [Link](2001, 12, 23), 8000.00, 'F')

MySQL connection is closed.


17 Write Python interface program using MySQL to retrieve details of coaches as
per the sport name input by user from table CLUB in database GAMES.

Code
import [Link]

def get_coaches_by_sport():

conn = None

cursor = None

try:

# Establish connection to the 'GAMES' database

conn = [Link](

host="localhost",

user="your_username",

password="your_password",

database="GAMES"

if conn.is_connected():

cursor = [Link]()

# User input for the sport name

search_sport = input("Enter the sport name to retrieve coach details: ")


# Parameterized SQL query to prevent SQL injection

query = "SELECT * FROM CLUB WHERE Sports = %s"

[Link](query, (search_sport,))

# Fetch all matching records

results = [Link]()

if results:

print(f"\nDetails of coaches for {search_sport}:")

print("-" * 80)

# Printing headers for clarity

print(f"{'ID':<5} {'Name':<15} {'Age':<5} {'Sport':<15} {'Appt Date':<12} {'Pay':<10} {'Sex'}")

print("-" * 80)

for row in results:

print(f"{row[0]:<5} {row[1]:<15} {row[2]:<5} {row[3]:<15} {str(row[4]):<12} {row[5]:<10}


{row[6]}")

else:

print(f"No records found for the sport: {search_sport}")

except [Link] as e:

print(f"Error: {e}")

finally:

if cursor:

[Link]()

if conn and conn.is_connected():

[Link]()
if __name__ == "__main__":

get_coaches_by_sport()
Output
Enter the sport name to retrieve coach details: Karate

Details of coaches for Karate:

--------------------------------------------------------------------------------

ID Name Age Sport Appt Date Pay Sex

--------------------------------------------------------------------------------

1 Kukreja 35 Karate 1996-03-27 10000.0 M

2 Ravina 34 Karate 1998-01-20 12000.0 F

If a user inputs "Tennis" (which is not in the data):


text
Enter the sport name to retrieve coach details: Tennis
No records found for the sport: Tennis
18. Write SQL statements for following based on table CLUB:

i)List all coaches whose sports is swimming or karate.

ii)List all details sorted in ascending order of age.

iii)Display Sports which have more than one coach.

iv)Display the number of Sports played in Club.

v)List all male Coaches having pay in range of 5000 to 10000

CODES
i) List all coaches whose sports is swimming or karate.
sql
SELECT * FROM CLUB
WHERE Sports = 'Swimming' OR Sports = 'Karate';
Output:
CoachID CoachName Age Sports DateOfApp Pay Sex

1 Kukreja 35 Karate 1996-03-27 10000 M

2 Ravina 34 Karate 1998-01-20 12000 F

5 Zubin 36 Swimming 1998-02-24 7500 M

6 Ketaki 33 Swimming 2001-12-23 8000 F

ii) List all details sorted in ascending order of age.


sql
SELECT * FROM CLUB
ORDER BY Age ASC;

Output:
CoachID CoachName Age Sports DateOfApp Pay Sex

3 Karan 32 Squash 2000-02-19 20000 M

4 Tarun 33 Basket Ball 2005-01-01 15000 M

6 Ketaki 33 Swimming 2001-12-23 8000 F

2 Ravina 34 Karate 1998-01-20 12000 F

1 Kukreja 35 Karate 1996-03-27 10000 M

5 Zubin 36 Swimming 1998-02-24 7500 M

iii) Display Sports which have more than one coach.


sql
SELECT Sports FROM CLUB
GROUP BY Sports
HAVING COUNT(*) > 1;
Output:
Sports

Karate

Swimming

iv) Display the number of Sports played in Club.


sql
SELECT COUNT(DISTINCT Sports) AS Total_Sports
FROM CLUB;
Output:
Total_Sports

v) List all male Coaches having pay in range of 5000 to 10000.


sql
SELECT * FROM CLUB
WHERE Sex = 'M' AND Pay BETWEEN 5000 AND 10000;
Output:
CoachID CoachName Age Sports DateOfApp Pay Sex

1 Kukreja 35 Karate 1996-03-27 10000 M

5 Zubin 36 Swimming 1998-02-24 7500 M


19 . Write Python interface program using MySQL to increase price by 10% in
table CUSTOMER of MYORG database.

CODE
import [Link]

def update_customer_prices():

try:

# Establish connection to the 'MYORG' database

conn = [Link](

host="localhost",

user="your_username",

password="your_password",

database="MYORG"

if conn.is_connected():

cursor = [Link]()

# SQL Query to increase price by 10%

# Multiplying by 1.1 increases the original value by 10%

update_query = "UPDATE CUSTOMER SET Price = Price * 1.10"


[Link](update_query)

# Permanent changes require a commit()

[Link]()

print(f"Update successful! {[Link]} rows were modified.")

# Optional: Display updated data

[Link]("SELECT * FROM CUSTOMER")

for row in [Link]():

print(row)

except [Link] as e:

print(f"Error while connecting to MySQL: {e}")

finally:

if conn.is_connected():

[Link]()

[Link]()

print("\nMySQL connection is closed.")

if __name__ == "__main__":

update_customer_prices()
OUTPUT
Update successful! 6 rows were modified.

(101, 'Amit Kumar', 'Delhi', 550.0, 2)

(102, 'Rohan Singh', 'Mumbai', 1320.0, 1)

(103, 'Sita Verma', 'Chennai', 22000.0, 1)

(104, 'Tarun Gupta', 'Kolkata', 16500.0, 3)

(105, 'Zubin Khan', 'Bangalore', 8250.0, 1)

(106, 'Ketaki Roy', 'Pune', 8800.0, 2)

MySQL connection is closed.


20. Write a Python interface program using MySQL to delete all those customers
whose name contains Kumar from table CUSTOMER in database MYORG.

CODE
import [Link]

def delete_customers_by_name():

conn = None

cursor = None

try:

# Establish connection to the 'MYORG' database

conn = [Link](

host="localhost",

user="your_username",

password="your_password",

database="MYORG"

if conn.is_connected():

cursor = [Link]()

# SQL Query to delete customers whose name contains 'Kumar'

# %Kumar% ensures it finds 'Kumar' anywhere in the string


delete_query = "DELETE FROM CUSTOMER WHERE Cname LIKE '%Kumar%'"

[Link](delete_query)

# Commit the changes to the database

[Link]()

# Display how many rows were deleted

if [Link] > 0:

print(f"Successfully deleted {[Link]} record(s) containing 'Kumar'.")

else:

print("No records found with the name containing 'Kumar'.")

except [Link] as e:

print(f"Error: {e}")

finally:

# Close the cursor and connection

if cursor:

[Link]()

if conn and conn.is_connected():

[Link]()

print("MySQL connection closed.")

if __name__ == "__main__":

delete_customers_by_name()
OUTPUT
If the table contained a customer named "Amit Kumar", the output would be:
text
Successfully deleted 1 record(s) containing 'Kumar'.
MySQL connection closed.

If no customers match the criteria:


text
No records found with the name containing 'Kumar'.
MySQL connection closed.
21.. Create following tables in database MYORG with appropriate data type using
SQL commands of following structure.

Table : Company Table Customer

CID Primary key CustId Primary Key

Name Not Null Name Not Null

City Not Null Price Not Null

Product Name Not Null Qty Check greater than 0

CID Foreign Key

CODE
-- Step 1: Create the database

CREATE DATABASE MYORG;

-- Step 2: Use the database

USE MYORG;

-- Step 3: Create the Company table

-- This table must be created first as it is referenced by the Customer table

CREATE TABLE Company (

CID INT PRIMARY KEY,

Name VARCHAR(100) NOT NULL,

City VARCHAR(50) NOT NULL,


Product_Name VARCHAR(100) NOT NULL

);

-- Step 4: Create the Customer table

-- Includes NOT NULL, CHECK, and FOREIGN KEY constraints

CREATE TABLE Customer (

CustId INT PRIMARY KEY,

Name VARCHAR(100) NOT NULL,

Price DECIMAL(10, 2) NOT NULL,

Qty INT NOT NULL CHECK (Qty > 0),

CID INT,

FOREIGN KEY (CID) REFERENCES Company(CID)

);

-- Verify the table structures

DESCRIBE Company;

DESCRIBE Customer;
OUTPUT
After executing the DESCRIBE commands, the system will display the schema details:
Table: Company
Field Type Null Key Default Extra

CID int NO PRI NULL

Name varchar(100) NO NULL

City varchar(50) NO NULL

Product_Name varchar(100) NO NULL

Table: Customer
Field Type Null Key Default Extra

CustId int NO PRI NULL

Name varchar(100) NO NULL

Price decimal(10,2) NO NULL

Qty int NO NULL

CID int YES MUL NULL


22. Write SQL commands to insert following data in above created tables
Company and Customer , also list all data .

Table:Customer

CustId Name Price Qty CID

101 Rohan Sharma 70000 20 222

102 Deepak 50000 10 666


Kumar

103 Mohan Kumar 30000 5 111

104 Sahil Bansal 35000 3 333

105 Neha Soni 25000 7 444

106 Sonal Agarwal 20000 5 333

107 Arjun Singh 50000 15 666

CODE
-- Use the database

USE MYORG;

-- Insert data into the Company table


INSERT INTO Company (CID, Name, City, Product_Name) VALUES

(111, 'Sony', 'Delhi', 'TV'),

(222, 'Nokia', 'Mumbai', 'Mobile'),

(333, 'Onida', 'Delhi', 'TV'),

(444, 'Blackberry', 'Mumbai', 'Mobile'),

(555, 'Samsung', 'Chennai', 'Mobile'),

(666, 'Dell', 'Delhi', 'Laptop');

-- Insert data into the Customer table

-- Note: CID must exist in the Company table first due to Foreign Key constraints

INSERT INTO Customer (CustId, Name, Price, Qty, CID) VALUES

(101, 'Rohan Sharma', 70000, 20, 222),

(102, 'Deepak Kumar', 50000, 10, 666),

(103, 'Mohan Kumar', 30000, 5, 111),

(104, 'Sahil Bansal', 35000, 3, 333),

(105, 'Neha Soni', 25000, 7, 444),

(106, 'Sonal Agarwal', 20000, 5, 333),

(107, 'Arjun Singh', 50000, 15, 666);

-- List all data from both tables

SELECT * FROM Company;

SELECT * FROM Customer;

OUTPUT
Table: Company
CID Name City Product_Name

111 Sony Delhi TV

222 Nokia Mumbai Mobile

333 Onida Delhi TV

444 Blackberry Mumbai Mobile

555 Samsung Chennai Mobile

666 Dell Delhi Laptop

Table: Customer
CustId Name Price Qty CID

101 Rohan Sharma 70000.00 20 222

102 Deepak Kumar 50000.00 10 666


103 Mohan Kumar 30000.00 5 111

104 Sahil Bansal 35000.00 3 333

105 Neha Soni 25000.00 7 444

106 Sonal Agarwal 20000.00 5 333

107 Arjun Singh 50000.00 15 666

23 Write SQL commands for the following queries based on tables Company and
Customer.

Display those company names having price less than 30000.

To increase price by 1000 for those customers whose name starts with ‘S’.
To display Company details in reverse alphabetical order.

To display customer details along with product name and company name of
the product.

To display details of companies based in Mumbai or Delhi.

CODE
i)Display those company names having price less than 30000
SELECT [Link]

FROM Company

JOIN Customer ON [Link] = [Link]

WHERE [Link] < 30000;

Output:
Name

Blackberry

Onida

ii)To increase price by 1000 for those customers whose name


starts with ‘S’.
UPDATE Customer

SET Price = Price + 1000

WHERE Name LIKE 'S%';

Output:
Query OK, 2 rows affected (Updated prices for Sahil Bansal and Sonal Agarwal)

iii)To display Company details in reverse alphabetical order.


SELECT * FROM Company
ORDER BY Name DESC;

Output:
CID Name City Product_Name

111 Sony Delhi TV

555 Samsung Chennai Mobile

333 Onida Delhi TV

222 Nokia Mumbai Mobile

666 Dell Delhi Laptop

444 Blackberry Mumbai Mobile

iv) To display customer details along with product name and


company name of the product.
SELECT Customer.*, Company.Product_Name, [Link] AS Company_Name

FROM Customer

JOIN Company ON [Link] = [Link];

Output:
CustId Name Price Qty CID Product_Name Company_Name

101 Rohan Sharma 70000 20 222 Mobile Nokia

102 Deepak Kumar 50000 10 666 Laptop Dell


103 Mohan Kumar 30000 5 111 TV Sony

104 Sahil Bansal 36000 3 333 TV Onida

105 Neha Soni 25000 7 444 Mobile Blackberry

106 Sonal Agarwal 21000 5 333 TV Onida

107 Arjun Singh 50000 15 666 Laptop Dell

v) To display details of companies based in Mumbai or Delhi.


SELECT * FROM Company

WHERE City IN ('Mumbai', 'Delhi');

Output:
CID Name City Product_Name

111 Sony Delhi TV

222 Nokia Mumbai Mobile

333 Onida Delhi TV

444 Blackberry Mumbai Mobile

666 Dell Delhi Laptop

24. Write Python interface program using MySQL to insert rows in table CLUB in
database GAMES.

Code
import [Link]
def insert_club_records():

conn = None

try:

# 1. Establish connection to the 'GAMES' database

# Replace 'your_username' and 'your_password' with your actual MySQL credentials

conn = [Link](

host="localhost",

user="your_username",

password="your_password",

database="GAMES"

if conn.is_connected():

cursor = [Link]()

# 2. Define the INSERT SQL statement with placeholders (%s)

sql = "INSERT INTO CLUB (CoachID, CoachName, Age, Sports, DateOfApp, Pay, Sex) VALUES (%s,
%s, %s, %s, %s, %s, %s)"

# 3. Define the data to be inserted as a list of tuples

records_to_insert = [

(7, 'Aman Verma', 40, 'Swimming', '2022-05-15', 12000, 'M'),

(8, 'Sita Iyer', 38, 'Karate', '2023-01-10', 15000, 'F'),

(9, 'Raj Malhotra', 45, 'Squash', '2021-11-20', 18000, 'M')

]
# 4. Execute the insertion

[Link](sql, records_to_insert)

# 5. Commit changes to make them permanent

[Link]()

print(f"Success: {[Link]} rows inserted into the CLUB table.")

except [Link] as e:

print(f"Error while connecting to MySQL: {e}")

finally:

# 6. Close the connection

if conn and conn.is_connected():

[Link]()

[Link]()

print("MySQL connection is closed.")

if __name__ == "__main__":

insert_club_records()

output
Success: 3 rows inserted into the CLUB table.

MySQL connection is closed.


25. Write Python interface program using MySQL to increase price by 10% in table
CUSTOMER of MYORG database.

Code
import [Link]
def update_customer_prices():

conn = None

cursor = None

try:

# Establish connection to the 'MYORG' database

conn = [Link](

host="localhost",

user="your_username",

password="your_password",

database="MYORG"

if conn.is_connected():

cursor = [Link]()

# SQL Query to increase price by 10%

# Multiplying by 1.10 is equivalent to adding 10%

update_query = "UPDATE CUSTOMER SET Price = Price * 1.10"

[Link](update_query)

# DML operations like UPDATE require a commit to save changes

[Link]()
print(f"Update successful! {[Link]} records were affected.")

# Optional: Display the updated data

[Link]("SELECT * FROM CUSTOMER")

print("\nUpdated CUSTOMER Table:")

for row in [Link]():

print(row)

except [Link] as e:

print(f"Error while connecting to MySQL: {e}")

finally:

# Close connection and cursor

if cursor:

[Link]()

if conn and conn.is_connected():

[Link]()

print("\nMySQL connection is closed.")

if __name__ == "__main__":

update_customer_prices()

output
Update successful! 7 records were affected.

Updated CUSTOMER Table:


(101, 'Rohan Sharma', 77000.0, 20, 222)

(102, 'Deepak Kumar', 55000.0, 10, 666)

(103, 'Mohan Kumar', 33000.0, 5, 111)

(104, 'Sahil Bansal', 39600.0, 3, 333)

(105, 'Neha Soni', 27500.0, 7, 444)

(106, 'Sonal Agarwal', 23100.0, 5, 333)

(107, 'Arjun Singh', 55000.0, 15, 666)

MySQL connection is closed.

26. Write a Python interface program using MySQL to delete all those customers
whose name contains Kumar from table CUSTOMER in database MYORG.

Code
import [Link]
def delete_customers_named_kumar():

conn = None

try:

# 1. Establish connection to 'MYORG' database

conn = [Link](

host="localhost",

user="your_username", # Replace with your MySQL username

password="your_password", # Replace with your MySQL password

database="MYORG"

if conn.is_connected():

cursor = [Link]()

# 2. SQL query to delete names containing 'Kumar'

# % represents zero or more characters

sql_query = "DELETE FROM CUSTOMER WHERE Name LIKE '%Kumar%'"

# 3. Execute the deletion

[Link](sql_query)

# 4. Commit changes (REQUIRED for DML operations like DELETE)

[Link]()
print(f"Update successful! {[Link]} records deleted.")

except [Link] as err:

print(f"Error: {err}")

finally:

# 5. Clean up connection

if conn and conn.is_connected():

[Link]()

[Link]()

print("MySQL connection closed.")

if __name__ == "__main__":

delete_customers_named_kumar()

Output
Update successful! 2 records deleted.

MySQL connection closed.

You might also like