0% found this document useful (0 votes)
26 views53 pages

Ram Prakash

Uploaded by

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

Ram Prakash

Uploaded by

bhavikaryan1810
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 53

PM SHRI KENDRIYA VIDYALA

NO.1 OE TRICHY

PRACTICAL FILE

SUBJECT : COMPUTER SCIENCE


NAME : K AKSHAYA
CLASS & SEC : XII ‘B’
SESSION : 2024-25
ROLL NO:

Page | 1
CERTIFICATE

This is to certify that computer science


practical has been successfully completed
by
K Akshaya of class XII ‘B’ during the
session 2024-25 as per the prescribed
syllabus of CBSE

SIGNATURE OF INTERNAL EXAMINER

SIGNATURE OF EXTERNAL EXAMINER

SIGNATURE OF PRINCIPAL
Page | 2
INDEX
S NO. PRACTICAL PAGE NO. SIGNATURE
1. PRACTICAL 1
2. PRACTICAL 2
3. PRACTICAL 3
4. PRACTICAL 4
5. PRACTICAL 5
6. PRACTICAL 6
7. PRACTICAL 7
8. PRACTICAL 8
9. PRACTICAL 9
10. PRACTICAL 1O
11. PRACTICAL 11
12. PRACTICAL 12
13. PRACTICAL 13
14. PRACTICAL 14
15. PRACTICAL 15
16. PRACTICAL 16
17. PRACTICAL 17
18. PRACTICAL 18
19. PRACTICAL 19
20. PRACTICAL 20
21. PRACTICAL 21
22. PRACTICAL 22
23. PRACTICAL 23
24. PRACTICAL 24
25. PRACTICAL 25
26. PRACTICAL 26

Page | 3
PRACTICAL 1
AIM : To write a menu driven program using functions in python to check a number
- prime or not.
- palindrome or not
- factorial of number

CODE:
# Function to check if a number is prime

def is_prime(num):

if num <= 1:

return False

for i in range(2, int(num**0.5) + 1):

if num % i == 0:

return False

return True

# Function to check if a number is

palindrome

def is_palindrome(num):

return str(num) == str (num)[::-1]

# Function to calculate factorial of a number

def factorial(num):

fact = 1

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

fact *= i

return fact

# Menu driven program

while True:

print("\nMenu:")

print("1. Check if a number is Prime")

Page | 4
print("2. Check if a number is Palindrome")

print("3. Calculate Factorial")

print("4. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:

num = int(input("Enter a number to check if it is prime: "))

if is_prime(num):

print(f"{num} is a prime number.")

else:

print(f"{num} is not a prime number.")

elif choice == 2:

num = int(input("Enter a number to check if it is a palindrome:

")) if is_palindrome(num):

print(f"{num} is a palindrome.")

else:

print(f"{num} is not a palindrome.")

elif choice == 3:

num = int(input("Enter a number to calculate its factorial: "))

print(f"The factorial of {num} is {factorial(num)}")

elif choice == 4:

print("Exiting the program.")

break

else:

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

OUTPUT:

Page | 5
Page | 6
PRACTICAL 2
AIM : To write a python program using function named largest(a,b,c) which will accept 3 numbers as
parameters and return the largest one. Use the concept of KEYWORD parameters.

CODE :
# Function to find the largest of three

numbers

def largest(a, b, c):

return max(a, b, c)

num1 = int(input("Enter the first number: "))

num2 = int(input("Enter the second number: "))

num3 = int(input("Enter the third number: "))

# Calling the function

print(f"The largest number is: {largest(a=num1, b=num2, c=num3)}")

OUTPUT :

Page | 7
PRACTICAL 3
AIM : To Write a program to calculate compound interest using function named compint(P,r,n,t) ,where
the default value of rate( r) is 10.

CODE :
# Function to calculate compound interest with default rate

def compint(P, r=10, n, t):

return P * (1 + r / 100) ** (n * t)

P = float(input("Enter the principal amount: "))

n = int(input("Enter the number of times interest is compounded per year: "))

t = float(input("Enter the time period in years: "))

#calling function

compound_interest = compint(P, n=n, t=t)

print(f"The compound interest is: {compound_interest}")

OUTPUT :

Page | 8
PRACTICAL 4
AIM : To Write a program using function to print Fibonacci series upto n terms. Give default value of n as
15

CODE :
# Function to print Fibonacci series up to n terms

def fibonacci(n=15):

a, b = 0, 1

print("Fibonacci Series:")

for _ in range(n):

print(a, end=" ")

a, b = b, a + b

n_terms = input("Enter the number of terms for Fibonacci series (default is 15): ")

n_terms = int(n_terms) if n_terms else 15

# Call the function

fibonacci(n_terms)

OUTPUT :

Page | 9
PROGRAM 5
AIM : To write a program to generate 10 random numbers between 1 to 100

CODE :
import random

# Function to generate 10 random numbers between 1 and 100

def generate_random_numbers():

random_numbers = [random.randint(1, 100) for _ in range(10)]

return random_numbers

print("10 Random numbers between 1 and 100:")

print(generate_random_numbers())

OUTPUT :

Page | 10
PRACTICAL 6
AIM : To Write a program to generate the following series

CODE :
# Pattern-1: *

print("Pattern-1:")

rows = int(input("Enter the number of rows for Pattern-1: "))

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

print('*' * i)

# Pattern-2: 1 2 3 4

5 print("\nPattern-

2:")

rows = int(input("Enter the number of rows for Pattern-2: "))

for i in range(rows, 0, -1):

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

print(j, end=' ')

print()

# Pattern-3: A, AB,

ABC

print("\nPattern-3:")

rows = int(input("Enter the number of rows for Pattern-3: "))

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

for j in range(i):

print(chr(65 + j), end='') # chr(65) is 'A', chr(66) is 'B', etc.


Page | 11
print()

Page | 12
OUTPUT :

Page | 13
PRACTICAL 7
AIM : Write a program to enter a list and find the largest and smallest element in the list.

CODE :
# Program to find the largest and smallest element in a list

lst = list(map(int, input("Enter a list of numbers separated by space: ").split()))

largest = max(lst)

smallest = min(lst)

print(f"The largest element in the list is: {largest}")

print(f"The smallest element in the list is: {smallest}")

OUTPUT :

Page | 14
PRACTICAL 8
AIM : Write a program to enter a list and replace the even elements by their square and odd by their cube

CODE :
# Program to replace even elements by their square and odd elements by their cube

lst = list(map(int, input("Enter a list of numbers separated by space: ").split()))

for i in range(len(lst)):

if lst[i] % 2 == 0:

lst[i] = lst[i] ** 2

else:

lst[i] = lst[i] ** 3

print(f"The modified list is: {lst}")

OUTPUT :

Page | 15
PRACTICAL 9
AIM : Write a program to enter a tuple and find the sum and average of all the elements

CODE :
# Program to calculate sum and average of elements in a tuple

tup = tuple(map(int, input("Enter numbers for the tuple separated by space: ").split()))

total_sum = sum(tup)

average = total_sum / len(tup) if len(tup) > 0 else 0

print(f"The sum of the elements in the tuple is: {total_sum}")

print(f"The average of the elements in the tuple is: {average}")

OUTPUT :

Page | 16
PRACTICAL10
AIM : Write a program to create a dictionary having names of your friends as keys and their phone number
as values

CODE :
# Program to create a dictionary with friends' names and their phone

numbers

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

phonebook = {}

for _ in range(n):

name = input("Enter friend's name: ")

phone = input(f"Enter {name}'s phone number: ")

phonebook[name] = phone

print("\nFriends' Phonebook:")

for name, phone in phonebook.items():

print(f"{name}: {phone}")

OUTPUT :

Page | 17
PRACTICAL 11
AIM : To Write a python program to read and display text file content with each word separated by #.

CODE :

def display_file_content_with_hash():
filename = input("Enter the filename: ")
try:
with open(filename, 'r') as file:
content = file.read()
words = content.split()
print('#'.join(words))
except FileNotFoundError:
print(f"File '{filename}' not found.")

# Call the function


display_file_content_with_hash()

OUTPUT:

Page | 18
PRACTICAL 12
AIM : To write a python program to copy all the lines that contain the character ‘a’ in a text file “file1.txt”
to another file “file2.txt”.

CODE :
def copy_lines_containing_a():

source_file = input("Enter the source filename: ")

target_file = input("Enter the target filename: ")

try:

with open(source_file, 'r') as file1, open(target_file, 'w') as file2:

for line in file1:

if 'a' in line:

file2.write(line)

print(f"Lines containing 'a' have been copied to {target_file}.")

except FileNotFoundError:

print(f"File '{source_file}' or '{target_file}' not found.")

# Call the function

copy_lines_containing_a()

OUTPUT :

Page | 19
PRACTICAL 13
AIM : To write a menu driven program using functions to find the following in text file “story.txt”
● Upper case letters
● Lower case letters
● Digits
● Spaces
● vowels

CODE :
def count_uppercase(file):

return sum(1 for char in file if char.isupper())

def count_lowercase(file):

return sum(1 for char in file if char.islower())

def count_digits(file):

return sum(1 for char in file if char.isdigit())

def count_spaces(file):

return sum(1 for char in file if char == ' ')

def count_vowels(file):

vowels = "aeiouAEIOU"

return sum(1 for char in file if char in vowels)

def analyze_text_file():

filename = input("Enter the filename: ")

try:

with open(filename, 'r') as file:

content = file.read()

print("Select an option:")

Page | 20
print("1. Uppercase letters")

print("2. Lowercase letters")

print("3. Digits")

print("4. Spaces")

print("5. Vowels")

choice = int(input("Enter your choice: "))

if choice == 1:

print(f"Uppercase letters count: {count_uppercase(content)}")

elif choice == 2:

print(f"Lowercase letters count: {count_lowercase(content)}")

elif choice == 3:

print(f"Digits count: {count_digits(content)}")

elif choice == 4:

print(f"Spaces count: {count_spaces(content)}")

elif choice == 5:

print(f"Vowels count: {count_vowels(content)}")

else:

print("Invalid choice.")

except FileNotFoundError:

print(f"File '{filename}' not found.")

# Call the function

analyze_text_file()

OUTPUT :

Page | 21
Page | 22
PRACTICAL 14
AIM : Write a menu driven program using functions to count following in text file “story.txt”
● Total words
● Words having length 5
● “hello”

CODE :
def count_total_words(file):

return len(file.split())

def count_words_of_length_5(file):

return sum(1 for word in file.split() if len(word) == 5)

def count_hello(file):

return file.split().count('hello')

def analyze_word_counts():

filename = input("Enter the filename: ")

try:

with open(filename, 'r') as file:

content = file.read()

print("Select an option:")

print("1. Total words")

print("2. Words with length 5")

print("3. Count occurrences of 'hello'")

choice = int(input("Enter your choice: "))

if choice == 1:

print(f"Total words: {count_total_words(content)}")

elif choice == 2:

Page | 23
print(f"Words of length 5: {count_words_of_length_5(content)}")

elif choice == 3:

print(f"Occurrences of 'hello': {count_hello(content)}")

else:

print("Invalid choice.")

except FileNotFoundError:

print(f"File '{filename}' not found.")

# Call the function

analyze_word_counts()

OUTPUT :

Page | 24
PRACTICAL 15
AIM :To write a menu driven program to find the following in text file “story.txt”
● To count lines starting with ‘P’ or ‘T’
● To count lines starting with vowels

CODE :
def count_lines_starting_with_pt(file):

return sum(1 for line in file if line.strip().startswith(('P', 'T')))

def count_lines_starting_with_vowel(file):

vowels = ('A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u')

return sum(1 for line in file if line.strip().startswith(vowels))

def analyze_lines():

filename = input("Enter the filename: ")

try:

with open(filename, 'r') as file:

lines = file.readlines()

print("Select an option:")

print("1. Count lines starting with 'P' or 'T'")

print("2. Count lines starting with vowels")

choice = int(input("Enter your choice: "))

if choice == 1:

print(f"Lines starting with 'P' or 'T': {count_lines_starting_with_pt(lines)}")

elif choice == 2:

print(f"Lines starting with vowels: {count_lines_starting_with_vowel(lines)}")

else:

print("Invalid choice.")

except FileNotFoundError:

Page | 25
print(f"File '{filename}' not found.")

# Call the function

analyze_lines()

OUTPUT :

Page | 26
PRACTICAL 16
AIM : To Write a python program to create a binary file with roll number, name and address. Search for a
given roll number and display name and address , if not found display appropriate message.

CODE :
import pickle

def create_binary_file():

with open('students.dat', 'wb') as file:

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

for _ in range(n):

roll_no = int(input("Enter roll number: "))

name = input("Enter name: ")

address = input("Enter address: ")

student = (roll_no, name, address)

pickle.dump(student, file)

def search_roll_number():

roll_no_to_search = int(input("Enter roll number to search: "))

found = False

with open('students.dat', 'rb') as file:

try:

while True:

student = pickle.load(file)

if student[0] == roll_no_to_search:

print(f"Name: {student[1]}\nAddress: {student[2]}")

found = True

break

except EOFError:

if not found:

print("Roll number not found.")


Page | 27
# Creating the binary file

create_binary_file()

# Searching for a roll number

search_roll_number()

OUTPUT :

Page | 28
PRACTICAL 17
AIM : To write a python program to create a binary file with roll number, name and marks, input a roll
number and update the marks

CODE :
import pickle

def create_binary_file():

with open('marks.dat', 'wb') as file:

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

for _ in range(n):

roll_no = int(input("Enter roll number: "))

name = input("Enter name: ")

marks = float(input("Enter marks: "))

student = (roll_no, name, marks)

pickle.dump(student, file)

def update_marks():

roll_no_to_update = int(input("Enter roll number to update marks: "))

found = False

students = []

with open('marks.dat', 'rb') as file:

try:

while True:

student = pickle.load(file)

if student[0] == roll_no_to_update:

new_marks = float(input(f"Enter new marks for {student[1]}: "))

student = (student[0], student[1], new_marks)

Page | 29
found = True

students.append(student)

except EOFError:

pass

if found:

with open('marks.dat', 'wb') as file:

for student in students:

pickle.dump(student, file)

print("Marks updated successfully.")

else:

print("Roll number not found.")

# Create the binary file

create_binary_file()

# Update marks for a roll number

update_marks()

OUTPUT :

Page | 30
PRACTICAL 18
AIM : A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].
i. Write a user defined function CreateFile() to input data for a record and add to Book.dat .
ii. Write a function CountRec(Author) in Python which accepts the Author name as parameter and count and
return number of books by the given Author are stored in the binary file “Book.dat”

CODE :
import pickle

def create_file():

with open('Book.dat', 'ab') as file:

while True:

book_no = int(input("Enter Book Number: "))

book_name = input("Enter Book Name: ")

author = input("Enter Author Name: ")

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

book = (book_no, book_name, author, price)

pickle.dump(book, file)

more = input("Do you want to add more books (y/n)? ")

if more.lower() != 'y':

break

def count_rec(author_name):

count = 0

with open('Book.dat', 'rb') as file:

try:

while True:

book = pickle.load(file)

if book[2].lower() == author_name.lower():

count += 1

except EOFError:

pass
Page | 31
return count

# Create book file

create_file()

# Count books by a specific author

author_name = input("Enter author name to count their books: ")

count = count_rec(author_name)

print(f"Number of books by {author_name}: {count}")

OUTPUT :

Page | 32
PRACTICAL 19
AIM : . A binary file “STUDENT.DAT” has structure (admission_number, Name, Percentage). Write a function
countrec() in Python that would read contents of the file “STUDENT.DAT” and display the details of those students
whose percentage is above 75. Also display number of students scoring above 75%

CODE :
import pickle

def count_rec():

count = 0

with open('STUDENT.DAT', 'rb') as file:

try:

while True:

student = pickle.load(file)

if student[2] > 75:

print(f"Admission Number: {student[0]}, Name: {student[1]}, Percentage: {student[2]}")

count += 1

except EOFError:

pass

print(f"Total number of students with percentage above 75: {count}")

# Call function

count_rec()

OUTPUT :

Page | 33
PRACTICAL 20
AIM : To write a python program to create a CSV file with empid, name and mobile no. and search empid,
update the record and display the records.

CODE :
import csv

def create_csv_file():

with open('employee.csv', 'w', newline='') as file:

writer = csv.writer(file)

writer.writerow(['EmpID', 'Name', 'MobileNo'])

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

for _ in range(n):

emp_id = input("Enter Employee ID: ")

name = input("Enter Name: ")

mobile_no = input("Enter Mobile Number: ")

writer.writerow([emp_id, name, mobile_no])

def search_and_update_record():

emp_id_to_search = input("Enter EmpID to search: ")

found = False

rows = []

with open('employee.csv', 'r', newline='') as file:

reader = csv.reader(file)

for row in reader:

if row[0] == emp_id_to_search:

print(f"Found: {row}")

new_name = input("Enter new name: ")

Page | 34
new_mobile = input("Enter new mobile number: ")

row[1] = new_name

row[2] = new_mobile

found = True

rows.append(row)

if found:

with open('employee.csv', 'w', newline='') as

file: writer = csv.writer(file)

writer.writerows(rows)

print("Record updated successfully.")

else:

print("Employee ID not found.")

# Create CSV file

create_csv_file()

# Search and update employee record

search_and_update_record()

OUTPUT :

Page | 35
PRACTICAL 21

AIM : To write a Program in Python to create a stack named ‘book’ which contains these book details :
(bookno, book name). That is, now each item node ofthe stack containstwo types of information – a
bookno and its name. Implement Push, Pop, and Traversal operations on the stack.

CODE :
class Stack:

def init (self):

self.stack = []

def push(self, bookno, bookname):

self.stack.append((bookno, bookname))

def pop(self):

if not self.is_empty():

return self.stack.pop()

else:

print("Stack is empty.")

def is_empty(self):

return len(self.stack) == 0

def traverse(self):

if not self.is_empty():

for book in self.stack:

print(book)

else:

print("Stack is empty.")

# Create stack
Page | 36
book_stack = Stack()

# Push books

book_stack.push(1, "Python Programming")

book_stack.push(2, "Data Structures")

# Traverse stack

book_stack.traverse()

# Pop book

book_stack.pop()

book_stack.traverse()

OUTPUT :

Page | 37
PRACTICAL 22
AIM : To find each node of a STACK contains the following information: (i) Pin code of a city, (ii) Name of
city. Write a program to implement following operations on above stack.

(a.) PUSH( ) – To push a node into the stack.


(b.) POP( ) – To remove a node from the stack

CODE :
class CityStack:

def init (self):

self.stack = []

def push(self, pin_code, city_name):

self.stack.append((pin_code, city_name))

def pop(self):

if not self.is_empty():

return self.stack.pop()

else:

print("Stack is empty.")

def is_empty(self):

return len(self.stack) == 0

def traverse(self):

if not self.is_empty():

for city in self.stack:

print(city)

else:

print("Stack is empty.")

Page | 38
# Create stack

city_stack = CityStack()

# Push city

city_stack.push(110001, "Delhi")

city_stack.push(500001, "Hyderabad")

# Traverse stack

city_stack.traverse()

# Pop city

city_stack.pop()

city_stack.traverse()

OUTPUT :

Page | 39
PRACTICAL 23
AIM : To Write a python program to create stack Sport_Stack to store age of sportsman using
stack implementation as list. Write Operation for Push, Pop and Traversal operation using menu.

CODE :
class SportStack:
def init (self):
self.stack = []

def push(self, age):


self.stack.append(age)

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

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

def traverse(self):
if not self.is_empty():
for age in self.stack:
print(age)
else:
print("Stack is empty.")

# Create stack
sport_stack = SportStack()

# Push sportsman's age


sport_stack.push(23)
sport_stack.push(30)

# Traverse stack
sport_stack.traverse()

# Pop sportsman's age


sport_stack.pop()
sport_stack.traverse()

OUTPUT :

Page | 40
Page | 41
PRACTICAL 24
AIM:Create a CLUB table as mentioned with given data type and constraints. Table - CLUB

Field Name Data Type Data Limit Constraint


coach_id Int (3,0)
coachname Text 15 char NOT NULL
age Int (2,0)
sports Char 10
datofapp Date
pay Numeric (7,2) Pay > 0
sex Char 1 Default value ‘M’

and insert data as given below in this using suitable SQL statements.
COACH_ COACHNAM AGE SPORTS DATOFAP PAY SEX
ID E P
1 KUKREJA 35 KARATE 27/03/1996 1000 M
2 RAVINA 34 KARATE 20/01/1998 1200 F
3 KARAN 34 SQUASH 19/02/1998 2000 M
4 TARUN 33 BASKETBALL 01/01/1998 1500 M
5 ZUBIN 36 SWIMMING 12/01/1998 750 M
6 KETAKI 36 SWIMMING 24/02/1998 800 F
7 ANKITA 39 SQUASH 20/02/1998 2200 F
8 ZAREEN 37 KARATE 22/02/1998 1100 F
9 KUSH 41 SWIMMING 13/01/1998 NULL M
10 SHAILYA 37 BASKETBALL 19/02/1998 1700 M

Write SQL commands for the following –


1.) Alter table to make coach_id as primary key.
2.) Change the size of coachname field to 20 characters.
3.) Add new column ‘participants_no’ having integer data type in table.
4.) Remove above added column.
5.) Make ‘swimming’ as default value for sports.
6.) To display number of records in a table.
7.) To display sports name distinctly.
8.) To show all the information about the swimming coaches in the club .
9.) To list names of all coaches with their date of appointment (DATOFAPP) in
descending order.
10.) To display number of coaches in each sports.
11.) To display number of coaches who are being paid.
12.) To display a report , showing coachname , pay, age and bonus (15% of pay) for all
the coaches.[ the name of the field 15% of pay should be ‘Bonus’ ]
13.) To display total no. of male and female coaches individually.
14.) To display detail of the coach who appointed first.
Page | 41
15.) To display coachname in which name contains 2nd character as ‘A’.
16.) To print details of the coaches who are appointed in the month of
February 1998. 17.) To display average payment of all coaches.
18.) To display detail of the coaches whose age lies between 30 to 35.
19.) Update name of the coach as ‘KUSHA’ having coach id is 9.
20.) Remove the details of all coaches playing ‘karate’ and pay is 1000 or below.

CODE: CREATE TABLE CLUB (


coach_idINT(3,0),
coachnameTEXT(15) NOT NULL,
age INT(2,0),
sports CHAR(10),
datofapp DATE,
pay NUMERIC(7,2) CHECK (pay > 0),
sex CHAR(1) DEFAULT 'M');

INSERT INTO CLUB (coach_id, coachname, age, sports, datofapp, pay, sex) VALUES
(1, 'KUKREJA', 35, 'KARATE', '1996-03-27', 1000, 'M'),
(2, 'RAVINA', 34, 'KARATE', '1998-01-20', 1200, 'F'),
(3, 'KARAN', 34, 'SQUASH', '1998-02-19', 2000, 'M'),
(4, 'TARUN', 33, 'BASKETBALL', '1998-01-01', 1500, 'M'),
(5, 'ZUBIN', 36, 'SWIMMING', '1998-01-12', 750, 'M'),
(6, 'KETAKI', 36, 'SWIMMING', '1998-02-24', 800, 'F'),
(7, 'ANKITA', 39, 'SQUASH', '1998-02-20', 2200, 'F'),
(8, 'ZAREEN', 37, 'KARATE', '1998-02-22', 1100, 'F'),
(9, 'KUSH', 41, 'SWIMMING', '1998-01-13', NULL, 'M'),
(10, 'SHAILYA', 37, 'BASKETBALL', '1998-02-19', 1700, 'M');

1. ALTER TABLE CLUB ADD PRIMARY KEY (coach_id);


2. ALTER TABLE CLUB MODIFY coachname TEXT(20);
3. ALTER TABLE CLUB ADD participants_no INT;
4. ALTER TABLE CLUB DROP COLUMN participants_no;
5. ALTER TABLE CLUB MODIFY sports CHAR(10) DEFAULT 'SWIMMING';
6. SELECT COUNT(*) AS record_count FROM CLUB;
7. SELECT DISTINCT sports FROM CLUB;
8. SELECT * FROM CLUB WHERE sports = 'SWIMMING';
9. SELECT coachname, datofapp FROM CLUB ORDER BY datofapp DESC;
10. SELECT sports, COUNT(*) AS coach_count FROM CLUB GROUP BY sports;
11. SELECT COUNT(*) AS paid_coaches FROM CLUB WHERE pay IS NOT NULL;
12. SELECT coachname, pay, age, (pay * 0.15) AS Bonus FROM CLUB;
13. SELECT sex, COUNT(*) AS count FROM CLUB GROUP BY sex;
14. SELECT * FROM CLUB ORDER BY datofapp ASC LIMIT 1;
15. SELECT coachname FROM CLUB WHERE coachname LIKE '_A%';
16. SELECT * FROM CLUB WHERE MONTH(datofapp) = 2 AND YEAR(datofapp) = 1998;
17. SELECT AVG(pay) AS avg_payment FROM CLUB WHERE pay IS NOT NULL;
18. SELECT * FROM CLUB WHERE age BETWEEN 30 AND 35;
19. UPDATE CLUB SET coachname = 'KUSHA' WHERE coach_id = 9;
20. DELETE FROM CLUB WHERE sports = 'KARATE' AND pay <= 1000;

OUTPUT:

Page | 42
Page | 43
Page | 44
Page | 45
PRACTICAL 25

AIM:In a database there are two tables “Product” and “Client” as shown below
:Table – Product
P_ID Product_Name Manufacture Price

P001 Moisturiser XYZ 40


Sanitizer LAC 35
P002 Bath Soap COP 25
Shampoo TAP 95
P003 Lens Solution COP 350

P004

P005

Table – Client
C_ID ClientName City P_ID
01 Dreamz Disney New Delhi P002
05 Life Line Inc Mumbai P005
12 98.4 New Delhi P001
15 Appolo Banglore P003
Write the commands in SQL queries for the following:
1.) To display the details of product whose price is in range of 40 and 120 ( both
values included).
2.) To display the client name , city from table client and product name and price from
table product , with their corresponding matching P_ID.
3.) To increase the price of all the products by 20.
4.) To display product details where client belongs to ‘New Delhi’.
5.) To list all the products who do not have any client in ‘New Delhi’ and ‘Mumbai’
.
6.) To display number of clients in each city.
7.) To list all the clients having product price maximum rs. 50.
8.) To display product name and its price with decreasing order of price.
9.) To display total no. of products.
10.) Show the average price for all products.

CODE:
1. SELECT * FROM Product WHERE Price BETWEEN 40 AND 120;
2. SELECT Client.ClientName, Client.City, Product.Product_Name, Product.Price FROM Client
INNER JOIN Product ON Client.P_ID = Product.P_ID;
3. UPDATE Product SET Price = Price + 20;
4. SELECT Product.* FROM Product INNER JOIN Client ON Product.P_ID = Client.P_ID
WHERE Client.City = 'New Delhi';
5. SELECT * FROM Product WHERE P_ID NOT IN (SELECT P_ID FROM Client WHERE City
IN ('New Delhi', 'Mumbai'));
6. SELECT City, COUNT(*) AS ClientCount FROM Client GROUP BY City;
Page | 46
7. SELECT Client.ClientName FROM Client INNER JOIN Product ON Client.P_ID =
Product.P_ID WHERE Product.Price<= 50;
8. SELECT Product_Name, Price FROM Product ORDER BY Price DESC;
9. SELECT COUNT(*) AS TotalProducts FROM Product;
10. SELECT AVG(Price) AS AveragePrice FROM Product;

OUTPUT:

Page | 47
Page | 48
PRACTICAL 26
AIM:Write a menu-driven program which integrates MySQL and Python connectivity with
the table BOOKS whose content is given below. Create the database named LIBRARY.
Database Name- LIBRARY
Table Name- BOOKS
Make Book_id as the primary key.
Write the following functions for the same
a) Adding record
b) Deleting record
c) Updating record
d) Searching record
e) Showing all data

CODE:import mysql.connector

def connect_to_database():
return mysql.connector.connect(
host="host",
user="root",
password="1234",
database= "library"
)

def create_table():
db = connect_to_database()
cursor = db.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS BOOKS
( Book_id INT PRIMARY KEY,
Book_nameVARCHAR(255),
Author VARCHAR(255),
Price DECIMAL(10, 2)
)
""")
db.commit()
cursor.close()
db.close()
print("Table created successfully.")

def insert_book():
db = connect_to_database()
cursor = db.cursor()
book_id = int(input("Enter Book ID: "))
book_name = input("Enter Book Name: ")
author = input("Enter Author Name: ")
price = float(input("Enter Book Price: "))

cursor.execute("""
INSERT INTO BOOKS (Book_id, Book_name, Author, Price)
VALUES (%s, %s, %s, %s)
Page | 49
""", (book_id, book_name, author, price))

db.commit()
cursor.close()
db.close()
print("Book inserted successfully.")

def display_books():
db = connect_to_database()
cursor = db.cursor()
cursor.execute("SELECT * FROM BOOKS")
books = cursor.fetchall()
if books:
for book in books:
print(f"Book ID: {book[0]}, Book Name: {book[1]}, Author: {book[2]}, Price: {book[3]}")
else:
print("No books found.")
cursor.close()
db.close()

def update_book():
db = connect_to_database()
cursor = db.cursor()
book_id = int(input("Enter Book ID to update: "))
new_price = float(input("Enter new price for the book: "))

cursor.execute("""
UPDATE BOOKS
SET Price = %s
WHERE Book_id = %s
""", (new_price, book_id))

db.commit()
cursor.close()
db.close()
print("Book price updated successfully.")

def delete_book():
db = connect_to_database()
cursor = db.cursor()
book_id = int(input("Enter Book ID to delete: "))

cursor.execute("""
DELETE FROM BOOKS
WHERE Book_id = %s
""", (book_id,))

db.commit()
cursor.close()
db.close()
print("Book deleted successfully.")

Page | 50
def main():
while True:
print("\nLIBRARY MENU")
print("1. Create Table")
print("2. Insert Book")
print("3. Display All Books")
print("4. Update Book Price")
print("5. Delete Book")
print("6. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:
create_table()
elif choice == 2:
insert_book()
elif choice == 3:
display_books()
elif choice == 4:
update_book()
elif choice == 5:
delete_book()
elif choice == 6:
print("Exiting...")
break
else:
print("Invalid choice! Please try again.")

if _name_ == "_main_":
main()

OUTPUT:

Page | 51
Page | 52

You might also like