You are on page 1of 35

Kendriya Vidyalaya, EOI

Kathmandu

PRACTICAL RECORD
Acade AISSCE(XII) mic
Year- 2023- 24
Subject - Informatics Practices
Sub Code – 065

Submitted by: Under the guidance


of:

Roll No – Mr. A. P. S. Kushwah


Name:
Contact No.
INDEX

Sl. Date of Program Page No. Grade/ Date of Sign. Of


No. exp (From - To) Remarks submissio Teacher
n
1 Student grade evaluation

2 Tax calculation based on annual


salary
3 Factorial Number
4 Calculation of wages for employee
5 Prime Number
6 Operation on Dataframe
7 Grouping of data in dataframe
8 Display of data from dataframe for
Online tutorial company
9 Display of data from numpy array

10 Extraction of subset from ndarray A1


containing elements,
whose cube is fully divisible by 9.
11 Creation of line chart
12 Plotting Bar chart
13 Plotting of a graph for the function
y = x2
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 in first array.
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.
LAB ACTIVITY 1
Write a program to calculate grade from percentage marks obtained by students.
Percentage Marks Grade
>=90 A
75<=Percentage Marks<90 B
60<=Percentage Marks<75 C
33<=Percentage Marks<60 D
Percentage Marks <33 E
PROGRAM
#Taking input for five subjects
Hindi=int(input("Enter the marks of Hindi(out of 100)="))
English=int(input("Enter the marks of English(out of 100)="))
Maths=int(input("Enter the marks of Maths(out of 100)="))
Science=int(input("Enter the marks of Science(out of 100)="))
SSc=int(input("Enter the marks of Social Science(out of 100)="))
Tot_Marks= Hindi+English+Maths+Science+SSc
Per_Marks= round((Tot_Marks/500)*100,1)
print("Total Marks obtained=",Tot_Marks)
print("Percentage Marks=",Per_Marks)
#Evalution of grade
if(Per_Marks>=90):
grade='A'
elif(Per_Marks>=75):
grade='B'
elif(Per_Marks>=60):
grade='C'
elif(Per_Marks>=33):
grade='D'
elif(Per_Marks<33):
grade='E'
print("The Final grade is = ",grade)
OUTPUT
LAB ACTIVITY 2

Write a program to calculate income tax of employee as per their annual salary slabs.
AnnualSalary Tax Rate
Annual Salary< = 250000 0%
250000<Annual Salary<=500000 5%
500000<Annual Salary<=1000000 10%
1000000<Annual Salary 20%

PROGRAM
#Taking input of total annual salary of employee
Ann_Sal=int(input("Enter your Annual Salary = "))
#Calculating tax for different tax slabs
Tax=0
if(Ann_Sal<=250000):
Tax=0
elif(Ann_Sal>250000 and Ann_Sal<=500000):
Tax=(Ann_Sal-250000)*5/100
elif(Ann_Sal>500000 and Ann_Sal<=1000000):
Tax=(500000-250000)*.05 + (Ann_Sal-500000)*.1
elif(Ann_Sal>1000000):
Tax=(500000-250000)*.05 + (1000000-500000)*.1 + (Ann_Sal-1000000)*.2
print("The Amount of Tax to be paid = ",Tax)

OUTPUT
LAB ACTIVITY 3
Write a prorgam to display factorial of any number entered by user.

PROGRAM

#Calculating factorial
Num=int(input("Enter any number to find factorial= "))
fact=1
if(Num==0):
fact=1
else:
for i in range(1,Num+1):
fact=fact*i
print("Factorial of number ",Num," = ",fact)

OUTPUT
LAB ACTIVITY 4
Write a program to calculate wage of employees for the number of days they work. Wages
rates are given below-
Man 500 per day
Woman 350 per day

PROGRAM
no_of_man=int(input("Enter number of man/men working = "))
no_of_woman=int(input("Enter number of woman/women working = "))
m_days=int(input("Enter total number of days men worked = "))
w_days=int(input("Enter total number of days women worked = "))
#Calculating wages
Total_wages = m_days*no_of_man*500 + w_days*no_of_woman*350
print("Total wages to be paid = ",Total_wages)
ex=input ("press any key to exit")

OUTPUT
LAB ACTIVITY 5
Write a program to check whether the given numbre is prime or not.

PROGRAM

#Get a value to check prime number


num=int(input("Enter a number = "))
flag=0
for i in range(2,num):
if(num%i==0):
flag=1
if(flag==1):
print("It is not a prime number")
else:
print("It is a prime number")

ex=input("press any key to exit")

OUTPUT
LAB ACTIVITY 6
Consider the dataframe wdf (given in wdf.csv file in C: drive) and write code.
(i) Calculate minimum value for each of columns.
(ii) Calculate maximum value for each of rows.
(iii) Calculate variance for column Rainfall.
(iv) Compute mean, mode, median for last 10 rows.

PROGRAM

#Importing modules for pandas


import pandas as pd

df=pd.read_csv("c:/wdf.csv") #Reading data from .csv file


print(df)

#Minimum value for each column


dfm=df.min()
print(dfm)

#Maximum value for each row


dfM=df.max(axis=1)
print(dfM)

#Variance of Rainfall
dfV=df.Rainfall.var()
print("Variance of Rainfall =",dfV)

#Calculating mean, mode, median for last 10 rows


dfmn=df.loc[11:,].mean()
print("Mean value of each column is given below-\n",dfmn)
dfmd=df.loc[11:,].mode()
print("Mode value of each column is given below-\n",dfmd)
dfmdn=df.loc[11:,].median()
print("Mode value of each column is given below-\n",dfmdn)
ex=input("press any to exit")
OUTPUT
LAB ACTIVITY 7

A dataframe namely flidt stores some flights data (given in flights.csv file in C: drive) in the
form shown as given below-

Origin Destination Flights Aircraft Year Month Day


Write code to present the above information so that the data is shown as
Origin Destination Year Month Day Total Flights
That is total number of flights from a specific origin to destination on a specific data.
Note : First show original data and then show the data in required form.
Hint : Use groupby( )

PROGRAM
#Importing modules for pandas
import pandas as pd
import numpy as np
fldf=pd.read_csv("c:/flights.csv")
print("Flights data is:")
print(fldf)
newdf=fldf.groupby(by=['Origin','Destination','Year','Month','Day']).agg(np.sum)
print("Data after grouping and aggregation :")
print(newdf)
ex=input("press any key to exit")
OUTPUT
LAB ACTIVITY 8
Consider the data of Online tutorial company and prepare dataframe OnTutD from a
dictionary and write code for following-
(i)Compute and display total classes per tutor.
(ii)Compute and display number of countries per tutor.
(iii) Compute and display total classes by country.
(iv) Compute and display total classes on two fields, tutor and country wise.
(v) Compute and display average classes on two fields.
(vi) Sort and display data in descending order of tutor and country.

PROGRAM
#Importing modules for pandas
import pandas as pd
#Creation of dictionary
otd={'Tutor':['Tahira','Gurjyot','Anusha','Venkat','Jacob',
'Tahira','Gurjyot','Anusha','Venkat','Jacob',
'Tahira','Gurjyot','Anusha','Venkat','Jacob',
'Tahira','Gurjyot','Anusha','Venkat','Jacob'],
'Classes':[28,36,41,32,40,36,40,36,40,46,24,30,44,40,32,36,32,36,42,38],
'Quarter':[1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4],
'Country':['USA','UK','Japan','USA','Brazil','USA','USA',
'Japan','Brazil','USA','Brazil','USA','UK','Brazil',
'USA','Japan','Japan','Brazil','UK','USA']
}
#Creation of DataFrame from dictionary
df1=pd.DataFrame(otd)
print(df1)
df2=df1.pivot_table(index='Tutor',values='Classes',aggfunc='sum')
print(df2)
df3=df1.pivot_table(index='Tutor',values='Country',aggfunc='count')
print(df3)
df4=df1.pivot_table(index='Country',values='Classes',aggfunc='sum')
print(df4)
df5=df1.pivot_table(index=['Tutor','Country'],values=['Classes'],aggfunc='sum')
print(df5)
df6=df1.pivot_table(index=['Tutor','Country'],values='Classes',aggfunc='mean')
print(df6)
df7=df1.sort_values(['Tutor','Country'],ascending=False)
print(df7)
ex=input ("press any key to exit")
OUTPUT
LAB ACTIVITY 9
Write a program to create a 2D arrays shown below-
24356 (a) 5 6 (b) 5 4 3 6 (c ) 2 3 6 (d) 5 3 7 (e) 6 5 3 4 2
5 4 3 6 7 Now create the 67 1432 135 769 76345
7 3 6 4 9 new array as----> 49 94637
14325 52341

PROGRAM
#Importing modules for numpy
import numpy as np
Lst=[[2,4,3,5,6],[5,4,3,6,7],[7,3,6,4,9],[1,4,3,2,5]]
Ary=np.array(Lst)
print(Ary)

#Answer (a) Slicing first three elements of 4th and 5th Column
Ary1=Ary[:3,3:]
print(Ary1)

#Answer (b) Slicing First 4 elements of 2nd and 4th row


Ary2=Ary[1::2,:4]
print(Ary2)

#Answer (c) Slicing First, Third and Fifth elements of 1st and 4th row
Ary3=Ary[::3,::2]
print(Ary3)

#Answer (d) Slicing First, Third and Fifth elements of 2nd and 3rd row
Ary4=Ary[1:3,::2] # Ary4=Ary[-3:-1,-5::2]
print(Ary4)

#Answer (e) Displaying all rows and columns in reverse order


Ary5=Ary[:,::-1]
print(Ary5)
ex= input("press any key to exit")

OUTPUT
LAB ACTIVITY 10
Create an array A1 as given below-
7 4 3 9
2 5 6 8
9 12 1 15
Write a program in python to extract the subset from ndarray A1 containing elements,
whose cube is fully divisible by 9.

PROGRAM

#Importing modules for numpy


import numpy as np
Lst=[[7,4,3,9],[2,5,6,8],[9,12,1,15]]
A1=np.array(Lst)
print("The given array A1 is")
print(A1)
condition= (A1**3)%9==0
RevA1=np.extract(condition,A1)
print("The new elements whose cube is fully devisible by 9 is")
print(RevA1)
ex=input ("press any key to exit")

OUTPUT
LAB ACTIVITY 11
Write a program to create a line chart for following data-
x=[2,4,3,7,5]
y=[23,43,18,20,5]
Write code to
(a) Display dashed line
(b) Display * (star) marker
(c )Change the marker color to blue

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,orange
(b) Change width of bars in sequence as0.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()
ex=input("enter any key to exit")

OUTPUT
LAB ACTIVITY 13

Write a program in python to plot a graph for the function y = x 2

PROGRAM
import matplotlib.pyplot as plt
x_cords = range(-50,50)
y_cords = [x*x for x in x_cords]

plt.scatter(x_cords, y_cords)
plt.show()
ex=input("press any key to exit")

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.]]

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()
ex=input("press any key to exit")

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 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

"""(a) Create a simple histogram from above data."""


plt.hist(wff)
plt.show()

"""(b) Create a horizontal histogram from above data."""


plt.hist(wff,orientation='horizontal')
plt.show()

"""(c) Create a step type of histogram from above data."""


plt.hist(wff,histtype='step')
plt.show()

"""(d) Create a cumulative histogram from above data."""


plt.hist(wff,cumulative=True)
plt.show()
ex=input("press any key to exit")
OUTPUT
LAB ACTIVITY 17
Write a program in python to fetch and display records of perticular JOB 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()

#Fetching data of employees for perticular JOB type entered by user


jobtype=input("Write the name of JOB from CLERK,SALESMAN,MANAGER,ANALYST,PRESIDENT
to display list of employees working= ")
print("Records of employees working as ",jobtype)
qry="select * from emp where Job like %s"
crs.execute(qry,(jobtype,))
data1 =crs.fetchall()
df = pd.DataFrame(data1,
columns=["Ecode","Ename","Sex","Job","MGR","Hiredate","Sal","Comm","Dname"])
print(df)
crs.close()
except mysql.connector.Error as error:
print("Records not available")
ex=input("press any key to exit")

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()

#Fetching data of employees for perticular JOB type entered by user


qry="select * from emp"
crs.execute(qry)
data1 =crs.fetchall()
df = pd.DataFrame(data1,
columns=["Empno","Ename","Sex","Job","MGR","Hiredate","Sal","Comm","Dname"])
print(df)
k=1
while(k == 1):
colum=input("Write the name of column to group the records= ")
print("Total employees ",colum," wise is given below-")
Agg_data=df.groupby([colum]).count()
#Peforming dataframe operation
print(Agg_data["Ename"])
crs.close()
k=int(input("To group again,enter '1' or press other key to close"))
except mysql.connector.Error as error:
print("Records not available")
ex=input("press any key to exit")
OUTPUT
LAB ACTIVITY 19
Write a program in python to display the details of mobiles a per he range of price entered by
user from mysql table mobile stored in database store (given in mobile.csv file in C:
drive)
Use command in mysql to load file :
load data local infile 'c:\\mobile.csv' into table mobile fields terminated by ',' lines terminated by '\
r\n';

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

import mysql.connector as msc


import pandas as pd

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

You might also like