Practical File (Xii - Ip) 2023-24
Practical File (Xii - Ip) 2023-24
4 JAIPUR
SESSION : 2023-24
CLASS - XII
INFORMATICS PRACTICES
(PYTHON / MYSQL)
INDEX
Sl. Date Program Page No. Grade/ Sign. Of
No. (From - To) Remarks Teacher
1 Calculating the cube of the series
elements.
2 Series – cube calculation and display
of result based on condition.
3 Updation in Series data
4 Display of attributes of Series
5 Add and display of data in/from
dataframe
6 Creation of dataframe by list of
dictionaries and display of its attributes.
7 Performing arithmetic operations on
dataframe
8 Display of top 2 and bottom 2 achivers
from dataframe
9 Accessing data from dataframe
10 Add, update, remove data from
datafram Covid_df
11 Creation of line chart
12 Plotting Bar chart
13 Plotting of a graph for the function
y = 𝒙𝟐
14 Creation of multiple line charts on
common plot
15 Creation of an array in the range 1 to 20
with values 1.25 apart. Another array
containing the log values of the
elements stored in first array.
Then plotting of different graphs.
16 Creation of histogram
17 Fetching data from mysql table EMP for
a Job type entered by user
18 Fetching data from mysql table EMP
and group by a particular column
19 Shop application to search mobile in
database by brand or Price range.
20 Database operation to add , modify,
update, display records from emp table.
21 SQL queries – 20 Nos.
LAB ACTIVITY 1
Write a program in python to calculate the cube of the series values as
given below-
2,5,7,4,9
Code :
OUTPUT
Original Series data
0 2
1 5
2 7
3 4
4 9
dtype: int64
Cube of Series data
0 8
1 125
2 343
3 64
4 729
dtype: int64
LAB ACTIVITY 2
Write a program in python to create a series Ser1 of numeric data with labels as
a,b,c,d,e. Then create a new series object Ser2, contains squares of each values
from Ser1. Display Ser2 values which are greater than 15.
Code :
OUTPUT
PROGRAM
import pandas as pd
import numpy as np
PROGRAM
import pandas as pd OUTPUT
import numpy as np
Color Count Price
Orange
Yellow 30 40
dict = {'Color':['Yellow','Green','Yellow','Green','Green'], OrangeGreen 19 30
'Count':[30,19,25,29,65], MangoYellow 25 60
'Price':[40,30,60,120,150]} Mango Green 29 120
Pear Green 65 150
fruits=pd.DataFrame(dict, index=['Orange','Orange','Mango','Mango','Pear'])
Color Count Price Variety
print(fruits) Orange Yellow 30 40 Normal
Orange Green 19 30 Normal
Mango Yellow 25 60 Dashari
#Adding a new column Variety
Mango Green 29 120 Hafooj
fruits['Variety']=['Normal', 'Normal', 'Dashari', 'Hafooj', 'Normal'] Pear Green 65 150 Normal
print(fruits) Color Count Price Variety
Orange Yellow 30 40 Normal
Orange Green 19 30 Normal
#Adding a new row Apple Mango Yellow 25 60 Dashari
fruits.loc['Apple']=['Red',40,190,'Kashmiri'] Mango Green 29 120 Hafooj
print(fruits) Pear Green 65 150 Normal
Apple Red 40 190 Kashmiri
Orange 40
#Display price of all fruits Orange 30
print(fruits['Price']) Mango 60
Mango 120
Pear 150
#Display color and price of all fruits Apple 190
print(fruits[['Color','Price']]) Name: Price, dtype: int64
Color Price
Orange Yellow 40
#Display count to variety all columns Orange Green 30
print(fruits.loc[:,'Count':'Variety']) #fruits.iloc[ : , 1:4]) Mango Yellow 60
Mango Green 120
Pear Green 150
Apple Red 190
Count Price Variety
Orange 30 40 Normal
Orange 19 30 Normal
Mango 25 60 Dashari
Mango 29 120 Hafooj
Pear 65 150 Normal
Apple 40 190 Kashmiri
LAB ACTIVITY 6
Consider the following data and write python code for points (i) to (v)
Color Count Price
Orange Yellow 30 40
Orange Green 19 30
Mango Yellow 25 60
Mango Green 29 120
Pear Green 65 150
(i) Write code to create a dataframe fruits using list of dictionaries.
(ii) Write code to display following attributes of dataframe-
Index, Columns, axes, datatype, no. of elements, dimensions, data in numpy, check
empty dataframe, no. of axes, transpose
PROGRAM
import pandas as pd
import numpy as np
fruits=pd.DataFrame(dict, index=['Orange','Orange','Mango','Mango','Pear'])
print(fruits)
PROGRAM
import pandas as pd
import numpy as np
#Creation of dataframe df1
df1 = pd.DataFrame([[3,4,5],[2,7,np.NaN],[3,2,1]])
print("df1\n",df1)
#Creation of dataframe df2
df2 = pd.DataFrame([[2,8,3],[np.NaN,5,5],[np.NaN,np.NaN,2]])
print("df2\n",df2)
#Scaler arithmetic’s
df7=df1 + 10
print("df1 + 10\n",df7)
OUTPUT
df1
0 1 2
0 3 4 5.0
1 2 7 NaN
2 3 2 1.0
df2
0 1 2
0 2.0 8.0 3
1 NaN 5.0 5
2 NaN NaN 2
df1+df2
0 1 2
0 5.0 12.0 8.0
1 NaN 12.0 NaN
2 NaN NaN 3.0
df1 - df2
0 1 2
0 1.0 -4.0 2.0
1 NaN 2.0 NaN
2 NaN NaN -1.0
df1 X df2
0 1 2
0 6.0 32.0 15.0
1 NaN 35.0 NaN
2 NaN NaN 2.0
df1/df2
0 1 2
0 1.5 0.5 1.666667
1 NaN 1.4 NaN
2 NaN NaN 0.500000
df1 + 10
0 1 2
0 13 14 15.0
1 12 17 NaN
2 13 12 11.0
LAB ACTIVITY 8
Consider the following data frame of classes –
Class Name Subject gradeA Year
1 I Vinita EVS 24 2020
2 II Harish English 26 2020
3 III Amit Maths 20 2020
4 IV Deepak Hindi 21 2020
5 V Anil GK 29 2020
Write code to display the details of teacher(s), having highest number of gradeA students and lowest
number of gradeA students. (2 from top and 2 from bottom)
PROGRAM
import pandas as pd
# Creation of dictionary for given data
dict = {'Class':['I','II','III','IV','V'],
'Name':['Vinita','Harish','Amit','Deepak','Anil'],
'Subject':['EVS','English','Maths','Hindi','GK'],
'gradeA':[24,26,20,21,29],
'Year':[2020,2020,2020,2020,2020]}
#Creation of DataFrame
DfRecord = pd.DataFrame(dict, index=[1,2,3,4,5])
print("Original Dataframe")
print(DfRecord)
PROGRAM
import pandas as pd
#(vii) Find all rows with label ‘SDMH’ with all columns.
print("\n",Covid_df.loc['SDMH',:]) # Covid_df.loc['SDMH']
#(ix) List single True or False to signify if all amount more than 200000 or not.
print("\nChecking if all row contains amount greater than 200000 =
",(Covid_df['Amount']>200000).all())
#(xv) Display details of Masks and Gloves bought by AIIMS and SDMH
print("\n",Covid_df.loc[['AIIMS','SDMH'],['Masks','Gloves']])
OUTPUT
LAB ACTIVITY 10
Write a program to create a the following dataframe and answer the questions (i) to (v)-
Datafrme name : Covid_df
PROGRAM
PROGRAM
#Importing modules for matplotlib.pyplot
import matplotlib.pyplot as plt
x=[2,4,3,7,5]
y=[23,43,18,20,5]
plt.plot(x,y,color='r',linestyle='dashed',marker='+',markeredgecolor='b')
plt.xlabel("X")
plt.ylabel("Y")
plt.show()
OUTPUT
LAB ACTIVITY 12
Write a program to plot a bar chart in python to display the result of a school for five
consecutive years.
(a) Change the colour bars in sequence as red,yellow,green,blue,cyan
(b) Change width of bars in sequence as 0.5,0.6,0.7,0.8,0.9
PROGRAM
#Importing modules for matplotlib.pyplot
import matplotlib.pyplot as plt
Years=[2014,2015,2016,2017,2018]
PerResult=[91.0,89.7,84.2,98.9,94.3]
clr=['r','y','g','b','c']
wd=[0.5,0.6,0.7,0.8,0.9]
plt.bar(Years,PerResult,color=clr,width=wd)
plt.xlabel("Years")
plt.ylabel("Result in percentage")
plt.show()
OUTPUT
LAB ACTIVITY 13
PROGRAM
import matplotlib.pyplot as plt
x_cords = range(-50,50)
y_cords = [x*x for x in x_cords]
plt.plot(x_cords, y_cords)
plt.show()
OUTPUT
LAB ACTIVITY 14
Write a program to create multiple line charts on common plot where three data ranges are
plotted on the same chart.
The data ranges to be plotted are-
DATA = [[5.,42.,28.,18.],[9.,13.,22.,29.],[8.,32.,26.,40.]]
(i) Display legends as Range1,Range2 and Range3.
(ii) Display label on x and y axes as X and Y respectively.
(iii) Add title as “Multirange line chart”
PROGRAM
import numpy as np
import matplotlib.pyplot as plt
DATA = [[5.,42.,28.,18.],[9.,13.,22.,29.],[8.,32.,26.,40.]]
x=np.arange(4)
plt.plot(x,DATA[0],color='b',label='Range1')
plt.plot(x,DATA[1],color='y',label='Range2')
plt.plot(x,DATA[2],color='g',label='Range3')
plt.legend(loc='upper left')
plt.title("Multirange line chart")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()
OUTPUT
LAB ACTIVITY 15
Write a program to create an array in the range 1 to 20 with values 1.25 apart.
Another array containing the log values of the elements stored in first array.
(a) Create a plot of first vs second array; specify the x-axis (containing first array's values) title as
'Random Values' and y-axis title as 'Logarithm Values'
(b) Create a third array that stores the COS values of first array and then plot both the second and
third arrays vs first array. The COS values should be plotted with a dashdotted line.
(c) Change the marker type as a circle with the blue color in second array.
(d) Create a scatter chart as this : second array data points as blue small diamonds, third array data
points as black circle.
PROGRAM
import numpy as np
import matplotlib.pyplot as plt
a=np.arange(1,20,1.25)
b=np.log(a)
"""(a) Create a plot of first vs second array; specify the x-axis (containing first array's values) title as
'Random Values' and y-axis title as 'Logarithm Values'"""
plt.plot(a,b)
plt.xlabel('Random Values')
plt.ylabel('Logarithm values')
plt.show()
"""(b) Create a third array that stores the COS values of first array and then plot both the second and
third arrays vs first array. The COS values should be plotted with a dashdotted line."""
c=np.cos(a)
plt.plot(a,b)
plt.plot(a,c,linestyle='dashdot')
plt.show()
"""(c) Change the marker type as a circle with the blue color in second array."""
c=np.cos(a)
plt.plot(a,b)
plt.plot(a,c,'bo',linestyle='dashdot')
plt.show()
"""(d) Create a scatter chart as this : second array data points as blue small diamonds, third array data
points as black circle."""
c=np.cos(a)
plt.plot(a,b,'bd')
plt.plot(a,c,'ro')
plt.show()
OUTPUT
LAB ACTIVITY 16
Write a program to create the histogram for (a) to (g). The data is given below-
Weight measurements for 16 small orders of French Fries (in grams).
78 72 69 81 63 67 65 73
79 74 71 83 71 79 80 69
(a) Create a simple histogram from above data.
(b) Create a horizontal histogram from above data.
(c) Create a step type of histogram from above data.
(d) Create a cumulative histogram from above data.
PROGRAM
import numpy as np
import matplotlib.pyplot as plt
wff=np.array([78,72,69,81,63,67,65,75,79,74,71,83,71,79,80,69]) #weight of French fries
PROGRAM
try:
mydb = msc.connect(host = "localhost",
user = "root",
passwd = "mysql",
database = "test")
crs = mydb.cursor()
OUTPUT
LAB ACTIVITY 18
Write a program in python to count number of emloyees group by a perticular column entered
by user from mysql table emp stored in database test (given in emp.csv file in C: drive)
PROGRAM
import mysql.connector as msc
import pandas as pd
try:
mydb = msc.connect(host = "localhost",
user = "root",
passwd = "mysql",
database = "test")
crs = mydb.cursor()
PROGRAM
import os
import mysql.connector as msc
import pandas as pd
try:
mydb = msc.connect(host = "localhost",
user = "root",
passwd = "mysql",
database = "store")
crs = mydb.cursor()
k=1
while(k==1):
print("***************************************************************")
print("*******************MOBILE DATA MANAGEMENT**********************")
print("***************************************************************")
print("\nSEARCH MOBILE by\n1. By Brand Name\n2.By Price Limit\n3.Exit")
choice=int(input("Enter your choice = "))
if(choice==1):
os.system('cls')
brand=input("Enter Brand Name to search = ")
qry="select * from mobile where Mname= %s"
crs.execute(qry,(brand,))
data1 =crs.fetchall()
df = pd.DataFrame(data1, columns=["Mcode","Mname","Features","Year_manuf","Price"])
print(df)
elif(choice==2):
os.system('cls')
print("To Check by Price limits ")
min_price=input("Enter the Minimum price limit to buy =")
max_price=input("Enter the Maximum price limit to buy =")
qry="Select * from mobile where Price>= %s and Price<= %s"
crs.execute(qry,(min_price,max_price,))
data1 =crs.fetchall()
df = pd.DataFrame(data1, columns=["Mcode","Mname","Features","Year_manuf","Price"])
print(df)
elif(choice==3):
exit()
else:
os.system("ls")
print("Enter correct choice")
k=int(input("Press 1 to continue, press other key to exit "))
except mysql.connector.Error as error:
print("Database Error")
OUTPUT
LAB ACTIVITY 20
Write a program in python to perform the following operations on mysql table emp stored in
database test -
(a) Display data of all employee.
(b) Add new employee data in table emplyee.
(c) Update data of employee based on empployee ID entered by user.
(d) Remove the records of employee based on their employee ID entered by user.
(e) Exit the program.
PROGRAM
def display():
try:
mydb = msc.connect(host = "localhost",
user = "root",
passwd = "mysql",
database = "office")
crs = mydb.cursor()
print("Employees Data")
crs.execute("SELECT * FROM emp")
data1 =crs.fetchall()
df = pd.DataFrame(data1, columns=["Ecode","Ename","Designation","Salary"])
print(df)
crs.close()
except mysql.connector.Error as error:
print("Records not available")
def insert():
try:
mydb = msc.connect(host = "localhost",
user = "root",
passwd = "mysql",
database = "office")
crs = mydb.cursor()
print("Inserting in new data")
ecode=int(input("Enter a new employee code="))
ename=input("Enter a name of employee=")
desig=input("Enter designation=")
salary=int(input("Enter salary="))
qry="INSERT INTO emp VALUES(%s,%s,%s,%s)"
data=(ecode,ename,desig,salary)
crs.execute(qry,data)
mydb.commit()
print(crs.rowcount,"Records Inserted")
crs.close()
except mysql.connector.Error as error:
print("Failed to insert record in table emp")
def delete():
try:
mydb = msc.connect(host = "localhost",
user = "root",
passwd = "mysql",
database = "office")
crs = mydb.cursor()
nm=input("Enter name of employee to delete=")
qry="DELETE FROM emp WHERE ename LIKE %s"
crs.execute(qry,(nm,))
mydb.commit()
crs.close()
except mysql.connector.Error as error:
print("Failed to delete record from table emp")
def update():
try:
mydb = msc.connect(host = "localhost",
user = "root",
passwd = "mysql",
database = "office")
crs = mydb.cursor()
code=int(input("Enter employee code to update data="))
nm=input("Enter new name=")
desig=input("Enter new designation=")
sal=int(input("Enter salary="))
qry="UPDATE emp SET ename=%s, designation=%s, salary=%s Where ecode=%s"
data=(nm,desig,sal,code)
crs.execute(qry,data)
mydb.commit()
crs.close()
except mysql.connector.Error as error:
print("Failed to update records in table emp")
k=0
while(k!=5):
print("*************MENU**************")
print("1. Insert new record")
print("2. Delete records")
print("3. Update records")
print("4. Display all records")
print("5. Exit")
k=int(input("Enter your choice="))
if(k==1):
insert()
elif(k==2):
delete()
elif(k==3):
update()
elif(k==4):
display()
else:
exit
OUTPUT
MYSQL
Write Queries for the followings:-
1. Write a query to display all contents of table employee table.
Ans.
SELECT *
FROM emp;
--------------------------------------------------------------------------------------------------------------------------------
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
----- ---------- --------- ---------- --------- ---------- ---------- ---------- -------------------------------------------------
7369 SMITH CLERK 7902 17-DEC-1980 800 NULL 20
7499 ALLEN SALESMAN 7698 20-FEB-1981 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-1981 1250 500 30
7566 JONES MANAGER 7839 02-APR-1981 2975 NULL 20
7654 MARTIN SALESMAN 7698 28-SEP-1981 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-1981 2850 NULL 30
7782 CLARK MANAGER 7839 09-JUN-1981 2450 NULL 10
7788 SCOTT ANALYST 7566 19-APR-1987 3000 NULL 20
7839 KING PRESIDENT 17-NOV-1981 5000 NULL 10
7844 TURNER SALESMAN 7698 08-SEP-1981 1500 700 30
7876 ADAMS CLERK 7788 23-MAY-1987 1100 NULL 20
7900 JAMES CLERK 7698 03-DEC-1981 950 NULL 30
7902 FORD ANALYST 7566 03-DEC-1981 3000 NULL 20
7934 MILLER CLERK 7782 23-JAN-1982 1300 NULL 10
---------------------------------------------------------------------------------------------------------------------------------
2. Write a query to display different jobs from employee table.
Ans.
SELECT distinct(job)
FROM emp;
JOB
---------
ANALYST
CLERK
MANAGER
PRESIDENT
SALESMAN
3. Write a query to display the empname who is earning more than 2500.
Ans.
SELECT ename
FROM emp
WHERE sal>2500;
ENAME
----------
JONES
BLAKE
SCOTT
KING
FORD
4. Write a query to display the managers working in department number 10.
Ans.
SELECT ename
FROM emp
WHERE JOB=”MANAGER” and deptno=10;
ENAME
---------
CLARK
ENAME
----------
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER
6. Write a query to display the managers who earn more than 2800.
Ans.
SELECT ename,job
FROM emp
WHERE job='MANAGER' AND sal>2800;
ENAME JOB
---------- ---------
JONES MANAGER
BLAKE MANAGER
7. Write a query to display the department number where more than three employees are
working.
Ans.
SELECT deptno
FROM emp
GROUP BY deptno
HAVING count(*)>3;
DEPTNO
--------
20
30
8. Write a query to display the name of employee with their salary in order of their joining.
Ans.
SELECT ename,sal
FROM emp
ORDER BY hiredate;
ENAME SAL
---------- ----------
SMITH 800
ALLEN 1600
WARD 1250
JONES 2975
BLAKE 2850
CLARK 2450
TURNER 1500
MARTIN 1250
KING 5000
JAMES 950
FORD 3000
MILLER 1300
SCOTT 3000
ADAMS 1100
9. Write a query to display the name and salary from department number 30 and sorted in
descending order of salary.
Ans.
SELECT ename,sal
FROM emp
WHERE deptno=30
ORDER BY sal DESC;
ENAME SAL
---------- ----------
BLAKE 2850
ALLEN 1600
TURNER 1500
MARTIN 1250
WARD 1250
JAMES 950
SELECT deptno,max(sal)
FROM emp
GROUP BY deptno;
DEPTNO MAX(SAL)
------ ----------
10 5000
20 3000
30 2850
11. Write a SQL command to increase the salary by 300 to the employees belong to deptno 20.
Ans.
UPDATE emp
SET sal=sal+300
WHERE deptno=20;
5 rows updated.
DEPTNO NOOFEMP
------ ----------
10 3
20 5
30 6
Ans.
INSERT INTO emp
VALUES (8000,'DEVESH','CLERK',7200,'01-JAN-2011',3500,0,10);
14. Write a query to display the employee name earning between 1500 and 2500.
Ans.
Method-1
SELECT ename
FROM emp
WHERE sal>=1500 AND sal<=2500;
Method-2
SELECT ename
FROM emp
WHERE sal BETWEEN (1500 and 2500);
ENAME
---------
ALLEN
CLARK
TURNER
15. Write a query to display the employee name joined in the year 1981.
Method-1
SELECT ename
FROM emp
WHERE hiredate>='01-JAN-1981' AND hiredate<='31-DEC-1981';
Method-2
SELECT ename
FROM emp
WHERE hiredate between ("01-JAN-1981" and "31-DEC-1981");
Method-3
SELECT ename
FROM emp
WHERE year(hiredate)="1981";
ENAME
--------
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
KING
TURNER
JAMES
FORD
16. Write a query to display details of employees working in any department out of 10 and 20.
Method-1
SELECT *
FROM emp
WHERE deptno =10 OR deptno=20;
Method-2
SELECT *
FROM emp
WHERE deptno IN (10,20);
SELECT *
FROM emp
WHERE comm IS NOT NULL;
--------------------------------------------------------------------------------------------------------------------------------
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
----- ---------- --------- ---------- --------- ---------- ---------- ---------- -------------------------------------------------
7499 ALLEN SALESMAN 7698 20-FEB-1981 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-1981 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-1981 1250 1400 30
7844 TURNER SALESMAN 7698 08-SEP-1981 1500 700 30
--------------------------------------------------------------------------------------------------------------------------------
18. Write a query to see average salary paid to department number 20.
SELECT AVG(sal)
FROM emp
WHERE depno=20;
AVG(sal)
------------
2175
19. Write a query to delete the records of employees working as analyst and working in department number
20.
02records deleted