Program 20

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 50

Session:

Session:2014-15

REPORT FILE
COMPUTER SCIENCE

(PYTHON)

Submitted to: Submitted By:


MS. KUMUD CHAUHAN SHIVAM SAINI
(P.G.T. COMPUTER SCIENCE) CLASS : XII
“THOMAS EDISON”
Roll No.-
An understanding of the study like is never the
outcomes of the effort of the single person;
rather it bears the imprint of a number of
persons who directly or indirectly help us in
completing the present study. We should be
falling in our duty if we don’t say a word of
thanks to all those whose sincere advice made
my project a real educative and pleasurable one.
We take this opportunity to express my
profound sense of gratitude and respect to all
those who help me throughout the duration of
this project.
We sincerely thanks to our respected Principal
Mr. D.S. Negi,
Priyanka Modern School, Dhampur.
A project work is not more an experiment in the lab but is
something
more in which students deals with a number of problems,
conducts
number of experiments, consults with a number of people at
different
aspects of life and finally finding the solutions for the
problems from
which the hypothesis made. So, it creates a team spirit in
the students,
develops various skill like observations, handling of
experiments, test of investigation, making of assumptions
and hypothesis. Project work
exploits the hidden abilities and capabilities of individuals.
So it is to be appreciated that Central Board of Secondary
Education for giving us a chance to work on project.
INDEX
1. WAF to find weather a string is
PALINDROME or not.
2. WAF to calculate Factorial of a given
Number.
3. WAF to count upper case and lower case letters
in a given string.
4. Write a python program to pass a string to a
function and count how many vowels are present
in the string.
5. WAF to search an element in a list and display the
frequency of element present inlist and their
location using Linear search by using user define
function.
[List and search element should be entered by
user]
6. MAKE A MENU DRIVEN PROGRAM USNING
FUNCTION TO ACCESS THEM.
1. AREA OF SQUARE
2. AREA OF CIRLCE
3. AREA OF RECTANGLE
4. PERIMETER OF SQUARE
5. PERIMETER OF CIRCLE
7. Write a python program to pass list to a function
and double the odd values and half even values of
a list and display list element after changing.
8. Write a function namely nth root() that receives
two parameter x and n and return nth root of x i.e.
x1/n. the default value of n is 2.
9. WAF to count and print lines that start with "H"
in file “Story.txt”
10. A binary file “book. dat” has structure
[book no, book_name, author , price]
a.) Write a user defined function create file() to
input data for a record and add to book.dat.
b.) Write a function countReac(author) in python
which acceps the author name as a parameter
and count and no. of books by the given
author are stored in the binary file
“Book.dat”.
11. Write a python program to create a binary file
with name and roll number. Search for a given
roll number and display name ,if not found
display appropriate message.
12. A binary file named”TEST.dat” has some records
of the structure
[Test id, subject, max marks, scored marks]
Write a function in python named display avg.
marks(sub) that will accept a subject as an
argument and read the contents of TEST.dat the
function will calculate and display the average of
the scored marks of the passes subject on screen.

13. Write a Python program to function with key


and value, and update value at that key in
dictionary entered by user.
14. Write a program to know the cursor position and
print the text according to below-given specifications:
a) Print the initial position
b) Move the cursor to 4th position
c) Display next 5 characters
d) Move the cursor to the next 10 characters
e) Print the current cursor position
f) Print next 10 characters from the current cursor
position
15. Write a Python program to implement a stack using list
(PUSH & POP Operation on Stack).
16. A dictionary that stores Product names as key and price
as values. Write a user-defined function to perform the
following operations:
•Push the values into the stack if the price of products is
greater than 300.
•Pop and display the contents of the stack.
For example, if the content of the dictionary is as
follows: product={‘Book’:250, ‘Pen’:120, ‘Pencil’:50,
‘Notebook’:400, ‘Register’:480} The elements of the
stack should be: [250, 400, 480]
17. Write a python program using function POP(Arr),
where Arr is a stack implemented by a list of numbers.
The function returns the value deleted from the stack.
18. Prateek has created a list arr with some elements. Help
him to create a user-defined function to perform the
following tasks:
*Create a stack after checking the elements if it is
even then multiply by 2 and if the element is odd,
then multiply it by 3.
* Pop and display the contents of the stack.
19. Integrate MySQL with Python by importing the
MySQL module and add records of student and display
all the record.
20. Integrate SQL with Python by importing the MySQL
module to search a student using rollno, update the
record.
21. 20 SQL QUERRIES.

22. SQL AGGREGATE FUNCTION SQL JOIN


QUERY
_______________________________________________
( INTERNAL EXAMINER’S SIGN)

______________
H.O.D.’S SIGN
(MRS. KUMUD CHAUHAN)

___________________________________________________

EXTERNAL EXAMINER’S SIGN)

________________
PRINCIPAL SIGN
(MR. DS. NEGI)
Ques.1 WAF to find weather a string is
PALINDROME or not.

Ques.2 WAF to calculate factorial of a


given number.
Output:-

Ques.3 WAF to count uppercase


and lowercase letters in a given
string.

Ques.4 Write a Python program to pass


a string to a function and count how
many vowels present in the string.

defcount_vowels(s):
vowels = "aeiouAEIOU"
vowel_count = 0
for char in s:
if char in vowels:
vowel_count += 1
returnvowel_count
input_string = input("Enter a string:
")
vowels_in_string =
count_vowels(input_string)
print(f"The number of vowels in the
string is: {vowels_in_string}")

OUTPUT
Enter a string: PRIYANKA
The number of vowels in the string is: 1

Ques.5 WAF to search an element in a


list and display the frequency of
element present in list and their location
using Linear search by using user
defined function.
[List and search element should be
entered by user.]
deflinear_search(lst, target):
locations = []
frequency = 0
for i in range(len(lst)):
iflst[i] == target:
locations.append(i)
frequency += 1
return frequency, locations
lst = input("Enter the list of elements
(comma-separated): ").split(",")
lst = [element.strip() for element in lst]
target = input("Enter the element to search:
").strip()
freq, locs = linear_search(lst, target)
iffreq> 0:
print(f"The element '{target}' appears
{freq} time(s) at the following index/indices:
{locs}")
else:
print(f"The element '{target}' is not found in
the list.")

OUTPUT
Enter the list of elements (comma-separated):
[3,646,46,44,66,4]
Enter the element to search: 646
The element '646' appears 1 time(s) at the following
index/indices: [1]
Ques.6 MAKE A MENU DRIVEN
PROGRAM USNING FUNCTION TO
ACCESS THEM.
1. AREA OF SQUARE
2. AREA OF CIRLCE
3. AREA OF RECTANGLE
4. PERIMETER OF SQUARE
PERIMETER OF CIRCLE

import math
defarea_of_square(side):
return side * side
defarea_of_circle(radius):
returnmath.pi * radius * radius
defarea_of_rectangle(length, breadth):
return length * breadth
defperimeter_of_square(side):
return 4 * side
defperimeter_of_circle(radius):
return 2 * math.pi * radius
def menu():
while True:
print("\nMenu:")
print("1. Area of Square")
print("2. Area of Circle")
print("3. Area of Rectangle")
print("4. Perimeter of Square")
print("5. Perimeter of Circle")
print("6. Exit")
choice = input("Enter your choice (1-6): ")

if choice == "1":
# Area of Square
side = float(input("Enter the side of the square:
"))
print(f"Area of Square: {area_of_square(side)}")

elif choice == "2":


# Area of Circle
radius = float(input("Enter the radius of the
circle: "))
print(f"Area of Circle: {area_of_circle(radius)}")

elif choice == "3":


# Area of Rectangle
length = float(input("Enter the length of the
rectangle: "))
breadth = float(input("Enter the breadth of the
rectangle: "))
print(f"Area of Rectangle:
{area_of_rectangle(length, breadth)}")

elif choice == "4":


# Perimeter of Square
side = float(input("Enter the side of the square:
"))
print(f"Perimeter of Square:
{perimeter_of_square(side)}")

elif choice == "5":


# Perimeter of Circle
radius = float(input("Enter the radius of the
circle: "))
print(f"Perimeter of Circle:
{perimeter_of_circle(radius)}")

elif choice == "6":


# Exit the program
print("Exiting the program...")
break

else:
print("Invalid choice! Please enter a number
between 1 and 6.")

# Call the main menu function to run the


program
menu()

OUTPUT
Menu:
1. Area of Square
2. Area of Circle
3. Area of Rectangle
4. Perimeter of Square
5. Perimeter of Circle
6. Exit
Enter your choice (1-6): 4
Enter the side of the square: 90
Perimeter of Square: 360.0

Menu:
1. Area of Square
2. Area of Circle
3. Area of Rectangle
4. Perimeter of Square
5. Perimeter of Circle
6. Exit
Enter your choice (1-6):

Ques.7 Write a python program to pass list to a


function and double the odd values and half even
values of a list and display list element after
changing.

def modify_list(lst):
for i in range(len(lst)):
if lst[i] % 2 == 0:
lst[i] = lst[i] / 2
else:
lst[i] = lst[i] * 2
return lst
my_list = [1, 2, 3, 4, 5, 6, 7, 8]
print("Original list:", my_list)
modified_list = modify_list(my_list)
print("Modified list:", modified_list)

OUTPUT
Original list: [1, 2, 3, 4, 5, 6, 7, 8]
Modified list: [2, 1.0, 6, 2.0, 10, 3.0, 14, 4.0]
Ques.8 Write a function namely nth root()
that receive two parameter x and n and
return nth root of x i.e. x1/n. the default value
of n is 2.

def nth_root(x, n=2):


return x ** (1 / n)
x = 16
n=4
print(f"The {n}-th root of {x} is: {nth_root(x,
n)}")
print(f"The square root of {x} is: {nth_root(x)}")

OUTPUT
The 4-th root of 16 is: 2.0
The square root of 16 is: 4.0
Ques.9 WAF to count and print lines
that start with "H" in file “Story.txt”.

def count_lines_starting_with_H(filename):
count = 0
try:
with open(filename, 'r') as file:
for line in file:
if line.strip().startswith('H'):
print(line.strip())
count += 1
print(f"\nTotal number of lines that start
with 'H': {count}")
except FileNotFoundError:
print(f"Error: The file '{filename}' was not
found.")
count_lines_starting_with_H('Story.txt')

OUTPUT
Assuming Story.txt contains the following:
Hello, this is a story.
How are you doing today?
This is another line.
Happiness is the key.
Habits form the future.
__________________________________________________
Hello, this is a story.
How are you doing today?
Happiness is the key.
Habits form the future.
Total number of lines that start with 'H':

Ques-10 A binary file “book. dat” has


structure
[book no, book_name, author , price]

a.) Write a user defined function create file() to


input data for a record and add to book.dat.
b.)Write a function countReac(author) in python
which acceps the author name as a parameter and
count and no. of books by the given author are
stored in the binary file “Book.dat”.
import struct
# Part a) Function to create a new record
and add it to the binary file
def create_file():
with open("book.dat", "ab") as file:
book_no = int(input("Enter book
number: "))
book_name = input("Enter book name:
")
author = input("Enter author name: ")
price = float(input("Enter book price:
"))
record = struct.pack('i50s50sf',
book_no, book_name.encode('utf-8'),
author.encode('utf-8'), price)
file.write(record)
print("Record added successfully!")

# Part b) Function to count and return the


number of books by a specific author
def countReac(author):
count = 0
with open("book.dat", "rb") as file:
while True:
record =
file.read(struct.calcsize('i50s50sf'))

if not record:
break
book_no, book_name, author_name,
price = struct.unpack('i50s50sf', record)
book_name =
book_name.decode('utf-8').strip()
author_name =
author_name.decode('utf-8').strip()
if author_name.lower() ==
author.lower():
count += 1

print(f"Number of books by {author}:


{count}")
return count
if __name__ == "__main__":
create_file()
author_name = input("Enter author name
to search:")
countReac(author_name)

OUTPUT
Enter book number: 1
Enter book name: Python
Enter author name: XYZ
Enter book price: 290

When adding a book


Enter book number: 1
Enter book name: Python
Enter author name: XYZ
Enter book price: 290
Record added successfully!

When searching for books by an


author:
Enter author name to search: XYZ
Number of books by XYZ: 1
Ques-11 Write a python program to
create a binary file with name and roll
number. Search for a given roll number
and display name ,if not found display
appropriate message.\

import struct
def create_file():
with open("students.dat", "ab") as file:
roll_number = int(input("Enter roll
number: "))
name = input("Enter student name: ")
record = struct.pack('i50s',
roll_number, name.encode('utf-8'))
file.write(record)
print("Record added successfully!")
def search_by_roll_number(search_roll):
found = False
with open("students.dat", "rb") as file:
while True:
record =
file.read(struct.calcsize('i50s'))
if not record:
break
roll_number, name =
struct.unpack('i50s', record)
name = name.decode('utf-8').strip()
if roll_number == search_roll:
print(f"Roll Number:
{roll_number}, Name: {name}")
found = True
break
if not found:
print(f"Student with roll number
{search_roll} not found.")
if __name__ == "__main__":
while True:
create_file()
more = input("Do you want to add
another record? (y/n): ").lower()
if more != 'y':
break
try:
roll_number_to_search =
int(input("Enter roll number to search for: "))
search_by_roll_number(roll_number_to_sear
ch)
except ValueError:
print("Invalid input! Please enter a valid
roll number.")

OUTPUT
When adding records:

Enter roll number: 101


Enter student name: RAM
Record added successfully!
Do you want to add another record? (y/n): y

Enter roll number: 102


Enter student name: SHYAM
Record added successfully!
Do you want to add another record? (y/n): n

When searching for a roll number:


Enter roll number to search for: 101
Roll Number: 101, Name: RAM

If the roll number is not found:


Enter roll number to search for: 103
Student with roll number 103 not found.
Ques-12 A binary file named”TEST.dat” has
some records of the structure
[Test id, subject, max marks, scored marks]
Write a function in python named display avg.
marks(sub) that will accept a subject as an
argument and read the contents of TEST.dat the
function will calculate and display the average of
the scored marks of the passes subject on screen.

import struct
def display_avg_marks(sub):
total_marks = 0
count = 0
try:
with open("TEST.dat", "rb") as file:
while True:
record =
file.read(struct.calcsize('i50sii'))
break
test_id, subject, max_marks,
scored_marks = struct.unpack('i50sii',
record)
subject = subject.decode('utf-
8').strip()
if subject.lower() == sub.lower():
total_marks += scored_marks
count += 1
if count == 0:
print(f"No records found for the
subject: {sub}")
else:
avg_marks = total_marks / count
print(f"Average marks for the
subject '{sub}': {avg_marks:.2f}")
except FileNotFoundError:
print("Error: The file 'TEST.dat' was not
found.")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
subject = input("Enter the subject to
calculate the average marks: ")
display_avg_marks(subject)

OUTPUT
Enter the subject to calculate the average
marks: Math
Average marks for the subject 'Math':
85.00
If no records found for the given subject:

Enter the subject to calculate the average


marks: History
No records found for the subject: History

Ques-13 Write a Python program to


function with key and value, and update
value at that key in dictionary entered by
user.
def update_value_in_dict(dictionary, key,
new_value):
if key in dictionary:
dictionary[key] = new_value
print(f"Value for key '{key}' updated to
'{new_value}'.")
else:
dictionary[key] = new_value
print(f"Key '{key}' added with value
'{new_value}'.")

def main():
my_dict = {"apple": 5, "banana": 10,
"cherry": 7}

print("Current dictionary:", my_dict)


key = input("Enter the key to update or
add: ")
value = input(f"Enter the new value for
'{key}': ")
try:
value = int(value)
except ValueError:
pass
update_value_in_dict(my_dict, key, value)
print("Updated dictionary:", my_dict)

if __name__ == "__main__":
main()

OUTPUT
Current dictionary: {'apple': 5, 'banana': 10,
'cherry': 7}
Enter the key to update or add: banana
Enter the new value for 'banana': 15
Value for key 'banana' updated to '15'.
Updated dictionary: {'apple': 5, 'banana': 15,
'cherry': 7}

Ques-14 Write a program to know the cursor


position and
print the text according to below-given specifications:
a) Print the initial position
b) Move the cursor to 4th position
c) Display next 5 characters
d) Move the cursor to the next 10 characters
e) Print the current cursor position
f) Print next 10 characters from the current cursor
Position

def main():
text = "This is a sample text used to
demonstrate cursor movement functionality."
cursor_position = 0

# a) Print the initial position


print(f"Initial cursor position: {cursor_position}")

# b) Move the cursor to 4th position (index 3)


cursor_position = 3
print(f"Cursor moved to position:
{cursor_position}")

# c) Display next 5 characters from the current


position
next_5_chars =
text[cursor_position:cursor_position + 5]
print(f"Next 5 characters from position
{cursor_position}: '{next_5_chars}'")

# d) Move the cursor to the next 10 characters


cursor_position += 10
print(f"Cursor moved to position:
{cursor_position}")

# e) Print the current cursor position


print(f"Current cursor position:
{cursor_position}")

# f) Print next 10 characters from the current


position
next_10_chars =
text[cursor_position:cursor_position + 10]
print(f"Next 10 characters from position
{cursor_position}: '{next_10_chars}'")

if __name__ == "__main__":
main()

OUTPUT
Initial cursor position: 0
Cursor moved to position: 3
Next 5 characters from position 3: 's is '
Cursor moved to position: 13
Current cursor position: 13
Next 10 characters from position 13: 'mple
text '
Ques-15 Write a Python program to
implement a stack using list (PUSH &
POP Operation on Stack).

class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
print(f"Pushed {item} to the stack")
def pop(self):
if not self.is_empty():
item = self.stack.pop()
print(f"Popped {item} from the
stack")
return item
else:
print("Stack is empty! Cannot
pop.")
return None
def peek(self):
if not self.is_empty():
return self.stack[-1]
else:
print("Stack is empty! No top
element.")
return None
def is_empty(self):
return len(self.stack) == 0
def size(self):
return len(self.stack)
if __name__ == "__main__":
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)
stack.pop()
print(f"Top element is: {stack.peek()}")
print(f"Is stack empty?
{stack.is_empty()}")
print(f"Stack size: {stack.size()}")
stack.pop()
stack.pop()
stack.pop()

OUTPUT
Pushed 10 to the stack
Pushed 20 to the stack
Pushed 30 to the stack
Top element is: 30
Popped 30 from the stack
Top element is: 20
Popped 20 from the stack
Popped 10 from the stack
Stack is empty! Cannot pop.

Ques-16 A dictionary that stores Product


names as key and price as values. Write a user-
defined function to perform the following
operations:
•Push the values into the stack if the price of
products is greater than 300.
•Pop and display the contents of the stack.
For example, if the content of the dictionary is as
follows: product={‘Book’:250, ‘Pen’:120,
‘Pencil’:50, ‘Notebook’:400, ‘Register’:480} The
elements of the stack should be: [250, 400, 480].

class Stack:
def __init__(self):
self.stack = []
def push(self, value):
"""Push an element onto the stack."""
self.stack.append(value)
def pop(self):
"""Pop an element from the stack."""
if not self.is_empty():
return self.stack.pop()
else:
return None
def is_empty(self):
"""Check if the stack is empty."""
return len(self.stack) == 0
def display(self):
"""Display the contents of the stack."""
if self.is_empty():
print("Stack is empty.")
else:
print("Stack contents:", self.stack)
def push_prices_to_stack(product_dict, stack):
"""Push product prices greater than 300 into
the stack."""
for product, price in product_dict.items():
if price > 300:
stack.push(price)
print(f"Pushed {price} to the stack")
def pop_stack_contents(stack):
"""Pop and display contents of the stack."""
print("Popping from stack:")
while not stack.is_empty():
value = stack.pop()
print(f"Popped {value} from the stack")
if __name__ == "__main__":
product = {'Book': 250, 'Pen': 120, 'Pencil': 50,
'Notebook': 400, 'Register': 480}
stack = Stack()
push_prices_to_stack(product, stack)
stack.display()
pop_stack_contents(stack)

OUTPUT
Pushed 400 to the stack
Pushed 480 to the stack
Stack contents: [400, 480]
Popping from stack:
Popped 480 from the stack
Popped 400 from the stack

Ques-17 Write a python program using


function POP(Arr), where Arr is a stack
implemented by a list of numbers. The
function returns the value deleted from the
stack.

def POP(Arr):
"""Pop the top element from the stack and
return it."""
if len(Arr) > 0:
return Arr.pop()
else:
print("Stack is empty! Cannot pop.")
return None
if __name__ == "__main__":
stack = [10, 20, 30, 40, 50]
print("Initial stack:", stack)
print("Popped value:", POP(stack))
print("Updated stack:", stack)
print("Popped value:", POP(stack))
print("Updated stack:", stack)

OUTPUT
Initial stack: [10, 20, 30, 40, 50]
Popped value: 50
Updated stack: [10, 20, 30, 40]
Popped value: 40
Updated stack: [10, 20, 30]
Stack is empty! Cannot pop.
Popped value: None
Ques-18 Prateek has created a list arr with
some elements. Help him to create a user-
defined function to perform the following tasks:
*Create a stack after checking the elements if
it is even then multiply by 2 and if the element
is odd ,then multiply it by 3.
* Pop and display the contents of the stack.

def create_stack(arr):
"""Create a stack based on the given list,
modifying elements as per the conditions."""
stack = []
for num in arr:
if num % 2 == 0:
stack.append(num * 2)
else:
stack.append(num * 3)
return stack
def pop_and_display_stack(stack):
"""Pop and display the contents of the
stack."""
print("Popping from the stack:")
while stack:
popped_value = stack.pop()
print(f"Popped {popped_value} from the
stack")
if not stack:
print("Stack is empty!")
if __name__ == "__main__":
arr = [10, 15, 8, 9, 3, 12, 5]
stack = create_stack(arr)
print("Created stack:", stack)
pop_and_display_stack(stack)

OUTPUT
Created stack: [20, 45, 16, 27, 9, 24, 15]
Popping from the stack:
Popped 15 from the stack
Popped 24 from the stack
Popped 9 from the stack
Popped 27 from the stack
Popped 16 from the stack
Popped 45 from the stack
Popped 20 from the stack
Stack is empty!
Ques-19 Integrate MySQL with Python by
importing the MySQL module and add records of
student and display all the record.

import mysql.connector
def connect_to_database():
"""Establish a connection to the MySQL database."""
try:
connection = mysql.connector.connect(
host='localhost',
user='root',
password='password',
database='school' )
if connection.is_connected():
print("Successfully connected to the database.")
return connection
except mysql.connector.Error as err:
print(f"Error: {err}")
return None
def add_student(connection, name, age, grade):
"""Add a student record to the students table."""
cursor = connection.cursor()
insert_query = "INSERT INTO students (name, age,
grade) VALUES (%s, %s, %s)"
values = (name, age, grade)
try:
cursor.execute(insert_query, values)
connection.commit()
print(f"Student '{name}' added successfully.")
except mysql.connector.Error as err:
print(f"Error: {err}")
finally:
cursor.close()

def display_students(connection):
"""Display all student records from the students
table."""
cursor = connection.cursor()
select_query = "SELECT * FROM students"
try:
cursor.execute(select_query)
records = cursor.fetchall()
print("\nStudent Records:")
print("ID | Name | Age | Grade")
print("-" * 30)
for row in records:
print(f"{row[0]} | {row[1]} | {row[2]} | {row[3]}")
except mysql.connector.Error as err:
print(f"Error: {err}")
finally:
cursor.close()
if __name__ == "__main__":
connection = connect_to_database()
if connection:
add_student(connection, 'RAM', 20, 'A')
add_student(connection, 'SHYAM', 22, 'B')
add_student(connection, 'SANCHI', 21, 'A')
display_students(connection)
connection.close()

OUTPUT
Successfully connected to the database.
Student 'RAM' added successfully.
Student 'SHYAM' added successfully.
Student 'SANCHI' added successfully.
Student Records:
ID | Name | Age | Grade
--------------------------------------------------------------
1 | RAM | 20 | A
2 | SHYAM | 22 | B
3 | SANCHI | 21 | A
Ques-20 Integrate SQL with Python by
importing the MySQL module to search a
student using rollno, update the record.

Create the Database and Table:


Create the database if it doesn't exist
CREATE DATABASE IF NOT EXISTS school;
USE school;
Create the students table if it doesn't exist
CREATE TABLE IF NOT EXISTS students (
rollno INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
age INT,
grade VARCHAR(10));

Python Program:
import mysql.connector
def connect_to_database():
"""Establish a connection to the MySQL database."""
try:
connection = mysql.connector.connect(
host='localhost',
user='root',
password='password'
database='school')
if connection.is_connected():
print("Successfully connected to the database.")
return connection
except mysql.connector.Error as err:
print(f"Error: {err}")
return None
def search_student_by_rollno(connection, rollno):
"""Search for a student by roll number."""
cursor = connection.cursor()
select_query = "SELECT * FROM students WHERE rollno = %s"
try:
cursor.execute(select_query, (rollno,))
result = cursor.fetchone()
if result:
print(f"Student Found: Roll No: {result[0]}, Name: {result[1]}, Age:
{result[2]}, Grade: {result[3]}")
return result
else:
print(f"No student found with Roll No: {rollno}")
return None
except mysql.connector.Error as err:
print(f"Error: {err}")
return None
finally:
cursor.close()
def update_student_record(connection, rollno, new_name, new_age,
new_grade):
"""Update student record based on roll number."""
cursor = connection.cursor()
update_query = "UPDATE students SET name = %s, age = %s,
grade = %s WHERE rollno = %s"
values = (new_name, new_age, new_grade, rollno)
try:
cursor.execute(update_query, values)
connection.commit() # Commit the changes to the database
if cursor.rowcount > 0:
print(f"Student record with Roll No {rollno} updated successfully.")
else:
print(f"No record found with Roll No {rollno} to update.")
except mysql.connector.Error as err:
print(f"Error: {err}")
finally:
cursor.close()
if __name__ == "__main__":
connection = connect_to_database()
if connection:
rollno = int(input("Enter the roll number of the student to search: "))
student = search_student_by_rollno(connection, rollno)
if student:
new_name = input(f"Enter new name for {student[1]}: ")
new_age = int(input(f"Enter new age for {student[1]}: "))
new_grade = input(f"Enter new grade for {student[1]}: ")
update_student_record(connection, rollno, new_name, new_age,
new_grade)
connection.close()

OUTPUT
Successfully connected to the database.
Enter the roll number of the student to search: 1
Student Found: Roll No: 1, Name: Alice, Age: 20, Grade: A
Enter new name for Alice: Alicia
Enter new age for Alicia: 21
Enter new grade for Alicia: B
Student record with Roll No 1 updated successfully .
Ques-21 20 SQL QUERRIES .

1. Create a Table

Create a table called students with columns for student_id, name, age, and
grade.

CREATE TABLE students (


student_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
age INT,
grade VARCHAR(10)

2. Insert Data

Insert a new student record into the students table.

INSERT INTO students (name, age, grade)


VALUES ('Alice', 20, 'A');

3. Select All Data

Select all records from the students table.

SELECT * FROM students;

4. Select Specific Columns

Select the name and age columns from the students table.

SELECT name, age FROM students;

5. Select with WHERE Clause

Select students who are older than 18 years.


SELECT * FROM students WHERE age > 18;

6. Update Data

Update the grade of a student with student_id 1 to 'B'.

UPDATE students SET grade = 'B' WHERE student_id = 1;

7. Delete Data

Delete the student with student_id 1 from the students table.

DELETE FROM students WHERE student_id = 1;

8. Count Records

Count the number of students in the students table.

SELECT COUNT(*) FROM students;

9. Order By

Select all students and order them by age in descending order.

SELECT * FROM students ORDER BY age DESC;

10. Group By

Count how many students belong to each grade.

SELECT grade, COUNT(*) AS number_of_students


FROM students
GROUP BY grade;

11. Having Clause

Select grades with more than 1 student.

SELECT grade, COUNT(*) AS number_of_students


FROM students
GROUP BY grade
HAVING COUNT(*) > 1;

12. Join Tables (Inner Join)

Suppose there are two tables: students and courses (with columns course_id,
student_id, course_name). Select the student name and their course name.

SELECT students.name, courses.course_name


FROM students
INNER JOIN courses ON students.student_id = courses.student_id;
13. Left Join

Select all students and their courses, including students who may not
have enrolled in any courses.

SELECT students.name, courses.course_name


FROM students
LEFT JOIN courses ON students.student_id = courses.student_id;

14. Right Join

Select all courses and the students who are enrolled in them.

SELECT students.name, courses.course_name


FROM students
RIGHT JOIN courses ON students.student_id = courses.student_id;

15. Union

Combine the results of two SELECT queries (e.g., students from two
different courses).

SELECT name FROM students WHERE course = 'Math'


UNION
SELECT name FROM students WHERE course = 'Science';

16. Select Distinct Values

Select distinct grades from the students table.

SELECT DISTINCT grade FROM students;

17. Limit Results

Select the first 5 students from the students table.

SELECT * FROM students LIMIT 5;

18. Alter Table (Add Column)

Add a column email to the students table.

ALTER TABLE students ADD COLUMN email VARCHAR(255);

19. Drop Table

Delete the students table from the database.

DROP TABLE students;

20. Create Index

Create an index on the name column of the students table to improve


search performance.
CREATE INDEX idx_name ON students(name);

Ques-22 SQL AGGREGATE


FUNCTION SQL JOIN QUERY.

Let's explore SQL Aggregate Functions and SQL JOINs with examples.

Example Database

Consider we have two tables:

1. students (Student records)

CREATE TABLE students (


student_id INT PRIMARY KEY,
name VARCHAR(100),
age INT,
grade VARCHAR(10)
);

2. courses (Courses enrolled by students)

CREATE TABLE courses (


course_id INT PRIMARY KEY,
course_name VARCHAR(100),
student_id INT,
FOREIGN KEY (student_id) REFERENCES students(student_id)
);

Example Data for students table:


INSERT INTO students (student_id, name, age, grade)
VALUES
(1, 'Alice', 20, 'A'),
(2, 'Bob', 22, 'B'),
(3, 'Charlie', 21, 'A'),
(4, 'David', 23, 'C');
Example Data for courses table:
INSERT INTO courses (course_id, course_name, student_id)
VALUES
(1, 'Math', 1),
(2, 'Science', 1),
(3, 'Math', 2),
(4, 'History', 3),
(5, 'Math', 4);

1. SQL Aggregate Function Example

1.1 COUNT() – Count the number of students in each grade:

SELECT grade, COUNT(*) AS number_of_students


FROM students
GROUP BY grade;

1.2 SUM() – Calculate the total age of all students:

SELECT SUM(age) AS total_age


FROM students;

1.3 AVG() – Calculate the average age of students:

SELECT AVG(age) AS average_age


FROM students;

1.4 MIN() – Find the youngest student:

SELECT MIN(age) AS youngest_age


FROM students;

1.5 MAX() – Find the oldest student:

SELECT MAX(age) AS oldest_age


FROM students;

2. SQL JOIN Queries

2.1 INNER JOIN – Join students and courses tables on student_id and select
students with their course names:

SELECT students.name, courses.course_name


FROM students
INNER JOIN courses
ON students.student_id = courses.student_id;

Result:

| name | course_name |
|---------|-------------|
| Alice | Math |
| Alice | Science |
| Bob | Math |
| Charlie | History |
| David | Math |

2.2 LEFT JOIN – List all students and their courses, including students who are not
enrolled in any courses:

SELECT students.name, courses.course_name


FROM students
LEFT JOIN courses
ON students.student_id = courses.student_id;

Result:

| name | course_name |
|---------|-------------|
| Alice | Math |
| Alice | Science |
| Bob | Math |
| Charlie | History |
| David | Math |

2.3 RIGHT JOIN – List all courses and the students enrolled in them:

SELECT students.name, courses.course_name


FROM students
RIGHT JOIN courses
ON students.student_id = courses.student_id;

Result:

javascript
Copy code
| name | course_name |
|---------|-------------|
| Alice | Math |
| Alice | Science |
| Bob | Math |
| Charlie | History |
| David | Math |

2.4 FULL JOIN (Not supported in MySQL) – A full join would combine the results of
LEFT JOIN and RIGHT JOIN by including all rows from both tables. However, MySQL
doesn't support FULL JOIN directly, so it can be achieved by combining LEFT JOIN and
RIGHT JOIN using UNION.

(SELECT students.name, courses.course_name


FROM students
LEFT JOIN courses
ON students.student_id = courses.student_id)
UNION
(SELECT students.name, courses.course_name
FROM students
RIGHT JOIN courses
ON students.student_id = courses.student_id);

2.5 SELF JOIN – A self join is a join of a table with itself. For example, suppose you
want to find students who have the same grade as another student:

SELECT a.name AS Student1, b.name AS Student2, a.grade


FROM students a, students b
WHERE a.grade = b.grade AND a.student_id != b.student_id;

3. Combining Aggregate Functions with JOIN

3.1 COUNT with JOIN – Count the number of courses each student is enrolled in:

SELECT students.name, COUNT(courses.course_name) AS course_count


FROM students
LEFT JOIN courses ON students.student_id = courses.student_id
GROUP BY students.name;

Result:

| name | course_count |
|---------|--------------|
| Alice | 2 |
| Bob | 1 |
| Charlie | 1 |
| David | 1 |

3.2 AVG with JOIN – Calculate the average age of students enrolled in each course:

SELECT courses.course_name, AVG(students.age) AS average_age


FROM students
INNER JOIN courses ON students.student_id = courses.student_id
GROUP BY courses.course_name;

Result:

| course_name | average_age |
|-------------|-------------|
| Math | 21 |
| Science | 20 |
| History | 21 |

You might also like