#1
import pickle
# Function to create the binary file [Link]
def CreateEmp():
x=int(input("enter number of records you want to enter:"))
file=open('[Link]', 'wb')
for i in range (x):
EID = int(input("Enter Employee ID: "))
Ename = str(input("Enter Employee Name:"))
designation = input("Enter Designation: ")
salary = float(input("Enter Salary: "))
employee = {'EID': EID, 'Ename': Ename, 'designation': designation,
'salary': salary}
[Link](employee, file)
# Function to display employees with salary more than 50,000
def display():
file=open('[Link]', 'rb')
while True:
try:
employee = [Link](file)
if employee['salary'] > 50000:
print("EID",employee['EID'], "Name",employee['Ename'])
except EOFError:
break
CreateEmp()
display()
-----------------------------------------------------------------------------------
-----------
import [Link]
# Connect to MySQL server
con = [Link](host="localhost", user="root", password="")
mycursor = [Link]()
# Create database and use it
[Link]('CREATE DATABASE IF NOT EXISTS PRACTICAL')
[Link]('USE PRACTICAL')
# Create table
[Link]('''
CREATE TABLE IF NOT EXISTS EMPLOYEE (
Empid INT PRIMARY KEY,
EName VARCHAR(50),
CompName VARCHAR(50),
City VARCHAR(50),
SEX CHAR(1)
)
''')
print("Table Created")
# Clear previous records
[Link]('DELETE FROM EMPLOYEE')
# Insert records one by one
[Link]("INSERT INTO EMPLOYEE VALUES (11, 'Aleshia Rosenburg', 'Hawerby',
'Hawerby', 'F')")
[Link]("INSERT INTO EMPLOYEE VALUES (22, 'Evan Gemini', 'Abbey Ward',
'Abbey Ward', 'M')")
[Link]("INSERT INTO EMPLOYEE VALUES (33, 'Franci Elliott', 'Southbourne',
'Southbourne', 'F')")
[Link]("INSERT INTO EMPLOYEE VALUES (44, 'Ulysses Mcmahan', 'Hawerby',
'Hawerby', 'M')")
[Link]("INSERT INTO EMPLOYEE VALUES (55, 'Tyisha Champagne', 'Hawerby',
'Hawerby', 'F')")
[Link]()
print('Records Inserted')
# Query a: Display employee data for female gender
[Link]('SELECT * FROM EMPLOYEE WHERE SEX = "F"')
x=[Link]()
for emp in x:
print(emp)
# Query b: Display name and city of employees whose Empid is 30 and above
[Link]('SELECT EName, City FROM EMPLOYEE WHERE Empid >= 30')
y=[Link]():
for emp in y:
print(emp)
# Close connection
[Link]()
-----------------------------------------------------------------------------------
------------------------------------------
2
def count_lines():
count = 0
file=([Link], 'r')
x=[Link]()
for i in x:
if i[0]=='A'or'E'or'I':
count += 1
print("Number of lines starting with A, E, or I: ",count)
count_lines()
-----------------------------------------------------------------------------------
--------------------------------------
import [Link]
# Connect to MySQL server
con = [Link](host="localhost", user="root", password="")
mycursor = [Link]()
# Create database and use it
[Link]('CREATE DATABASE IF NOT EXISTS PRACTICAL')
[Link]('USE PRACTICAL')
# Table creation
[Link]('''
CREATE TABLE IF NOT EXISTS SALES (
SalesId INT PRIMARY KEY,
Salesperson VARCHAR(50),
Item VARCHAR(50),
Units INT,
UnitCost INT,
Totalcost INT
)
''')
print("table is created")
# Clear previous records for simplicity
[Link]('DELETE FROM SALES')
# Record insertion
[Link]("INSERT INTO SALES VALUES (100, 'Jones', 'Pen', 45, 10, 450)")
[Link]("INSERT INTO SALES VALUES (102, 'Kivell', 'Binder', 50, 19, 950)")
[Link]("INSERT INTO SALES VALUES (105, 'Jardine', 'Pencil', 36, 16,
576)")
[Link]("INSERT INTO SALES VALUES (106, 'Gill', 'Pen', 27, 19, 513)")
[Link]("INSERT INTO SALES VALUES (115, 'Andrews', 'Pen', 75, 10, 750)")
[Link]("INSERT INTO SALES VALUES (119, 'Jardine', 'Pencil', 90, 11,
990)")
# Commit changes
[Link]()
print([Link], 'Records Inserted')
# Query a: Search records for item 'Pen' with Totalcost more than 600
[Link]("SELECT * FROM SALES WHERE Item = 'Pen' AND Totalcost > 600")
x=[Link]()
for record in x:
print(record)
# Query b: List items with UnitCost more than 15, sorted by Units
[Link]("SELECT * FROM SALES WHERE UnitCost > 15 ORDER BY Units")
y=[Link]()
for record in y:
print(record)
# Close the connection
[Link]()
-----------------------------------------------------------------------------------
--------------------------
import csv
# Function to get student details and write data to CSV file
def get_and_write_student_data():
more_records = 'y'
while more_records.lower() == 'y':
roll_number = input("Enter roll number: ")
name = input("Enter student name: ")
marks = input("Enter marks: ")
student_data = [roll_number, name, marks]
# Writing to CSV file in 'w' mode (overwrite the file each time)
file = open('[Link]', mode='a', newline='') # Changed to 'a' for
appending new records
writer = [Link](file)
[Link](student_data)
[Link]()
more_records = input("Do you want to add another student record? (y/n): ")
# Function to read and display data from CSV file
def display_csv():
try:
file = open('[Link]', mode='r')
reader = [Link](file)
print("\nContents of '[Link]':")
for row in reader:
print(row)
[Link]()
except FileNotFoundError:
print("File not found. No data to display.")
# Get student details and write to CSV
get_and_write_student_data()
# Display contents of CSV file
display_csv()
-----------------------------------------------------------------------------------
------------------------
import [Link]
# Establishing the connection
con = [Link](host="localhost", user="root", password="")
mycursor = [Link]()
# Create the PRACTICAL database if it doesn't exist
[Link]('CREATE DATABASE IF NOT EXISTS PRACTICAL')
[Link]('USE PRACTICAL')
# Table creation: Creating the STUDENT table
[Link]('''
CREATE TABLE IF NOT EXISTS STUDENT (
Id INT,
SName VARCHAR(50),
Gender VARCHAR(10),
Country VARCHAR(50),
Age INT,
Marks INT
)
''')
# Inserting records into the STUDENT table one by one
[Link]('INSERT INTO STUDENT (Id, SName, Gender, Country, Age, Marks)
VALUES (1562, "Dulce", "Female", "United States", 32, 495)')
[Link]('INSERT INTO STUDENT (Id, SName, Gender, Country, Age, Marks)
VALUES (1582, "Mara", "Female", "Great Britain", 25, 426)')
[Link]('INSERT INTO STUDENT (Id, SName, Gender, Country, Age, Marks)
VALUES (2587, "Philip", "Male", "France", 36, 480)')
[Link]('INSERT INTO STUDENT (Id, SName, Gender, Country, Age, Marks)
VALUES (3549, "Kathleen", "Female", "United States", 25, 400)')
[Link]('INSERT INTO STUDENT (Id, SName, Gender, Country, Age, Marks)
VALUES (3598, "Etta", "Female", "Great Britain", 56, 325)')
[Link]('INSERT INTO STUDENT (Id, SName, Gender, Country, Age, Marks)
VALUES (6548, "Vinca", "Male", "United States", 40, 485)')
# Commit the transaction
[Link]()
print("6 Records Inserted")
# Query a. List the name of Male students sorted by highest to lowest marks
[Link]('''
SELECT SName FROM STUDENT
WHERE Gender = "Male"
ORDER BY Marks DESC
''')
male_students = [Link]()
print("\nMale Students sorted by marks (highest to lowest):")
for student in male_students:
print(student[0])
# Query b. Search minimum Marks from student table for United States
[Link]('''
SELECT MIN(Marks) FROM STUDENT
WHERE Country = "United States"
''')
min_marks_us = [Link]()
print("\nMinimum Marks for students from United States:", min_marks_us[0])
# Closing the connection
[Link]()
-----------------------------------------------------------------------------------
------------------------------------------------------------
import pickle
# Function to create the '[Link]' file and input student data
def CreateStd():
# Open file in binary write mode
file = open('[Link]', 'wb')
while True:
# Input student data
SID = int(input("Enter Student ID: "))
Sname = input("Enter Student Name: ")
Stream = input("Enter Stream: ")
Marks = float(input("Enter Marks: "))
# Create a dictionary to hold the student record
student_record = {'SID': SID, 'Sname': Sname, 'Stream': Stream, 'Marks':
Marks}
# Use pickle to serialize the student record and write it to the file
[Link](student_record, file)
# Ask user if they want to enter another record
more = input("Do you want to enter another student record? (y/n): ")
if [Link]() != 'y':
break
[Link]() # Closing the file after writing
print("Student records have been written to '[Link]'.")
# Function to display student records with marks greater than 350
def sdisplay():
# Open the file in binary read mode
file = open('[Link]', 'rb')
print("\nStudents with marks greater than 350:")
while True:
try:
# Use pickle to deserialize the student record
student_record = [Link](file)
# Check if marks are greater than 350 and display the record
if student_record['Marks'] > 350:
print(f"ID: {student_record['SID']}, Name:
{student_record['Sname']}, Stream: {student_record['Stream']}, Marks:
{student_record['Marks']}")
except EOFError:
break
[Link]() # Closing the file after reading
# Main execution
# Create student records in the binary file
CreateStd()
# Display students with marks greater than 350
sdisplay()
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
---------
import [Link]
# Establishing the connection to MySQL
con = [Link](host="localhost", user="root", password="")
mycursor = [Link]()
# Create the PRACTICAL database if it doesn't exist
[Link]('CREATE DATABASE IF NOT EXISTS PRACTICAL')
[Link]('USE PRACTICAL')
# Table creation (BOOKS)
[Link]('''
CREATE TABLE IF NOT EXISTS BOOKS (
BOOK_NAME VARCHAR(100),
PUBLISHERS VARCHAR(100),
PRICE INT
)
''')
# Inserting records into the BOOKS table
[Link]('''INSERT INTO BOOKS (BOOK_NAME, PUBLISHERS, PRICE)
VALUES
('FAST COOK', 'EPB', 355),
('THE TEARS', 'TDH', 650),
('MY FIRST C++', 'EPB', 350),
('C++ BRAINWORKS', 'TDH', 350),
('THUNDERBOLTS', 'FIRST PUBL', 750)''')
# Commit the changes to the database
[Link]()
print([Link], 'Records Inserted')
# a. Query to increase the price of all books published by TDH by 100
[Link]('''
UPDATE BOOKS
SET PRICE = PRICE + 100
WHERE PUBLISHERS = 'TDH'
''')
[Link]()
print("Price updated for all books of TDH publishers by 100.")
# b. Query to display all books sorted by name in Z to A order
[Link]('''
SELECT BOOK_NAME, PUBLISHERS, PRICE
FROM BOOKS
ORDER BY BOOK_NAME DESC
''')
books = [Link]()
print("\nBooks sorted by name (Z to A):")
for book in books:
print(book)
# Close the connection
[Link]()
-----------------------------------------------------------------------------
5
# Function to create a list of 10 elements and push numbers greater than 50 into a
stack
def create_and_push_to_stack():
# Creating a list with 10 elements (random numbers for example purposes)
numbers = [12, 75, 44, 56, 85, 22, 91, 37, 62, 50]
stack = [] # Empty stack
for num in numbers:
if num > 50:
[Link](num)
return stack
# Function to pop and display the content of the stack
def pop_and_display_stack(stack):
if stack==[]: # If the stack is empty
print("Stack is empty")
else:
print("Popping elements from the stack:")
element = [Link]()
print("poped item",element)
print("stack is")
top=len(stack)-1
for i in range(top-1,-1,-1):
print(i)
-----------------------------------------------------------------------------------
---------------------------------
import [Link]
# Establish the connection to MySQL
con = [Link](host="localhost", user="root", password="")
mycursor = [Link]()
# Create the PRACTICAL database if it doesn't exist
[Link]('CREATE DATABASE IF NOT EXISTS PRACTICAL')
[Link]('USE PRACTICAL')
# Table creation: STUDENT
[Link]('''
CREATE TABLE IF NOT EXISTS STUDENT (
Name VARCHAR(100),
AvgMark FLOAT,
Grade CHAR(1),
Class VARCHAR(10)
)
''')
# Inserting records into the STUDENT table
[Link]('''INSERT INTO STUDENT (Name, AvgMark, Grade, Class)
VALUES
('Karan', 78.5, 'B', '12B'),
('Divakar', 89.2, 'A', '11C'),
('Divya', 68.6, 'C', '12C'),
('Arun', 73.1, 'B', '12C'),
('Sabina', 90.6, 'A', '11A')''')
# Commit the changes to the database
[Link]()
print([Link], 'Records Inserted')
# a. List the names of students who are in class 12, sorted by average marks
[Link]('''
SELECT Name
FROM STUDENT
WHERE Class LIKE '12%'
ORDER BY AvgMark DESC
''')
# Fetching the result and displaying the names
print("\nList of students in class 12 sorted by average marks:")
students_12th = [Link]()
for student in students_12th:
print(student)
# b. Delete all the records whose AvgMark is less than 80
[Link]('''
DELETE FROM STUDENT
WHERE AvgMark < 80
''')
# Commit the deletion
[Link]()
# Closing the connection
[Link]()