0% found this document useful (0 votes)
22 views37 pages

Wa0000.

Uploaded by

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

Wa0000.

Uploaded by

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

BVM GLOBAL @ COIMBATORE

Senior Secondary School


LAB MANUALS
Class: XII Subject: Computer Science
Program:1
Finding the frequency of a number stored in a list using linear
search mechanism
Question:
Write a python program to search an element in a list and display the frequency of
the element with its location using linear search mechanism
Aim:
To Write a python program to search an element in a list and display thefrequency
of the element with its location using linear search mechanism
Coding:
def lsearch(l,x):
count=0
for i in range(0,len(l)):if
l[i]==x:
print("Found at location:",i)
count+=1
print("\n frequency of element:",count)

a=eval(input("Enter a list:"))
b=eval(input("Enter the element to be searched:"))lsearch(a,b)

Output:

Enter a list:[1,2,3,1,4,5,6,5]
Enter the element to be searched:1
Found at location: 0
Found at location: 3

frequency of element: 2
Result:
The program is executed and the output is verified.
Program : 2
List traversal
Question:
Write a python program to pass a list to a function to double the odd valuesand half
the even values stored in it.
Aim:
To write a python program to pass a list to a function to double the oddvalues and
half the even values stored in it.
Coding:
def double_half(l):
for i in range(0,len(l)):if
l[i]%2!=0:
l[i]*=2
else:
l[i]/=2
print("Updated list is:",l)
a=eval(input("Enter the list:"))
double_half(a)

Output:
Enter the list:[10,11,12,13,14,15] Updated
list is: [5.0, 22, 6.0, 26, 7.0, 30]
Result:
The program is executed and the output is verified.
Program : 3
Updating a dictionary

Question:
Write a python program to update the value of a dictionary. Obtain thekey
from the user to update the value.
Aim:
To write a python program to input the key and update its value stored in a
dictionary
Coding:
def modify(d,k): value2=eval(input("Enter
the value:"))d[k]=value2
print("Updated dictionary:",d)

x=int(input("Enter the number of pairs in dictionary:"))dic={ }


for i in range(x): key=eval(input("Enter
the key:"))
value=eval(input("Enter the value:"))
dic[key]=value
print("original dictionary is:",dic)
a=eval(input("Enter the key whose value you want to change:"))modify(dic,a)

Output:
Enter the number of pairs in dictionary:3
Enter the key:"NAME"
Enter the value:"RAMESH"
Enter the key:"AGE"
Enter the value:16
Enter the key:"DESIGNATION"
Enter the value:"Grade 12"
original dictionary is: {'NAME': 'RAMESH', 'AGE': 16, 'DESIGNATION': 'Grade 12'}
Enter the key whose value you want to change:"AGE "Enter the
value:18
Updated dictionary: {'NAME': 'RAMESH', 'AGE': 18, 'DESIGNATION': 'Grade 12'}

Result:
The program is executed and the output is verified.
Program : 4
Printing Factorial value
Question:

Write a python program to print the factorial value of the given number.
Aim:

To write a python program to print the factorial value of the given number.
Coding:
def fact(num):
fact = 1
n = num # storing num in n for printing
while num>1: # loop to iterate from n to 2
fact = fact * num
num-=1
print("Factorial of ", n , " is :",fact)

print("Printing Factorial Value")


print("************************")
number = int(input("Enter any number :"))
fact(number)
Output:
Printing Factorial Value
************************
Enter any number :5
Factorial of 5 is : 120

Result:
The program is executed and the output is verified.
Program : 5
Checking Prime number
Question:
Write a python program to check whether the given number is prime or not.
Aim:
To write a python program to check whether the given number is prime ornot.

Coding:

import math print("Prime


or not")
print("************\n")
num = int(input("Enter any number :"))
isPrime=True

for i in range(2,int(math.sqrt(num))+1):if
num % i == 0:
isPrime=Falseif
isPrime:
print("## Number is Prime ##\n")
else:
print("## Number is not Prime ##\n")

Output:
Prime or not
************
Enter any number :10
## Number is not Prime ##

Prime or not
************
Enter any number :3 ##
Number is Prime ##
Result:
The program is executed and the output is verified.
Program 6:
Program to search any word in given string/ sentence .

Question :
Write a python program to read a sentence and print the number of timesthe
given word presents in the sentence.
Aim:
To write a python program to read a sentence and print the number oftimes the
given word presents in the sentence.

Coding:

print("Program to find the occurrence of any word in a string")


print("******************************************************")
def countWord(str1,word):s =
str1.split()
count=0 for
w in s:
if w==word:
count+=1
return count
str1 = input("Enter any sentence :")
word = input("Enter word to search in sentence :")count =
countWord(str1,word)
if count==0:
print("## Sorry! ",word," not present ")else:
print("## ",word," occurs ",count," times ## ")

Output:

Program to find the occurrence of any word in a string


****************************************************** Enter any
sentence :computer is my favourite subjectEnter word to
search in sentence :my
## my occurs 1 times ##

Result:
The program is executed and the output is verified.
Program: 7
Program to take 10 sample phishing email, and find the mostcommon word
occurring

Question:
Write a python program to take 10 sample phishing emails, and findthe most
common word occurring.

Aim:
To Write a python program to take 10 sample phishing emails, andfind the most
common word occurring.

Coding:

#Program to take 10 sample phishing mail #and


count the most commonly occuring word
phishingemail= [ "[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
"[email protected]"
"[email protected]"
"[email protected]"
"[email protected]" ]

myd={}
for e in phishingemail:
x=e.split('@')
for w in x:
if w not in myd:
myd[w]=1
else:
myd[w]+=1
key_max = max(myd,key=myd.get)
print("Most Common Occurring word is :",key_max)

Output:
Most Common occurring word is : mymoney.com
Result:
The program is executed and the output is verified.
Program : 8
Program to read and display the number of vowel letters present in a text
file.

Question:
Write a python Program to read a text file and display the number ofvowel letters
present in it.

Aim:
To write a python Program to read a text file and display the numberof vowel
letters present in it.
Coding:

def WRITE():
f=open("Sample.txt",'w')
a=['HELLO WORLD',' I LOVE COMPUTER SCIENCE']
f.writelines(a)
f.close()

def READ():
vowels=['a','e','i','o','u']
count=0
f=open("Sample.txt",'r')
b=f.read()
for x in b :
if x.lower() in vowels:
count+=1
print("Number of vowel letters found:",count)f.close()

WRITE()
READ()

Output:
Number of vowel letters found: 12
Result:
The program is executed and the output is verified.
Program : 9
Generating random number
Question:
Write a python program that generates random numbers between the given range.
Aim:
To write a python program that generates random numbers between the given
range.
Coding:

def fun():
import random
lower=int(input("Enter the lower limit:"))
upper=int(input("Enter the upper limit:"))
num=random.randint(lower,upper) print("The
value generated is :", num)

fun()
Output:
Enter the lower limit:1000
Enter the upper limit:1500 The
value generated is : 1468
Result:
The program is executed and the output is verified.
Program : 10
Searching operation in Binary file.

Question :
Write a python Program to Store Student Roll Number, Name, Average in abinary
file and to display the student details whose average is more than 89.
Aim:
To To write a python Program to Store Student Roll Number, Name , Averagein
a binary file and to display the student details whose average is more than 89.

Coding:

Coding:
import pickle
def writedata( ): # To insert n number of data inside the file
f=open("newfile.dat","wb")
li=[]
opt='y'
while opt=='y':
rno=int(input("Enter the roll number:"))
name=input("ENter The Student Name:")
avg=float(input("Enter the average score:"))
li.append([rno,name,avg])
pickle.dump(li,f)
opt=input("press y if you want to add more records:")
f.close()

def search(): # to search and print the students details whose avergae is more than
89
f=open("newfile.dat","rb")
li2=[]
while True:
try:
li2=pickle.load(f)
except EOFError:
break
print("ROLL_NO\tNAME\tAVERGAE")
print("***********************")
for a in li2:
if a[2]>=89:
print(a[0],a[1],a[2], sep="\t")
f.close()
writedata()
search()

Output:

Enter the roll number:1


ENter The Student Name:Nitya
Enter the average score:90
press y if you want to add more records: y
Enter the roll number:2
ENter The Student Name:Reyan
Enter the average score:87
press y if you want to add more records: y
Enter the roll number:3
Enter The Student Name:Suriya
Enter the average score:93

press y if you want to add more records: n

ROLL_NO NAME AVERGAE


**********************************
1 Nitya 90.0
3 Suriya 93.0

Result:
The program is executed and the output is verified.

Program: 11
Copying the content of one text file into another text
file.
Question:
Write a python Program to read a text file and copying the lines starting with ‘T ‘
or ’t’ into another text file.

Aim:
To write a python Program to read a text file and copying the lines starting with
‘T ‘ or ’t’ into another text file.

Coding:
f=open("D:\source.txt",'r')
f1=open("D:\copy.txt",'w')
line=f.readlines()
for a in line:
if a[0]=='T' or line[0]=='t':
f1.write(a)
f.close()
f1.close()

f2=open("D:\copy.txt",'r')
print("The copied content is:")
content=f2.readlines()
for a in content:
print(a)
f2.close()
Note: Create a text file source.txt and store the below content beforeexecuting the
coding.
Content inside the file source.txt:
**************************************************
Once upon a time,
There was a king called Baratha
Who ruled India.
************************************************

Output:
The copied content is:
There was a king called Baratha

Result:
The program is executed and the output is verified.

Program : 12
Searching operation in a CSV file.
Question:
Write a python Program to create CSV file and store
empno,name,salary and search any empno and display name,salaryand if not
found appropriate message.
Aim:
To write a python Program to create CSV file and store empno,name,salary andsearch any empno
and display name,salary and if not found appropriate message.
Coding:
import csv
with open('myfile.csv',mode='a') as csvfile:
mywriter = csv.writer(csvfile,delimiter=',')
ans='y'
while ans.lower()=='y':
eno=int(input("Enter Employee Number "))
name=input("Enter Employee Name ")
salary=int(input("Enter Employee Salary :"))
mywriter.writerow([eno,name,salary])
print("## Data Saved... ##")
ans=input("Add More ?")
ans='y'
with open('myfile.csv',mode='r') as csvfile:
myreader = csv.reader(csvfile,delimiter=',')
while ans=='y':
found=False
e = int(input("Enter Employee Number to search :"))
for row in myreader:
if len(row)!=0:
if int(row[0])==e:
print("============================")
print("NAME :",row[1])
print("SALARY :",row[2])
found=True
break
if not found:
print("==========================")
print(" EMPNO NOT FOUND")
print("==========================")
ans = input("Search More ? (Y)")

Output:
Enter Employee Number 1
Enter Employee Name Subikshan
Enter Employee Salary :30000
## Data Saved... ##
Add More ?y
Enter Employee Number 2
Enter Employee Name Srinivas
Enter Employee Salary :28000
## Data Saved... ##
Add More ?y
Enter Employee Number 3
Enter Employee Name Sabari
Enter Employee Salary :31000
## Data Saved... ##
Add More ?n
Enter Employee Number to search :2
============================
NAME : Srinivas
SALARY : 28000
Result:
The program is executed and the output is verified.

Program : 13
Checking Palindrome string
Question:
Write a python program to check whether the given string is palindrome or
not.
Aim:
To write a python program to check whether the given string is palindrome ornot.
Coding:
print("Python Program to Check a Given String is Palindrome or Not")

string = input("Please enter your own String : ")

if(string == string[ : : - 1]):


print("This is a Palindrome String")
else:
print("This is Not a Palindrome String")

Output:
Python Program to Check a Given String is Palindrome or Not
Please enter your own String : malayalam
This is a Palindrome String

Python Program to Check a Given String is Palindrome or Not


Please enter your own String : hi
This is Not a Palindrome String
Result:
The program is executed and the output is verified.

Program :14
Counting the number of words present in a text file
Question:
Write a python program to read a text file and print the number ofwords
present in it.
Aim:
To write a python program to read a text file and print the number ofwords
present in it.
Coding:
def WRITE():
f=open("File.txt","w")
content=input("Enter the content( a sentence):")
f.write(content)
f.close()

def COUNTING():
count=0
f=open("File.txt","r")
a=f.read() b=a.split()
print("Total number of words present in the given file is:",len(b))f.close()

WRITE()
COUNTING()

Output:
Enter the content( a sentence):hi how are you
Total number of words present in the given file is: 4
Result:
The program is executed and the output is verified.

Program : 15 Binary Search Mechanism


Question:
Write a python program to implement binary search mechanism
Aim:
To write a python program to implement binary search mechanism
Coding:

def binary_search(arr,
x):low = 0
high = len(arr) - 1
mid = 0
while low <= high:
mid = (high + low) //
2 if arr[mid] < x:
low = mid + 1
elif arr[mid] > x:
high = mid - 1
else:
return mid
return -1

print("Binary Search")
arr =eval(input("Enter a list of numbers in ascending
order:")) x = int(input("Enter the number to be searched:"))
result = binary_search(arr,
x) if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")
Output:
Binary Search
Enter a list of numbers in ascending order:[20,35,68,99,105,200]
Enter the number to be searched:99
Element is present at index 3
Binary Search
Enter a list of numbers in ascending order:[20,35,68,99,105,200]
Enter the number to be searched:205
Element is not present in array
Result:
The program is executed and the output is verified

Program:16
Stack mechanism
Question:
Write a python program to implement stack mechanism
Aim:
To write a python program to implement stack mechanism
Coding:
def PUSH():
n=int(input("Enter the Number:"))
stack.append(n)
t=len(stack)-1def
POP():
if stack==[]:
print("Underflow")
else:
print("The deleted Number is :",stack.pop())
def DISPLAY():
if stack==[]:
print("Underflow")
else:
t=len(stack)-1
while t>=0:
print(stack[t]) t-=1

print("STACK MECHANISM")
stack=[]
t=len(stack)-1
ch='y'
while ch=='y':

print("MENU \n 1. PUSH \n 2. POP \n 3.DISPLAY \n 4.Exit \n")


opt=int(input("Enter your choice:"))
if opt==1:
PUSH()
elif opt==2:
POP()
elif opt==3:
DISPLAY()
else:
print("BYE!!!!") break
ch=input("press y to continue:")

Output:
STACK MECHANISM
MENU
1. PUSH
2. POP
3.DISPLAY
4.Exit

Enter your choice:1


Enter the Number:5
press y to continue:y
MENU
1. PUSH
2. POP
3.DISPLAY
4.Exit

Enter your choice:1


Enter the Number:10
press y to continue:y
MENU
1. PUSH
2. POP
3.DISPLAY
4.Exit

Enter your choice:3


10
5
press y to continue:y
MENU
1. PUSH
2. POP
3.DISPLAY
4.Exit

Enter your choice:2


The deleted Number is : 10
press y to continue:y MENU
1. PUSH
2. POP
3.DISPLAY
4.Exit

Enter your choice:3 5


press y to continue:y
MENU
1. PUSH
2. POP
3.DISPLAY
4.Exit

Enter your choice:4


BYE!!!!
>>>

Result:
The program is executed and the output is verified
Program : 17
Question : USING GLOBAL KEYWORD INSIDE A FUNCTION DEFINITION
Aim : To use global keyword in function
b=100
def function(x,y):
global b
b=b+100
print("Global variable value inside function:",b)
z=x+y
print("Global variable value before function call:",b)
function(10,20)
print("Global variable value after function call:",b)
Output:
Global variable value before function call: 100
Global variable value inside function : 200
Global variable value after function call:100
Result : The Outputs are verified successfully.
Program : 19
SQL
Question:
Create a table ‘STUDENT’ and execute the queries to fetch result for the given
questions.
Aim:
To create a “STUDENT” table to execute the SQL queries and fetch records for the
given questions.
Creating Database:
create database
student;use student;
Creating Table:
CREATE TABLE STUDENT(RNO INT, NAME CHAR(15),CLASS INT,SCORE FLOAT,RESULT
CHAR(5));
Inserting records:
INSERT INTO STUDENT
VALUES(101,'ARSHATH',12,78,'PASS'); INSERT INTO
STUDENT VALUES(102,'ADARSH',12,65,'PASS'); INSERT
INTO STUDENT VALUES(103,'BINEESH',12,31,'FAIL');
INSERT INTO STUDENT
VALUES(104,'DHARUN',12,50,'PASS'); INSERT INTO
STUDENT VALUES(105,'VIGNESH',12,26,'FAIL');

Questions:
1. Add a column named REMARKS and make its default
value as “NA”. Query: ALTER TABLE STUDENT ADD
REMARKS CHAR(25) DEFAULT 'NA'; Output:
SELECT * FROM STUDENT;

2. Update the remarks as “Essential repeat” where result is ‘fail’.


Query: UPDATE STUDENT SET REMARKS="ESSENTIAL REPEAT" WHERE RESULT ='FAIL';
Output:
SELECT * FROM STUDENT;

3. Display the Name and Roll Number of the students in descending order of Roll
number.
Query: SELECT RNO,NAME FROM STUDENT ORDER BY RNO DESC;
Output:

Program :18
Question : FINDING NUMBER OF UPPERCASE, LOWERCASE, DIGITS, SPACES AND SPECIAL
CHARACTERS IN A TEXT FILE
Aim : To find the number of uppercase, lowercase, digits, spaces and special characters in a text file.
with open("myfile.txt") as fo:
fc=fo.read()
u=l=d=s=sc=0
for i in fc:
if i.isupper():
u+=1
elif i.islower():
l+=1
elif i.isdigit():
d+=1
elif i==' ':
s+=1
else:
sc+=1
print("No of upper case",u,)
print("No of lower case",l)
print("No of digit case",d)
print("No of space case",s)
print("No of special case",sc)
Result : The Outputs are verified successfully.
4. Write a query to display the number of students got pass and fail marks.
Query: SELECT RESULT, COUNT(*) FROM STUDENT GROUP BY RESULT;
Output:

5. Write a query to delete the record of Roll Number 102.


Query: DELETE FROM STUDENT WHERE RNO=102;
Output:
SELECT * FROM STUDENT;

Result:
The SQL queries were executed and fetched the records successfully.

Program : 20
SQL
Question:
Create the tables ‘PRODUCT’, ‘MANUFACTURER’ and execute the queries to fetch result for the given
questions.
Aim:
To create the tables ‘PRODUCT’, ‘MANUFACTURER’ to execute the SQL queries and fetch records
for the given questions.
Creating database:
create database product;
Creating tables:
CREATE TABLE PRODUCT(PID INT PRIMARY KEY,PNAME CHAR(25),QTY INT,PRICE INT CHECK(PRICE>0));
CREATE TABLE MANUFACTURER(PID INT,COMPANY CHAR(30));
Inserting records:
Table: PRODUCT
INSERT INTO PRODUCT VALUES(101,'KEYBOARD',15,2000);
INSERT INTO PRODUCT VALUES(103,'MOUSE',20,500);
INSERT INTO PRODUCT VALUES(102,'MOTHERBOARD',16,18000);
INSERT INTO PRODUCT VALUES(105,'MODEM',5,8000);
INSERT INTO PRODUCT VALUES(104,'MONITOR',20,14000);
Table: MANUFACTURE
INSERT INTO MANUFACTURER VALUES(101,'LG');
INSERT INTO MANUFACTURER VALUES(102,'IBM');
INSERT INTO MANUFACTURER VALUES(103,'DELL');
INSERT INTO MANUFACTURER VALUES(104,'LENOVO');
INSERT INTO MANUFACTURER VALUES(105,'FIJUTSU');

Questions:

1. Write a query to add a column name “EMAIL” and set its default value as “NOT AVAILABLE”.
Query: ALTER TABLE MANUFACTURER ADD EMAIL VARCHAR(30) DEFAULT 'NOT AVAILABLE';
Output:

2. Write a Query to update the Quantity of MODEM as 10.


Query: UPDATE PRODUCT SET QTY=10 WHERE PNAME='MODEM';
Output:

3. Write a query to display the company names in ascending order.


Query: SELECT COMPANY FROM MANUFACTURER ORDER BY COMPANY ;
Output:

4. Write a query to display the minimum and maximum prices of products.


Query & Output:
5. Write a query to display the Product name and Company name from the tables PRODUCT and
MANUFACTURER.
Query & Output:

Result:
The SQL queries were executed and fetched the records successfully.

Program:21
SQL
Question:
Create a table “TEACHER” and write queries to fetch records fort the given questions.
Aim:
To create a table “TEACHER” to execute the SQL queries and fetch records for the given questions
Creating database:
CREATE DATABASE TEACHER;
USE TEACHER
Creating tables:
CREATE TABLE TEACHER(TID INT, TNAME CHAR(20),SUBJECT CHAR(20),DESIGNATION CHAR(20));
CREATE TABLE DETAILS(TID INT,DOJ DATE,SALARY INT);
Inserting records:
TABLE: TEACHER
INSERT INTO TEACHER VALUES(2001,'ISWARYA','BIOLOGY','PGT');
INSERT INTO TEACHER VALUES(2005,'ANAND','CHEMISTRY','PGT');
INSERT INTO TEACHER VALUES(1007,'SREEMATHI','ECONOMICS','PGT');
INSERT INTO TEACHER VALUES(1009,'MAHATHI','ENGLISH','TGT');
INSERT INTO TEACHER VALUES(2045,'VAISHNAVI','HINDI','PRT');
TABLE:DETAILS

INSERT INTO DETAILS VALUES(2001,'1999-05-18',65000);


INSERT INTO DETAILS VALUES(2005,'2005-06-05',58000);
INSERT INTO DETAILS VALUES(1007,'2010-3-04',46000);
INSERT INTO DETAILS VALUES(1009,'2019-09-06',29000);
INSERT INTO DETAILS VALUES(2045,'2016-04-03',31000);

Questions:

1. Write a query to remove the salary column from the table details.
Query & Output:
ALTER TABLE DETAILS DROP COLUMN SALARY;
2. Write a query to display the name of the teacher with corresponding data of joining.

3. Write a query to display the Teachers Name and DOJ in ascending order of DOJ.

4. Write a query to display the number of Teachers in designation wise.

5. Write a query to display the name of the Teachers whose starting with the letter ‘M’.

Result:
The SQL queries were executed and fetched the records successfully.
Program : 22 SQL
Question: Create the below given tables and experiment the SQL queries to fetch records for the given
questions.
TABLE: STORE

TABLE: SUPPLIERS

Aim: To create the given tables and experiment SQL queries to fetch the records
Creating database:
CREATE DATABASE STORE;
USE STORE;
Creating tables:
Table STORE:
CREATE TABLE STORE(ITMNO INT,ITEM CHAR(25),SCODE INT,QTY INT,RATE FLOAT,LASTBUY DATE);
Inserting Records:

INSERT INTO STORE VALUES(2003,"BALLS",22,50,25,'2010-02-01');


INSERT INTO STORE VALUES(2002,"GEL PEN PREMIUM",21,150,12,'2010-02-24');
INSERT INTO STORE VALUES(2001,"EARSER SMALL",22,220,6,'2009-01-19');
INSERT INTO STORE VALUES(2009,"BALL PEN",21,180,18,'2009-11-03');
INSERT INTO STORE VALUES(2005,"SHARPENER CLASIC",23,60,8,'2009-06-30');
Table :SUPPLIERS
CREATE TABLE SUPPLIERS(SCODE INT,SNAME CHAR(25));
Inserting records:
INSERT INTO SUPPLIERS VALUES(21,'PREMIUM STATIONERS');
INSERT INTO SUPPLIERS VALUES(23,'SOFT PLASTICS');
INSERT INTO SUPPLIERS VALUES(22,'TERA SUPPLY');
Questions:
1. Write a query to display details of all the items in the STORE table in
ascending order of LastBuy.

2. Display ItemNo and Item name of those items from STORE table,whose
Rate is more than Rs 15.
3. Display the details of those items whose Supplier code(Scode) is 22 orQuantity
in store(Qty) is more than 110 from the table STORE.

4. Display minimum rate of items for each Supplier individually as perScode


from the table STORE.

5. Display the Item Name and Supplier Name with their corresponding SCODE.

Result:
The SQL queries were executed and fetched the records successfully.

Program:23 SQL
Question:

Create the below given table and experiment SQL queries to fetch records for the given questionsTABLE:
HOSPITAL
No Name Age Description Dateofadm Charges Gender
1 Sandeep 65 Surgery 23/02/98 300 M
2 Ravina 24 Orthopedic 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 Ketaki 16 ENT 24/02/98 300 F
7 Ankita 29 Cardiology 20/02/98 800 F
Aim: to create the given table and pass SQL queries to fetch records for the given questions
Creating database:
CREATE DATABASE HOSP;
USE HOSP;
Creating table:
CREATE TABLE HOSPITAL(NO INT,NAME CHAR(25),AGE INT,DESCRIPTION CHAR(25),DATEOFADMIN
DATE,CHARGES FLOAT,GENDER CHAR(10));

Inserting records:
INSERT INTO HOSPITAL VALUES(1,'SANDEEP',65,'SURGERY','1998-02-23',300,'M');
INSERT INTO HOSPITAL VALUES(2,'RAVINA',24,'ORTHOPEDIC','1998-01-20',200,'F');
INSERT INTO HOSPITAL VALUES(3,'KARAN',45,'ORTHOPEDIC','1998-02-19',200,'M');
INSERT INTO HOSPITAL VALUES(4,'TARUN',12,'SURGERY','1998-01-1',300,'M');
INSERT INTO HOSPITAL VALUES(5,'ZUBIN',36,'ENT','1998-01-12',250,'M');
INSERT INTO HOSPITAL VALUES(6,'KETAKI',16,'ENT','1998-02-24',300,'F');
INSERT INTO HOSPITAL VALUES(7,'ANKITA',29,'CARDIOLOGY','1998-02-28',800,'F');
Questions:
1. Display all information about the patients of Cardiology Department.

2. Display Patient's Name, Charge, Age for male patients only.

3. Display the name of the patients aged above 20.

4. Display the average charge.

5. Display the number of male and female patients.


Result:
The SQL queries were executed and fetched the records successfully.
24. Python –My Sql connectivity

Aim:

To create a table “ employee” and retrieve the records through Python-My Sql
connectivity for the below Questions.

i. To display the total salary of sales department.


ii. To display the record in descending order of employee number.
iii. To display the department wise count.
iv. To calculate 15% bonus for all employees.

Coding:

import mysql.connector as mycon


con = mycon.connect(host='localhost',user='root',password='root',database='sys')
cur = con.cursor()

cur.execute("create table if not exists employee(empno int, name varchar(20), dept


varchar(20),salary int)")
con.commit()

choice='y'
while choice=='y':
e = int(input("Enter Employee Number”)
n = input("Enter Name :")
d = input("Enter Departmen")
s = int(input("Enter Salary :"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
cur.execute(query)
con.commit()
print("## Data Saved ##")
choice=input("Press y if you want to add more records:")
print("*********************************************************")

print("To display the total salary of sales department\n")


query="select sum(salary) from employee where dept='sales'"
print("\t TOTAL SALARY OF SALES DEPARTMENT")
cur.execute(query)
result =
cur.fetchall()
print(result)
print("******************************************************")
print("\n\n Displaying the records in descending order of Employee Number:\n")
query="select * from employee order by empno desc"
cur.execute(query)
result =
cur.fetchall()
print("EMPNO NAME DEPARTMENT SALARY")
for row in
result:
print(row)
print("****************************************************")

print("\n\n Displaying department wise count")


query="select dept,count(*) from employee group by dept"
cur.execute(query)
result=cur.fetchall()
print("\nDEPARTMENT , COUNT
\n") for row in result:
print(row)
print("***************************************************")

print("\n\n Calculating 15 % Bonus:\n")


query="select name, salary*0.15 from
employee"cur.execute(query)
result=cur.fetchall()
print("\n NAME \t
BONUS\n") for row in result:
print(row)
print("***********************************************")

Output:

Enter Employee Number


:101 Enter Name
:Subhikshan Enter
Department :manager Enter
Salary :67000
## Data Saved ##
Press y if you want to add more records:y
Enter Employee Number :104
Enter Name :Tharanees
Enter Department
:auditing Enter Salary
:56000
## Data Saved ##
Press y if you want to add more records:y
Enter Employee Number :102
Enter Name :Aakash
Enter Department
:sales Enter Salary
:30000
## Data Saved ##
Press y if you want to add more records:y
Enter Employee Number :103
Enter Name :Mathan
Enter Department
:clerical Enter Salary
:23000
## Data Saved ##
Press y if you want to add more
records:yEnter Employee Number :105
Enter Name :Sree
Enter Department
:sales Enter Salary
:21500
## Data Saved ##
Press y if you want to add more records:n
***********************************************************
To display the total salary of sales department

TOTAL SALARY OF SALES


DEPARTMENT [(Decimal('51500'),)]
******************************************************

Displaying the records in descending order of Employee Number:

EMPNO NAME DEPARTMENT SALARY


(105, 'Sree', 'sales', 21500)
(104, 'Tharanees', 'auditing', 56000)
(103, 'Mathan', 'clerical', 23000)
(102, 'Aakash', 'sales', 30000)
(101, 'Subhikshan', 'manager', 67000)
****************************************************

Displaying department wise count

DEPARTMENT , COUNT

('manager', 1)
('auditing', 1)
('sales', 2)
('clerical', 1)
***************************************************

Calculating 15 % Bonus:

NAME BONUS

('Subhikshan', Decimal('10050.00'))
('Tharanees', Decimal('8400.00'))
('Aakash', Decimal('4500.00'))
('Mathan', Decimal('3450.00'))
('Sree', Decimal('3225.00'))
***********************************************
>>>

Result:

The program is executed successfully and the output is verified.


25. Python –My Sql connectivity

Aim:

To create a table “student” and retrieve the records through Python-My Sql
connectivity for the below questions.

i. To display the Details of the Students who scored above 85.


ii. To Display the Average score.
iii. To Display the Number of Students Got Pass / fail marks.
iv. To Display the Maximum and Minimum Score.

Coding:

import mysql.connector as mycon


con = mycon.connect(host='localhost',user='root',password='root',database='sys')
cur = con.cursor()

cur.execute("create table if not exists student(rno int, name varchar(20), score


int,result char(6))")
con.commit(
)choice='y'
while choice=='y':
r = int(input("Enter Roll Number
:")) n = input("Enter Name :")
s = input("Enter the Score :")
res = input("Enter Result Pass / Fail:")
query="insert into student values({},'{}',{},'{}')".format(r,n,s,res)
cur.execute(query)
con.commit()
print("## Data Saved ##")
choice=input("Press y if you want to add more records:")
print("***********************************************************")

print("To display the Details of the Students who scored above


85.\n") query="select * from student where score>85"
print("ROLL_NO NAME SCORE RESULT")
cur.execute(query)
result =
cur.fetchall() for row
in result:
print(row)
print("****************************************************
**")

print("Displaying the Names in descending order \n")


query="select name from student order by name desc"
cur.execute(query)
result = cur.fetchall()
print("NAME ")
for row in result:
print(row)
print("*********************************************************
”)
print(" Displaying the Number of Students Got Pass / fail marks:")
query="select result,count(*) from student group by result"
cur.execute(query)
result = cur.fetchall()
print("PASS / FAIL
COUNT")
for row in
result:
print(row)
print("*********************************************************")

print(" Displaying the Maximum and Minimum


Score") query="select max(score),min(score) from
student" cur.execute(query)
result =
cur.fetchall()print("
MAX MIN")
print(result)
print("*********************************************************

")

Output:

Enter Roll Number


:1001 Enter Name
:shruthi Enter the Score
:89
Enter Result Pass /
Fail:pass ## Data Saved ##
Press y if you want to add more records:y
Enter Roll Number :1002
Enter Name
:Mahath Enter the
Score :32
Enter Result Pass /
Fail:fail ## Data Saved ##
Press y if you want to add more records:y
Enter Roll Number :1003
Enter Name
:Suresh Enter the
Score :78
Enter Result Pass /
Fail:pass ## Data Saved ##
Press y if you want to add more records:y
Enter Roll Number :1004
Enter Name
:Diana Enter the
Score :15
Enter Result Pass /
Fail:fail ## Data Saved ##
Press y if you want to add more records:y
Enter Roll Number :1005
Enter Name
:Mahesh
Enter the Score :92
Enter Result Pass /
Fail:pass ## Data Saved ##
Press y if you want to add more records:n

***********************************************************

To display the Details of the Students who scored above 85.

ROLL_NO NAME SCORE RESULT


(1001, 'shruthi', 89, 'pass')
(1005, 'Mahesh', 92, 'pass')
******************************************************
Displaying the Average score:
AVERAE SCORE
[(Decimal('61.2000'),)]
*********************************************************
Displaying the Number of Students Got Pass / fail marks:
PASS / FAIL COUNT
('pass', 3)
('fail', 2)
*****************************************************
**** Displaying the Maximum and Minimum
Score MAX MIN
[(92, 15)]
*********************************************************

Result:

The program is executed successfully and the output is verified.

You might also like