0% found this document useful (0 votes)
43 views61 pages

Atharva Rathod Practical Record

The document is a collection of Python functions that perform various tasks such as calculating sums, averages, areas, and handling file operations. It includes functions for mathematical calculations, string manipulations, and file reading/writing operations. Additionally, it covers binary file operations for managing records of books, employees, and students.

Uploaded by

aniruddh162008
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)
43 views61 pages

Atharva Rathod Practical Record

The document is a collection of Python functions that perform various tasks such as calculating sums, averages, areas, and handling file operations. It includes functions for mathematical calculations, string manipulations, and file reading/writing operations. Additionally, it covers binary file operations for managing records of books, employees, and students.

Uploaded by

aniruddh162008
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

Python Functions Collection

1. Sum & Average


def sumaverage(lst, size):
total = sum(lst)
avg = total / size
print("Sum:", total)
print("Average:", avg)

2. Simple Interest
def Interest(Principal, Rate, Time):
si = (Principal * Rate * Time) /
100 print("Simple Interest:", si)

3. Area of Circle
def areacircle(radius):
area = 3.14 * radius * radius
print("Area of Circle:", area)

4. Even or Odd
def EvenOdd(number):
if number % 2 == 0:
print("Even Number")
else:
print("Odd Number")

5. Maximum of Three
def Maximum(first, second, third):
if first >= second and first >= third:
print("Maximum:", first)
elif second >= first and second >= third:
print("Maximum:", second)
else:
print("Maximum:", third)
6. Count Uppercase & Lowercase
def Count(message):
u=l=0
for ch in message:
if ch.isupper():
u += 1
elif ch.islower():
l += 1
print("Uppercase:", u)
print("Lowercase:", l)

7. Factorial
def Factorial(number):
fact = 1
for i in range(1, number + 1):
fact *= i
print("Factorial:", fact)

8. Unique List
def UniqueList(lst, size):
unique = []
for x in lst:
if x not in unique:
unique.append(x)
return unique

9. Print Even Numbers


def EvenList(lst, size):
for x in lst:
if x % 2 == 0:
print(x, end=" ")

10. Search an Element


def SearchElement(lst, size):
ele = int(input("Enter element to search: "))
if ele in lst:
print("Found at index", lst.index(ele))
else:
print("Not Found")

11. Replace Odd/Even Values


def Arrange(lst, size):
for i in range(size):
if lst[i] % 2 == 0:
lst[i] *= 2
else:
lst[i] *= 3
print(lst)

12. Change based on divisibility by 7


def Change(lst, size):
for i in range(size):
if lst[i] % 7 == 0:
lst[i] //= 7
else:
lst[i] *= 3
print(lst)

13. Reassign based on divisibility by 5


def Reassign(lst, size):
for i in range(size):
if lst[i] % 5 == 0:
lst[i] //= 5
else:
lst[i] *= 2
print(lst)

14. Find Maximum (No max())


def FindMax(lst, size):
max_val = lst[0]
index = 0
for i in range(size):
if lst[i] >
max_val:
max_val = lst[i]
index = i
print("Maximum:", max_val)
print("Index:", index)
15. Sum of Positive & Negative in Tuple
def CalculateSum(mytuple,
size): pos = neg = 0
for x in mytuple:
if x >= 0:
pos += x
else:
neg += x
print("Sum of Positive:", pos)
print("Sum of Negative:", neg)

16. Sum of Odd Numbers in Tuple


def OddSum(mytuple, size):
total = 0
for x in mytuple:
if x % 2 != 0:
total += x
print("Sum of Odd Numbers:", total)

17. Fibonacci Series


def FibonacciSeries(number):
a, b = 0, 1
for _ in range(number):
print(a, end=" ")
a, b = b, a + b

18. Show ASCII Codes


def ShowASCII(message):
for ch in message:
print(ch, "=", ord(ch))

19. Swap Values


def SwapValues(number1, number2):
temp = number1
number1 = number2
number2 = temp
print("After Swap:", number1, number2)
20. Check Leap Year
def LeapYear(year):
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
print("Leap Year")
else:
print("Not a Leap Year")

21. Menu Program (Even/Odd, Sum Even, Sum Odd)


def isEven(n):
return n % 2 == 0

def sumEven(lst):
return sum(x for x in lst if x % 2 == 0)

def sumOdd(lst):
return sum(x for x in lst if x % 2 != 0)

def menu1():
print("1. Check Even or Odd")
print("2. Sum of Even Numbers")
print("3. Sum of Odd Numbers")
ch = int(input("Enter choice: "))

lst = [1, 2, 3, 4, 5, 6]

if ch == 1:
n = int(input("Enter number: "))
print("Even" if isEven(n) else "Odd")
elif ch == 2:
print("Sum of Even:",
sumEven(lst)) elif ch == 3:
print("Sum of Odd:", sumOdd(lst))

22. Menu Program (Areas)


def areaRectangle(l,
b): return l * b

def areaCircle(r):
return 3.14 * r * r

def areaSquare(s):
return s * s

def menu2():
print("1. Area of Rectangle")
print("2. Area of Circle")
print("3. Area of Square")
ch = int(input("Enter choice: "))

if ch == 1:
l = int(input("Length: "))
b = int(input("Breadth:
"))
print("Area:", areaRectangle(l, b))
elif ch == 2:
r = int(input("Radius: "))
print("Area:", areaCircle(r))
elif ch == 3:
s = int(input("Side: "))
print("Area:", areaSquare(s))
Text File Programs
1. Program to count occurrences of “Me” or “My” (case-insensitive) in MyData.txt
Write a function CountMeMy() in Python that counts how many times the words “Me” or “My”
(including lowercase) appear in MyData.txt.

def CountMeMy():
count = 0
with open("MyData.txt", "r") as f:
for word in f.read().split():
if word.lower() in ["me", "my"]:
count += 1
print("Count of 'Me' or 'My':", count)

2. Program to count occurrences of 'A' or 'M' (case-insensitive) in Story.txt


Write a function AMCount() that reads each character and counts A/a or M/m.

def AMCount():
count = 0
with open("Story.txt", "r") as f:
for ch in f.read():
if ch.lower() in ["a", "m"]:
count += 1
print("Count of A or M:", count)

3. Program to count lines beginning with 'A' in MyData.txt


Write a function CountLineA() to count the number of lines starting with alphabet “A”.

def CountLineA():
count = 0
with open("MyData.txt", "r") as f:
for line in f:
if line.strip().startswith("A"):
count += 1
print("Lines starting with A:", count)
4. Program to display words < 4 characters from Story.txt
Write a function DisplayWords() to show only those words having less than 4 characters.

def DisplayWords():
with open("Story.txt", "r") as f:
for line in f:
for word in line.split():
if len(word) < 4:
print(word)

5. Program to count uppercase and lowercase letters in Story.txt


Write a function CountUpperLower() to count lowercase and uppercase characters.

def
CountUpperLower():
upper = lower = 0
with open("Story.txt", "r") as f:
for ch in f.read():
if
ch.isupper():
upper += 1
elif
ch.islower():
lower += 1
print("Uppercase:", upper)
print("Lowercase:", lower)

6. Program to count lines starting with ‘I’ or ‘M’ in MyData.txt


Write a function CountM() that counts lines starting with I or M.

def CountM():
count = 0
with open("MyData.txt", "r") as f:
for line in f:
if line.strip().startswith(("I", "M")):
count += 1
print("Lines starting with I or M:", count)
7. Program to count lines starting with ‘H’ in Lines.txt
Write a function CountH() to count lines beginning with H.

def CountH():
count = 0
with open("Lines.txt", "r") as f:
for line in f:
if
line.strip().startswith("H"):
count += 1
print("Lines starting with H:", count)

8. Program to count independent word “the” or “The” in MyFile.txt


Write a function CountThe() to count exact word occurrences of “the” or “The”.

def CountThe():
count = 0
with open("MyFile.txt", "r") as f:
for word in f.read().split():
if word.lower() == "the":
count += 1
print("Count of 'the':", count)

9. Program to count occurrences of “He” or “She” as independent words


Write a function CountHeShe() to count “He” or “She” in MyFile.txt.

def CountHeShe():
count = 0
with open("MyFile.txt", "r") as f:
for word in f.read().split():
if word in ["He",
"She"]: count += 1
print("Count of He/She:", count)

10. Program to display lines starting with ‘K’ from MyNotes.txt


Write a function Display() to print lines starting with alphabet K.

def Display():
with open("MyNotes.txt", "r") as f:
for line in f:
if
line.strip().startswith("K"):
print(line, end="")
11. Program to count number of spaces in Data.txt
Write a function CountSpace() to count all spaces.

def CountSpace():
count = 0
with open("Data.txt", "r") as f:
for ch in f.read():
if ch == " ":
count += 1
print("Total spaces:", count)

12. Program to count vowels in Data.txt


Write a function CountVowels() to count vowels (A, E, I, O, U in any case).

def CountVowels():
vowels = "aeiou"
count = 0
with open("Data.txt", "r") as f:
for ch in f.read().lower():
if ch in vowels:
count += 1
print("Total vowels:", count)

13. Program to copy contents of Data1.txt to Data2.txt without spaces


Write a function CopyContents() that writes everything except spaces.

def CopyContents():
with open("Data1.txt", "r") as f1, open("Data2.txt", "w") as f2:
for ch in f1.read():
if ch != " ":
f2.write(ch)
print("Copy complete (spaces removed).")
Binary File Programs
1. Program to Add Book Records and Count Books by Author
(Book.dat) AddRecords() adds records in the format [BookID,
BookName, Author, Price]. CountRec(author) counts books written
by the given author.

import pickle

def AddRecords():
f = open("Book.dat", "ab")
bookid = int(input("Enter Book
ID: ")) name = input("Enter Book
Name: ")) author = input("Enter
Author Name: ")) price =
float(input("Enter Price: "))
rec = [bookid, name, author,
price] pickle.dump(rec, f)
f.close()
print("Record added.")

def CountRec(author):
count =
0 try:
f = open("Book.dat",
"rb") while True:
rec = pickle.load(f)
if rec[2].lower() ==
author.lower(): count += 1
except:
pass
print("Books by", author, "=", count)

2. Program to Add and Search Employee Records (Employee.dat)


WriteRecords() adds [EmpCode, EmpName, Salary].
Search() prints record matching the given EmpCode.

import pickle

def WriteRecords():
f = open("Employee.dat", "ab")
code = int(input("Enter Employee
Code: ")) name = input("Enter
Employee Name: ")) salary =
float(input("Enter Salary: "))
rec = [code, name,
salary]
pickle.dump(rec, f)
f.close()
print("Record added.")
def Search():
code = int(input("Enter Employee Code to Search:
")) found = False
try:
f = open("Employee.dat",
"rb") while True:
rec =
pickle.load(f) if
rec[0] == code:
print("Record Found:", rec)
found = True
except:
pass
if not found:
print("No matching record found.")

3. Program to Add Students and Display Marks > 81 (Student.dat)


Create() adds [RollNumber, Name, Marks].
Display() prints students having marks more than

81. import pickle

def Create():
f = open("Student.dat", "ab")
roll = int(input("Enter Roll
Number: ")) name = input("Enter
Name: ")
marks = float(input("Enter
Marks: ")) rec = [roll, name,
marks] pickle.dump(rec, f)
f.close()
print("Record added.")

def Display():
found =
False try:
f = open("Student.dat",
"rb") while True:
rec =
pickle.load(f) if
rec[2] > 81:
print(rec)
found =
True
except:
pass
if not found:
print("No Record Found")
4. Program to Add Bus Records and Search for Buses Going to Delhi (Bus.dat)
Insert() adds [BusNumber, StartingPlace,
DestinationPlace]. Search() prints buses whose
destination is “Delhi”.

import

pickle def

Insert():
f = open("Bus.dat", "ab")
bno = int(input("Enter Bus
Number: ")) start = input("Enter
Starting Place: ") dest =
input("Enter Destination: "))
rec = [bno, start,
dest]
pickle.dump(rec, f)
f.close()
print("Record added.")

def Search():
print("Buses going to
Delhi:") try:
f = open("Bus.dat",
"rb") while True:
rec = pickle.load(f)
if rec[2].lower() == "delhi":
print(rec)
excep
t:
pass

5. Program to Add and Modify Route Records (Route.dat)


Insert() adds [RouteNumber, RouteName].
RouteChange(routeno) modifies RouteName of the given route

number. import pickle, os

def Insert():
f = open("Route.dat", "ab")
rno = int(input("Enter Route
Number: ")) rname = input("Enter
Route Name: ")) rec = [rno,
rname]
pickle.dump(rec
, f) f.close()
print("Record added.")

def
RouteChange(routeno):
f = open("Route.dat",
"rb")
temp = open("Temp.dat",
"wb") found = False
try:
while True:
rec =
pickle.load(f) if
rec[0] ==
routeno:
rec[1] = input("Enter new Route
Name: ") found = True
pickle.dump(rec,
temp) except:
pass
f.close()
temp.close
()
os.remove("Route.dat")
os.rename("Temp.dat",
"Route.dat") if found:
print("Route
updated.") else:
print("Route number not found.")

6. Program to Add Employee Records and Display Salary > 20000 (Employee.dat)
Insert() adds [EmpID, EmpName, Salary].
Display() prints employees whose salary is more than

20000. import pickle

def Insert():
f = open("Employee.dat", "ab")
eid = int(input("Enter Employee ID:
")) name = input("Enter Employee
Name: ")) salary = float(input("Enter
Salary: "))
rec = [eid, name,
salary]
pickle.dump(rec, f)
f.close()
print("Record added.")

def Display():
print("Employees with Salary >
20000:") try:
f = open("Employee.dat",
"rb") while True:
rec =
pickle.load(f) if
rec[2] > 20000:
print(rec)
excep
t:
pass
7. Program to Add, Display, Search, Modify and Delete Room Records (Hotel.dat)
AddRecords() adds [RoomNo, RoomType,
Price]. Display() prints all hotel records.
SpecificRoom(roomno) searches for a
room. ModifyRoom(roomno) updates
room details. DeleteRoom(roomno)
removes a room.

import pickle,

os def

AddRecords():
f = open("Hotel.dat", "ab")
rno = int(input("Enter Room
Number: ")) rtype = input("Enter
Room Type: ")) price =
float(input("Enter Price: "))
rec = [rno, rtype,
price]
pickle.dump(rec, f)
f.close()
print("Record added.")

def Display():
try:
f = open("Hotel.dat",
"rb") while True:
print(pickle.load(f))
except:
pass

def
SpecificRoom(roomno):
found = False
try:
f = open("Hotel.dat",
"rb") while True:
rec =
pickle.load(f) if
rec[0] ==
roomno:
print(rec)
found =
True
except:
pass
if not found:
print("Room not
found.")

def
ModifyRoom(roomno):
f = open("Hotel.dat",
"rb")
temp = open("Temp.dat",
"wb") found = False
try:
while True:
rec = pickle.load(f)
if rec[0] == roomno:
rec[1] = input("Enter new Room
Type: ") rec[2] = float(input("Enter
new Price: ")) found = True
pickle.dump(rec,
temp) except:
pass
f.close()
temp.close
()
os.remove("Hotel.dat")
os.rename("Temp.dat",
"Hotel.dat") if found:
print("Room
modified.") else:
print("Room not found.")

def
DeleteRoom(roomno):
f = open("Hotel.dat",
"rb")
temp = open("Temp.dat",
"wb") found = False
try:
while True:
rec =
pickle.load(f) if
rec[0] !=
roomno:
pickle.dump(rec,
temp) else:
found =
True
except:
pass
f.close()
temp.close
()
os.remove("Hotel.dat")
os.rename("Temp.dat",
"Hotel.dat") if found:
print("Room
deleted.") else:
print("Room not found.")

8. Program to Add and Delete Product Records


(Product.dat) Input() adds [ProductID, ProductName,
ProductPrice]. DeleteRecord(productid) removes
product data.
import pickle,

os def Input():
f = open("Product.dat", "ab")
pid = int(input("Enter Product ID:
")) name = input("Enter Product
Name: "))
price = float(input("Enter Product
Price: ")) rec = [pid, name, price]
pickle.dump(rec
, f) f.close()
print("Record added.")

def
DeleteRecord(productid)
: f = open("Product.dat",
"rb")
temp = open("Temp.dat",
"wb") found = False
try:
while True:
rec = pickle.load(f)
if rec[0] !=
productid:
pickle.dump(rec,
temp) else:
found =
True
except:
pass
f.close()
temp.close
()
os.remove("Product.dat")
os.rename("Temp.dat",
"Product.dat") if found:
print("Record
deleted.") else:
print("Product ID not found.")
CSV File Programs
1. Program to Add Mobile Records and Read All from Mobile.csv

Input() adds records in the format [MobileID, MobileCompany,


Price]. ReadAll() reads and prints all records from Mobile.csv.

import

csv def

Input():
f = open('Mobile.csv','a',newline='')
w = csv.writer(f)
mid = input("Enter Mobile ID: ")
comp = input("Enter Mobile
Company: ") price = input("Enter
Price: ") w.writerow([mid, comp,
price])
f.close()
print("Record added.")

def ReadAll():
f=
open('Mobile.csv','r')
r = csv.reader(f)
for rec in r:
print(rec)
f.close()

2. Program to Add Student Records and Read All from Student.csv

Input() adds student records [Admno, Name, Class, Section,


Marks]. ReadAll() prints all records from Student.csv.

import

csv def

Input():
f = open('Student.csv','a',newline='')
w = csv.writer(f)
adm = input("Enter
Admno: ") name =
input("Enter Name: ") clas
= input("Enter Class: ")
sec = input("Enter
Section: ") marks =
input("Enter Marks: ")
w.writerow([adm, name, clas, sec,
marks]) f.close()
print("Record added.")
def ReadAll():
f=
open('Student.csv','r'
) r = csv.reader(f)
for rec in r:
print(rec)
f.close()

3. Program to Add Student Records and Search by Admission Number

Input() adds student records [Admno, Name, Class, Section,


Marks]. Search(admno) prints the record matching the given
admission number.

import

csv def

Input():
f = open('Student.csv','a',newline='')
w = csv.writer(f)
adm = input("Enter
Admno: ") name =
input("Enter Name: ") clas
= input("Enter Class: ")
sec = input("Enter
Section: ") marks =
input("Enter Marks: ")
w.writerow([adm, name, clas, sec,
marks]) f.close()
print("Record added.")

def Search(admno):
f=
open('Student.csv','r'
) r = csv.reader(f)
found =
False for rec
in r:
if rec[0] ==
admno: print(rec)
found =
True if not
found:
print("Record not found")
f.close()

4. Program to Add Product Records and Search by Price > 800


Input() adds product records [ProductID, ProductName, Price].
SearchProduct(price) prints records with price more than 800.

import csv
def Input():
f=
open('Product.csv','a',newline=
'') w = csv.writer(f)
pid = input("Enter Product ID: ")
name = input("Enter Product
Name: ") price = input("Enter
Price: ") w.writerow([pid, name,
price]) f.close()
print("Record added.")

def
SearchProduct(price):
f =
open('Product.csv','r')
r = csv.reader(f)
for rec in r:
if int(rec[2]) >
price: print(rec)
f.close()

5. Program to Add Student Records and Display Marks > 80

Input() adds student records [Admno, Name, Class, Section,


Marks]. SearchRecord() prints all students with marks greater
than 80.

import

csv def

Input():
f = open('Student.csv','a',newline='')
w = csv.writer(f)
adm = input("Enter
Admno: ") name =
input("Enter Name: ") clas
= input("Enter Class: ")
sec = input("Enter
Section: ") marks =
input("Enter Marks: ")
w.writerow([adm, name, clas, sec,
marks]) f.close()
print("Record added.")

def SearchRecord():
f=
open('Student.csv','r'
) r = csv.reader(f)
for rec in r:
if int(rec[4]) >
80: print(rec)
f.close()
6. Program to Add Product Records and Search by Product Name “Scanner”

Input() adds product records [ProductID, ProductName, Price].


SearchRecord() prints all products with name “Scanner”.

import

csv def

Input():
f = open('Product.csv','a',newline='')
w = csv.writer(f)
pid = input("Enter Product ID: ")
name = input("Enter Product
Name: ") price = input("Enter
Price: ") w.writerow([pid, name,
price]) f.close()
print("Record added.")

def SearchRecord():
f=
open('Product.csv','r')
r = csv.reader(f)
for rec in r:
if rec[1].lower() ==
"scanner": print(rec)
f.close()
Data Structure Problems
1. Program to Push and Pop Student Names in a Stack

push(studentname) adds a student name to the


stack. pop(studentname) removes a student name
from the stack.

student = []

def push(studentname):
student.append(studentname)
print(f"{studentname} added to the
stack.")

def pop():
if len(student) == 0:
print("Stack is
empty") else:
removed = student.pop()
print(f"{removed} removed from the stack.")

2. Program to Push and Pop Book Titles in a Stack

PushOn(BookTitle) adds a book title to the stack.


Pop(BookTitle) removes the last added book title from

the stack. Books = []

def PushOn(BookTitle):
Books.append(BookTitle)
print(f"'{BookTitle}' added to the
stack.")

def Pop():
if len(Books) == 0:
print("Stack is
empty") else:
removed = Books.pop()
print(f"'{removed}' removed from the stack.")

3. Program to Perform Basic Stack Operations on Books

Creates a stack called Book with [BookID, BookName] and


performs: insert() – push data values into the stack
delete() – pop data values from the
stack show() – display data values from
the stack
Book = []

def insert():
bid = input("Enter Book ID: ")
name = input("Enter Book
Name: ") Book.append([bid,
name]) print("Book added to
stack.")

def delete():
if len(Book) == 0:
print("Stack is
empty") else:
removed = Book.pop()
print(f"Removed Book:
{removed}")

def show():
if len(Book) == 0:
print("Stack is
empty") else:
for b in reversed(Book):
print(b)

4. Program to Perform Basic Stack Operations on Students

Creates a stack called Student with [RollNo, Name] and


performs: insert() – push data values into the stack
delete() – pop data values from the
stack show() – display data values from
the stack

Student =

[] def

insert():
roll = input("Enter Roll No: ")
name = input("Enter Name:
") Student.append([roll,
name]) print("Student
added to stack.")

def delete():
if len(Student) ==
0: print("Stack is
empty") else:
removed = Student.pop()
print(f"Removed Student:
{removed}")
def show():
if len(Student) == 0:
print("Stack is empty")
else:
for s in reversed(Student):
print(s)

5. Program to Manage Hostel Records Using Stack

Menu-based program to add, delete, and display hostel records [HostelID,


TotalStudents, TotalRooms] using stack.

HostelStack =

[] def

addRecord():
hid = input("Enter Hostel ID: ")
totalStud = input("Enter Total Students: ")
totalRooms = input("Enter Total Rooms: ")
HostelStack.append([hid, totalStud,
totalRooms]) print("Hostel record added.")

def deleteRecord():
if len(HostelStack) ==
0: print("Stack is
empty") else:
removed = HostelStack.pop()
print(f"Removed record:
{removed}")

def showRecords():
if len(HostelStack) ==
0: print("Stack is
empty") else:
for rec in
reversed(HostelStack):
print(rec)
MySQL Problems

1. Shop Table

Code ItemName Company Qty City Price

102 Biscuit Hide and Seek 100 Delhi 10.00

103 Jam Kissan 110 Kolkata 25.00

101 Coffee Nestle 200 Kolkata 55.00

106 Sauce Nestle 56 Mumbai 55.00

107 Cake Britannia 72 Delhi 10.00

104 Maggi Nestle 150 Mumbai 10.00

105 Chocolate Cadbury 170 Delhi 25.00

(a) Question:
Display names of items starting with 'C' in ascending order of price.

Answer:
SQL Command:
SELECT ItemName FROM Shopee WHERE ItemName LIKE 'C%' ORDER BY Price
ASC;

Output:
ItemNam
e Cake
Coffee
Chocolat
e

(b)Question:
Display code, itemname, and city of items with quantity less than 100.

Answer:
SQL Command:
SELECT Code, ItemName, City FROM Shopee WHERE Qty < 100;

Output:
Code ItemName City
106Sauce Mumbai
107Cake Delhi
(c) Question:
Count the number of distinct companies.

Answer:
SQL Command:
SELECT COUNT(DISTINCT Company) FROM Shopee;

Outpu
t: 5

(d)Question:
Insert a new row: 108, 'Tea', 'Tata', 80, 'Delhi', 15.00

Answer:
SQL Command:
INSERT INTO Shopee VALUES (108, 'Tea', 'Tata', 80, 'Delhi', 15.00);

(e)Question:
Select itemname for items 'Jam' or 'Coffee'.

Answer:
SQL Command:
SELECT ItemName FROM Shopee WHERE ItemName IN ('Jam', 'Coffee');

Output:
ItemNam
e Jam
Coffee

(f)Question:
Count distinct cities.

Answer:
SQL Command:
SELECT COUNT(DISTINCT City) FROM Shopee;

Outpu
t: 3
(g)Question:
Find minimum quantity for items in Mumbai.

Answer:
SQL Command:
SELECT MIN(Qty) FROM Shopee WHERE City='Mumbai';

Output:
56

2. Employee Table

S.No Name Salary Area Age Grade Dept

1 Vinay 40000 West 45 C Civil

2 Akash 35000 South 38 A Elec

3 Yogesh 60000 North 52 Now B Civil

4 Monesh 38000 North 29 B Civil

5 Simarjee 42000 East 35 A Comp


t
6 Chetan 29000 South 34 A Mech

(a) Question:
Display names of all employees who are in area South.

Answer:
SQL Command:
SELECT Name FROM Employee WHERE Area='South';

Output
:
Name
Akash
Cheta
n

(b)Question:
Display name and age of all employees having age > 40.

Answer:
SQL Command:
SELECT Name, Age FROM Employee WHERE Age > 40;
Output:
Name
Age
Vinay 45
Yogesh 52

(c) Question:
Display list of all employees whose salary is between 30000 and 40000.

Answer:
SQL Command:
SELECT * FROM Employee WHERE Salary >= 30000 AND Salary <= 40000;

Output:
S.No Name Salary Area Age Grade Dept
1 Vinay 40000 West 45 C Civil
2 Akash 35000 South 38 A Elec
4 Monesh 38000 North 29 B Civil

(d)Question:
Display the list department-wise.

Answer:
SQL Command:
SELECT * FROM Employee ORDER BY Dept;

Output:
S.No Name Salary Area Age Grade
Dept 1 Vinay 40000 West 45 C Civil
3 Yogesh 60000 North 52 B Civil
4 Monesh 38000 North 29 B Civil
6 Chetan 29000 South 34 A Mech
5 Simarjeet 42000 East 35 A Comp
2 Akash 35000 South 38 A Elec

(e)Question:
Display employee names in descending order of age.

Answer:
SQL Command:
SELECT Name FROM Employee ORDER BY Age DESC;

Output
:
Name
Yoges
h
Vinay
Simarje
et
Akash
Chetan
Monesh

(f)Question:
Insert a new row with the following data:
7, “Tarak”, 45000, “South”, 45, “C”, “Elec”

Answer:
SQL Command:
INSERT INTO Employee VALUES (7, 'Tarak', 45000, 'South', 45, 'C', 'Elec');

Output:
Row added successfully (no visible output).

(g)Question:
Write the output of the following SQL commands:

(i) SELECT MIN(Age) FROM Employee;


Output: 29

(ii)SELECT SUM(Salary) FROM Employee WHERE Grade='A';


Output: 106000

(iii) SELECT AVG(Salary) FROM Employee WHERE Dept='Civil';


Output: 46000

(iv)SELECT COUNT(DISTINCT Dept) FROM Employee;


Output: 4
4. Student Table

StdNo Class Name Game Grade SUPW Sgrade

10 7 Sameer Cricket B Photography A

11 8 Sujit Tennis A Gardening C

12 7 Kamal Swimming B Photography B

13 7 Veena Tennis C Cooking A

14 9 Archana Basket Ball A Literature A

15 10 Arpit Cricket A Gardening C

(a) Question:
Display names of students who are getting grade “C” in either Game or SUPW.

Answer:
SQL Command:
SELECT Name FROM Student WHERE Grade='C' OR Sgrade='C';

Output:
Nam
e
Veen
a
Sujit
Arpit

(b) Question:
Display the number of students getting grade “A” in Cricket.

Answer:
SQL Command:
SELECT COUNT(*) FROM Student WHERE Game='Cricket' AND Grade='A';

Output:
Coun
t1

(c) Question:
Display the different games offered in the school.

Answer:
SQL Command:
SELECT DISTINCT Game FROM Student;
Output:
Game
Cricket
Tennis
Swimmin
g Basket
Ball

(d) Question:
Display the SUPW taken up by the students whose name starts with “A”.

Answer:
SQL Command:
SELECT SUPW FROM Student WHERE Name LIKE 'A%';

Output:
SUPW
Literatur
e
Gardenin
g

(e) Question:
Add a new column named “Marks” in the Student table.

Answer:
SQL Command:
ALTER TABLE Student ADD Marks INT;

Output:
Column added successfully (no visible output).

(f) Question:
Assign a value 200 for marks for all those who are getting grade “B” or above in
Game.

Answer:
SQL Command:
UPDATE Student SET Marks=200 WHERE Grade IN ('A','B');

Output:
Rows updated successfully (no visible output).

(g) Question:
Arrange the table in alphabetical order of SUPW.

Answer:
SQL Command:
SELECT * FROM Student ORDER BY SUPW ASC;

Output:
StdNo Clas Name Game Grade SUPW Sgrad Marks
s e

13 7 Veena Tennis C Cooking A NULL

15 10 Arpit Cricket A Gardening C 200

11 8 Sujit Tennis A Gardening C 200

14 9 Archana Basket Ball A Literature A 200

10 7 Sameer Cricket B Photograp A 200


hy

12 7 Kamal Swimming B Photograp B 200


hy
Hospital Table

No. Name Age Department DateofAdm Charges Gende


r

1 Sandeep 65 Surgery 23/02/98 300 M

2 Ravina 24 ENT 20/01/98 200 F

3 Karan 45 Orthopedic 19/02/98 200 M

4 Tarun 12 Surgery 01/01/98 300 M

5 Zubin 36 ENT 12/01/98 250 M

6 Ketika 16 ENT 24/02/98 250 F

7 Ankita 29 Cardiology 20/02/98 800 F

8 Zareen 45 Gynecology 22/02/98 300 F

9 Kush 19 Cardiology 13/01/98 800 M

10 Shailya 31 Nuclear 19/02/98 400 M


Med

(a) Show all information of patients in Cardiology department

Output:
7 Ankita 29 Cardiology 20/02/98 800 F
9 Kush 19 Cardiology 13/01/98 800 M

(b) List names of female patients in Orthopedic department

Output:
(No results)

(c) List names of all patients with their date of admission in ascending order

Output:
4 Tarun 01/01/98
5 Zubin 12/01/98
9 Kush 13/01/98
2 Ravina 20/01/98
7 Ankita 20/02/98
10 Shailya 19/02/98
3 Karan 19/02/98
8 Zareen 22/02/98
1 Sandeep 23/02/98
6 Ketika 24/02/98

(d) Display patient’s name, charges, age for male patients

Output:
1 Sandeep 300 65
3 Karan 200 45
4 Tarun 300 12
5 Zubin 250 36
9 Kush 800 19
10 Shailya 400 31

(e) Count the number of patients with age > 20

Outpu
t: 7

(f) Insert new row: 11, Mustafa, 37, ENT, 25/02/98, 250, M

Output (table after insertion, if needed for reference):


1 Sandeep 65 Surgery 23/02/98 300 M
2 Ravina 24 ENT 20/01/98 200 F
3 Karan 45 Orthopedic 19/02/98 200 M
4 Tarun 12 Surgery 01/01/98 300 M
5 Zubin 36 ENT 12/01/98 250 M
6 Ketika 16 ENT 24/02/98 250 F
7 Ankita 29 Cardiology 20/02/98 800 F
8 Zareen 45 Gynecology 22/02/98 300 F
9 Kush 19 Cardiology 13/01/98 800 M
10 Shailya 31 Nuclear Med 19/02/98 400 M
11Mustafa 37 ENT 25/02/98 250 M

(g) Outputs of MySQL queries

(i) select count(distinct(department)) from Hospital;


Output: 6
(ii)select max(age) from Hospital where Gender="M";
Output: 65
(iii) select avg(charges) from Hospital where Gender="F";
Output: 387.5
(iv)select sum(charges) from Hospital where
dateofAdm<"12/02/98"; Output: 1050
5. Club Members

Mcode Mname Gender Age Fees Type

1 Pratyus h M 45 24000 Yearly

2 Deepak M 35 8000 Monthly

3 Gitika F 22 7000 Monthly

4 Pallavi F 27 12000 Quarterly

5 Varun M 54 6000 Monthly

6 Prerna F 43 4500 Monthly

7 Farida F 22 500 Guest

8 Jatin M 51 24000 Yearly

9 Rakshit M 44 100000 Life

10 Harshit M 32 13000 Quarterly


(a) To display Mname, Age, Fees of members whose Fees is between 5000 and
11000.

Output:
Deepak 35 8000
Gitika 22 7000
Varun 54 6000

(b)To display Mcode, Mname, Age of all female members in ascending order of
age.

Output:
3 Gitika 22
7 Farida 22
4 Pallavi 27
6 Prerna 43

(c) To display Mname, Age, Type of all members in ascending order of Mname.

Output:
Deepak 35 Monthly
Farida 22 Guest
Gitika 22 Monthly
Harshit 32 Quarterly
Jatin 51 Yearly
Pallavi 27 Quarterly
Pratyush 45 Yearly
Prerna 43 Monthly
Rakshit 44 Life
Varun 54 Monthly

(d)To display Mname, Fees of all members whose Age < 40 and Type =
“Monthly”.

Output:
Deepak
8000
Gitika 7000

(e)To insert a new tuple: 11, “Vaibhav”, “M”, 30000, “Guest”.

Output: (no output; data inserted successfully)

(f)Output queries:

(i) Select max(Fees) from Club;


Output: 100000

(ii)Select sum(Fees) from Club where Age>35;


Output: 24000 + 6000 + 24000 + 4500 + 100000 + 13000 = 210500

(iii) Select avg(Age) from Club where Type =


“Monthly”; Output: (35 + 22 + 54 + 43)/4 =
38.5
6. Employee Table

Empid Firstname Lastname Address City

010 George Smith 83 First Street Howard

105 Mary Jones 842 Vine Ave Losantiville

152 Sam Tones 33 Elm Street Paris

215 Sarah Ackerman 440 U S 110 Upton

244 Manila Sengupta 24 Friends Street New Delhi

300 Rabert Samuel 9 Fifth Cross Washington

335 Henry Williams 12 Moore Street Boston

400 Rachel Lee 12 Harrson Street New York

441 Peter Thompso n 11 Red Road Paris

Salary Table
Empid Salary Benefits Designation

010 75000 15000 Manager

105 65000 15000 Manager

152 80000 25000 Director

215 75000 12500 Manager

244 50000 12000 Clerk

300 45000 10000 Clerk

335 40000 10000 Clerk

400 32000 7500 Salesman

441 28000 7500 Salesman


(a) Display firstname, lastname, address and city of all employees living in Paris.

Output:
Sam Tones 33 Elm Street Paris
Peter Thompson 11 Red Road
Paris

(b)Display contents of Employees table in descending order of Firstname.

Output:
Sam Tones 33 Elm Street Paris
Sarah Ackerman 440 U S 110
Upton
Rabert Samuel 9 Fifth Cross
Washington Peter Thompson 11 Red
Road Paris Rachel Lee 12 Harrson
Street New York Mary Jones 842 Vine
Ave Losantiville
Manila Sengupta 24 Friends Street New
Delhi Henry Williams 12 Moore Street
Boston George Smith 83 First Street
Howard

(c) Display firstname, lastname, and total salary of all managers (Total Salary
= Salary + Benefits).

Output:
George Smith 90000
Mary Jones 80000
Sarah Ackerman 87500

(d)Display maximum salary among managers and clerks.

Output:
Manager:
75000
Clerk: 50000

(e)Select firstname, salary from Employees and EmpSalary where


Designation = “Salesman”.

Output:
Rachel
32000
Peter 28000
(f)Select count(distinct Designation) from EmpSalary.

Output: 4

(g)Select Designation, sum(Salary) from EmpSalary group by


Designation having count(*)>2.

Output:
Manager 215000
Clerk 135000

(h)Select sum(Benefits) from Employees where Designation = “Clerk”.

Output: 32000
7. Stock Table

ItemNo Item Dcod Qty UnitPrice StockDate


e

5005 Ball Pen 0.5 102 100 16 31/03/201


0
5003 Ball Pen 0.25 102 150 20 01/01/201
0
5002 Gel Pen 101 125 14 14/02/201
Premium 0
5006 Gel Pen Classic 101 200 22 01/01/200
9
5001 Eraser Small 102 210 5 19/03/200
9
5004 Eraser Big 102 60 10 12/12/200
9
5009 Sharpener 103 160 8 23/01/200
Classic 9

Dealer Table

Dcode Dname

101 Reliable
Stationers
102 Clear Deals

103 Classic Plastics

(a) Display details of all items in STOCK in ascending order of StockDate.

Output:
5006 Gel Pen Classic 101 200 22 01/01/2009
5001 Eraser Small 102 210 5 19/03/2009
5004 Eraser Big 102 60 10 12/12/2009
5003 Ball Pen 0.25 102 150 20 01/01/2010
5002 Gel Pen Premium 101 125 14 14/02/2010
5005 Ball Pen 0.5 102 100 16 31/03/2010
5009 Sharpener Classic 103 160 8 23/01/2009

(b)Display ItemNo and Item Name of items with UnitPrice > 10.

Output:
5005 Ball Pen 0.5
5003 Ball Pen 0.25
5002 Gel Pen
Premium 5006 Gel
Pen Classic

(c) Display details of items whose dealer code = 102 or Qty > 100.

Output:
5005 Ball Pen 0.5 102 100 16 31/03/2010
5003 Ball Pen 0.25 102 150 20 01/01/2010
5002 Gel Pen Premium 101 125 14 14/02/2010
5001 Eraser Small 102 210 5 19/03/2009
5006 Gel Pen Classic 101 200 22 01/01/2009

(d)Display maximum UnitPrice of items for each dealer (Dcode).

Output:
101 22
102 20
103 8

(e)Count distinct Dcode in

STOCK. Output: 3

(f)Calculate Qty * UnitPrice for ItemNo = 5006.

Output: 4400

(g)Display Item and Dname where ItemNo = 5004.

Output:
Eraser Big Clear Deals

(h)Minimum StockDate in

STOCK. Output: 01/01/2009


8. Sender and Recipient

Sender Table

SenderID SenderNamSenderAddress SenderCity


e

ND01 R Jain 2 ABC Appts New Delhi

MU02 H Sinha 12 Newton Mumbai

MU15 S Jha 27/A, Park Street Mumbai

ND50 T Prasad 122-K, SDA New Delhi

Recipient Table

RecID SenderID RecName RecAddress RecCity

K005 ND01 R Bajpayee 5 Central Avenue Kolkata

ND08 MU02 S Mahajan 116 A Vihar New Delhi

MU19 ND01 H Singh 2A, Andheri East Mumbai

MU32 MU15 P K Swamy B5 C S Terminus Mumbai

ND48 ND50 S Tripathi 13, B1 D, Mayur Vihar New Delhi

(i) Display RecID, SenderName, SenderAddress, RecName, RecAddress


for every Recipient.

Output:
K005 R Jain 2 ABC Appts R Bajpayee 5 Central Avenue
ND08 H Sinha 12 Newton S Mahajan 116 A Vihar
MU19 R Jain 2 ABC Appts H Singh 2A, Andheri East
MU32 S Jha 27/A, Park Street P K Swamy B5 C S Terminus
ND48 T Prasad 122-K, SDA S Tripathi 13, B1 D, Mayur
Vihar

(ii)Display Recipient details in ascending order of RecName.

Output:
K005 R Bajpayee 5 Central
Avenue ND08 S Mahajan 116 A
Vihar MU19 H Singh 2A,
Andheri East
MU32 P K Swamy B5 C S Terminus
ND48 S Tripathi 13, B1 D, Mayur
Vihar

(iii) Number of Recipients from each city.

Output:
Kolkata
1
New Delhi 2
Mumbai 2

(iv)Select distinct SenderCity from Sender.

Output:
New
Delhi
Mumbai

(v)Display SenderName and RecName where RecCity = “Mumbai”.

Output:
R Jain H Singh
S Jha P K Swamy

(vi)Display RecName and RecAddress where RecCity not in (“Mumbai”,


“Kolkata”).

Output:
S Mahajan 116 A Vihar
S Tripathi 13, B1 D, Mayur Vihar

(vii) Display RecID and RecName where SenderID = “MU02” or “ND50”.

Output:
ND08 S Mahajan
ND48 S Tripathi
9. Products Table

No Name Price Supplier Stock

1 Motherboa 7000 Intel 20


rd

2 Keyboard 1000 TVSE 70

3 Mouse 500 Logitech 60

4 Soundcard 600 Samsung 50

5 Speaker 600 Samsung 25

6 Monitor 3000 Philips 22

7 CD ROM 2800 Creative 32

8 Printer 7900 HP 10

(a) Display data for the entire item sorted by their name.

Output:
CD ROM 2800 Creative 32
Keyboard 1000 TVSE 70
Monitor 3000 Philips 22
Motherboard 7000 Intel 20
Mouse 500 Logitech 60
Printer 7900 HP 10
Soundcard 600 Samsung 50
Speaker 600 Samsung 25

(b)Display Name and Price from the table in reverse order of Stock.

Output:
Keyboard
1000
Mouse 500
Soundcard 600
Speaker 600
CD ROM 2800
Monitor 3000
Motherboard 7000
Printer 7900

(c) List all Name and Price with Price between 3000 and 7000.
Output:
Monitor
3000
Motherboard 7000

(d)Set the price field of all products to 1200 where Name = 'Keyboard'.

Output:
Keyboard 1200 TVSE 70

(e)Delete rows with stock between 20 to 40.

Output:
Deleted rows: CD ROM, Motherboard, Monitor, Speaker

(f)Count the number of products with stock < 5.

Outpu
t: 0

(g)Outputs for given SQL commands:

(i) Sum(Stock): 20+70+60+50+25+22+32+10 = 289


(ii)Avg(Stock) where stock>20: (70+60+50+25+32)/5 = 47.4
(iii) Count(Distinct stock): 20,70,60,50,25,22,32,10 → 8
(iv)Max(Price): 7900
10.Shop Table

No Shop_Name Sale Area Cust_Percent Rating City

1 S M Sons 250000 West 68.6 C Delhi

2 Dharohar 500000 South 81.8 A Mumbai

3 Kirti Art 300000 North 79.8 B Kolkata

4 Ripple 380000 North 88.0 B Mumbai

5 Biswas 456000 East 92.0 A Delhi


Stores

6 Crystal 290000 South 66.7 A Kolkata

(a) Display the names of all shops which are in the area South.

Output:
Dharoh
ar
Crystal

(b)Display name and customer percentage of all the shops having


cust_percent>80.

Output:
Dharohar
81.8
Ripple 88.0
Biswas Stores 92.0

(c) Display a list of all shops with sale>300000 in ascending order of Shop_Name.

Output:
Biswas Stores 456000
Dharohar 500000
Ripple 380000

(d)Display a report with Shop_Name, Area and Rating for only those shops
whose sale is between 350000 and 400000.

Output:
Ripple North B
(e)Display the city and the number of shops in each city.

Outpu
t:
Delhi
2
Mumbai 2
Kolkata 2

(f)Insert details of a new shop with the following data: 7, 'The Shop', 550000,
'South', 90.8, 'A', 'Ahmedabad'.

Output:
Shop inserted: The Shop, 550000, South, 90.8, A, Ahmedabad

(g)Outputs for given SQL commands:

(i) Select Min(Cust_Percent) from Shop → 66.7


(ii)Select Sum(Sale) where Rating='A' → 500000 + 456000 + 290000 + 550000
= 1796000
(iii) Select Avg(Sale) from Shop where City=’Delhi’ → (250000 + 456000)/2 =
353000
(iv)Select Count(Distinct City) from Shop → 3
Python Database Connectivity

Employee Table
EmpID EmpName City Department Salary

1001 Rakesh Indore Accounts 20000


Sharm
a
1002 Vikas Jain Bhopal Sales 18000

1003 Sanjay Sahu Indore Purchase 17000

1004 Vijay Neema Dewas IT 25000

1005 Navin Sharma Indore IT 25000

Problem 1: Retrieve all records from EmpInfo

import mysql.connector

conn =
mysql.connector.connect( h
ost="localhost",
user="root",
password="your_passwor
d", database="Office"
)
cursor = conn.cursor()

cursor.execute("SELECT * FROM EmpInfo")


rows = cursor.fetchall()

print("All Employee Records:")


for row in rows:
print(row)

cursor.close()
conn.close(
)
Problem 2: Display employee details for EmpID = 1003

import mysql.connector

conn =
mysql.connector.connect( h
ost="localhost",
user="root",
password="your_passwor
d", database="Office"
)
cursor = conn.cursor()

emp_id = 1003
cursor.execute("SELECT * FROM EmpInfo WHERE EmpID = %s",
(emp_id,)) rows = cursor.fetchall()

print(f"Employee Record with EmpID =


{emp_id}:") for row in rows:
print(row)

cursor.close
()
conn.close(
)

Items Table

ItemNo ItemName ItemPrice Quantity ItemSold

1001 Bread 25 20 10

1002 Butter 50 15 7

1003 Milk 60 25 10

1004 Jam 105 13 8

1005 Coffee 120 25 12

Problem 3: Display Items with ItemSold > 8 and count


import mysql.connector

conn =
mysql.connector.connect( h
ost="localhost",
user="root",
password="your_passwor
d", database="Shops"
)
cursor = conn.cursor()

cursor.execute("SELECT * FROM Items WHERE ItemSold >


8") rows = cursor.fetchall()

print("Items with ItemSold >


8:") for row in rows:
print(row)

print(f"Number of records:

{len(rows)}") cursor.close()
conn.close()

Problem 4: Delete Item by ItemNo = 1003 and display remaining

import mysql.connector

conn =
mysql.connector.connect( h
ost="localhost",
user="root",
password="your_passwor
d", database="Shops"
)
cursor = conn.cursor()

item_no = 1003
cursor.execute("DELETE FROM Items WHERE ItemNo = %s",
(item_no,)) conn.commit()

print(f"Deleted ItemNo = {item_no}. Remaining


Items:") cursor.execute("SELECT * FROM Items")
rows =
cursor.fetchall() for
row in rows:
print(row)

cursor.close()
conn.close(
)
Problem 5: Update ItemPrice for ItemNo = 1004 and display all
import mysql.connector

conn =
mysql.connector.connect( h
ost="localhost",
user="root",
password="your_passwor
d", database="Shops"
)
cursor = conn.cursor()

item_no = 1004
new_price = 150
cursor.execute("UPDATE Items SET ItemPrice = %s WHERE ItemNo = %s",
(new_price, item_no))
conn.commit()

print(f"Updated ItemPrice for ItemNo = {item_no} to {new_price}. All Items:")


cursor.execute("SELECT * FROM Items")
rows =
cursor.fetchall() for
row in rows:
print(row)

cursor.close()
conn.close(
)

You might also like