0% found this document useful (0 votes)
31 views

Class XII-IP-Practical File

This document contains a programming file for the subject Informatics Practices for the 2019-20 session at Kasturi Ram International School. It lists 25 practical programs involving the use of Python, NumPy, Pandas and data visualization. The programs cover concepts like arrays, series, dataframes, MySQL connectivity and plotting various charts.

Uploaded by

Ashenur Rehman
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Class XII-IP-Practical File

This document contains a programming file for the subject Informatics Practices for the 2019-20 session at Kasturi Ram International School. It lists 25 practical programs involving the use of Python, NumPy, Pandas and data visualization. The programs cover concepts like arrays, series, dataframes, MySQL connectivity and plotting various charts.

Uploaded by

Ashenur Rehman
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

KASTURI RAM INTERNATIONAL SCHOOL

Session 2019-20

INFORMATICS PRACTICES(065)

PROGRAMMING FILE

MADE BY-
NAME :__________________
CLASS : XII
ROLL NO :________
LIST OF PRACTICALS :

S.NO. PROGRAM
1 Write a Program in Python, which accepts an numpy array of integer and
divide all those array elements by 7 which are divisible by 7 and
multiply other array elements by 3.
2 Write a program in Python which accepts an integer numpy array and
replaces elements having even values with its half and elements having
odd values with twice its value.
3 Write a program that would accept a one dimensional integer array and
rearrange the array in such a way that the values of alternate locations of
the array are exchanged .
4 Write a program in Python which accepts an integer numpy array and
show result using functions like hsplit(), vsplit() ,cov() , corrcoef()
elements having odd values with twice its value.
5 Write a Program to show the utility of numpy and series in python.
6 Write a Program to show the utility of head and tail functions of series in
python.
7 Write a Program to create series using pre-defined array/ create series
using userdefined array/list/ create series using pre-defined list/create
Series using Predefined Dictionary/create series using User-defined
Dictionary/ change index in series/print head and tail elements/print
according to index position and condition .
8 Write a Program to enter data and show data in python using dataFrames
and pandas.
9 Write a Program to enter multiple values based data in multiple
columns/rows and show that data in python using statistical functions on
dataFrames and pandas.
10 Write a Program to enter multiple values based data in multiple
columns/rows and show that data in python using SORTING on
dataFrames and pandas.’’’
11 Write a program to show working of pivot() and pivot_table() along with
statistical functions.
12 Write a program to show result of quantile and sorting of values on two
different dataframes.
13 Write a program to plot a line chart with title ,xlabel , ylabel and line
style.
14 Write a program to plot bar chart having Cities along with their
Population on xaxis and yaxis.
15 Write a program to plot bar chart having data x,y on xaxis and yaxis,
showing in different color with different width.
16 Write a program to plot SCATTER CHART having data x,y on xaxis
and yaxis, with marker and color attribute.
17 Write a program to create boxplot having an ndarray with 10 values.
18 Write a program to plot HISTOGRAM from an ndarray with 14
bins(intervals)
19 Write a program to plot CUMULATIVE HISTOGRAM of
BARSTACKED type from two ndarrays with 14 bins(intervals)
20 Write a program to plot a MULTI-LINE chart with title ,xlabel , ylabel
and line style.
21 Write a program to write dictionary data in CSV file
22 Write a Program to read CSV file and show its data in python using
dataFrames and pandas.’’’
23 Write a Program to enter values in python using dataFrames and show
these values/rows in 4 different excel files .
24 Write a Program to read Excel file and show its data in python using
dataFrames and pandas.
25 Write a program to show MySQL CONNECTIVITY for inserting two
tuples in table:"shelly" inside database:"python10"
26 Write a Program to show database connectivity of python Data Frames
with mysql database.
#Program1: Write a Program in Python, which accepts an numpy array of
integer and divide all those array elements by 7 which are divisible by 7 and
multiply other array elements by 3.
Sample Input Date of the array
A[O] A[1] A[2] A[3] A[4]
21 12 35 42 18
Content of the array after program :A[O] A[1] A[2] A[3] A[4]
3 36 5 6 54

import numpy as np
a=np.array([21,12,35,42,18])
print("\nthe elemnets of a numpy array is ",a)
for i in range(a.size):
if a[i]%7==0:
a[i]=a[i]/7
else:
a[i]=a[i]*3
print ("\nthe elements after change are :",a)
#Program2 : Write a program in Python which accepts an integer numpy
array and replaces elements having even values with its half and elements
having odd values with twice its value.

import numpy as np
l=[]
for i in range(5):
a=int(input("enter any no:"))
l.append(a)
a=np.array(l)
print("\nthe elements in a numpy arrar are :",a)
for i in range(a.size):
if a[i]%2==0:
a[i]=a[i]/2
else:
a[i]=a[i]*2
print ("\nthe elements after change are : ",a)
#Program3: Write a program that would accept a one dimensional integer
array and rearrange the array in such a way that the values of alternate
locations of the array are exchanged
(Assume the size of the array to be even)
Example : If the array initially contains {2, 5, 9, 14, 17, 8, 19, 16},
then after rearrangement the array should contain {5, 2, 14, 9, 8, 17, 16,
19}

import numpy as np
a=np.array([2, 5, 9, 14, 17, 8, 19, 16])
print ("\nthe elements of numpy array are :",a)
i=0
while i<a.size:
a[i],a[i+1]=a[i+1],a[i]
i=i+2
print ("\n\nthe elements of numpy array after change are :",a)
#Program4: Write a program in Python which accepts an integer numpy
array and show result using functions like hsplit(), vsplit() ,cov() , corrcoef()
elements having odd values with twice its value.

import numpy as np
ar1=np.array([[0,1],[3,4]])
ar2=np.array([[10,11],[13,14]])
print("the elements in array 1 are :\n",ar1)
print("\nthe elements in array 2 are :\n",ar2)
ar3=np.concatenate((ar1,ar2),axis=0)
print("\nthe elements in array 3 after concatenation throgh row are :",ar3)
ar4=np.hsplit(ar1,2)
print("\nthe elements after horizontal split in array 1 are :",ar4)
ar5=np.vsplit(ar2,2)
print("\nthe elements after vertical split in array 2 are :",ar5)
cov1=np.cov(ar1,ar2)
print ("\nthe covariance of array1 and array2 is : ",cov1)
cor1=np.corrcoef(ar1,ar2)
print ("\nthe correlation of array1 and array2 is : ",cor1)
#Program5: Write a Program to show the utility of numpy and series in
python.

import pandas as pd
import numpy as np
data = np.array(['a','b','c','d'])
s = pd.Series(data)
print("the data in series form is\n",s)
data1 = np.array(['a','b','c','d'])
s1 = pd.Series(data1,index=[100,101,102,103])
print("the data in series form with index value is \n" ,s1)
#Program6: Write a Program to show the utility of head and tail functions of
series in python.

import pandas as pd
my_series=pd.Series([1,2,3,"A String",56.65,-100], index=[1,2,3,4,5,6])
print(my_series)
print("Head")
print(my_series.head(2))
print("Tail")
print(my_series.tail(2))
my_series1=pd.Series([1,2,3,"A String",56.65,-100], index=['a','b','c','d','e','f'])
print(my_series1)
print(my_series1[2])
my_series2=pd.Series({'London':10, 'Tripoli':100,'Mumbai':150})
print (my_series2)
print("According to Condition")
print (my_series2[my_series2>10])
dic=({'rohit':[98266977,'rohit@gmail.com'], 'prakash':
[9826972,'prakash@gmail.com'],
'vedant':[788990,'vedant@gmail.com']})
s=pd.Series(dic)
print (s)
print("According to First Condition")
print(s[1])
print("According to Second Condition")
l=s.size
print("No of items" ,l)
for i in range(0,l):
if s[i][0]==9826972:
print (s[i])
“””Program7: Write a Program to create series using pre-defined array/
create series using userdefined array/list/ create series using pre-defined
list/create Series using Predefined Dictionary/create series using User-defined
Dictionary/ change index in series/print head and tail elements/print
according to index position and condition in python.”””

import pandas as pd #creating series using pre-defined array


data=['a','b','c']
s=pd.Series(data)
print("THE VAUUES IN SERIES ARE \n",s)
#creating series using user-defined array/list
#creating an array
ar1=list()
n=int(input("Enter the values for an array"))
print("Enter numbers")
for i in range(0,n):
num=int(input("num:"))
ar1.append(num)
s=pd.Series(ar1)
print("THE VALUES IN NEW SERIES ARE \n",s)
#creating series using pre-defined list
list=['a','b','c']
s=pd.Series(list)
print(s)
list=[[0,1,2,3],['a','b','c'],["vedant","purnendu","rupali"]]
s=pd.Series(list)
print("\nTHE VALUES IN SERIES CREATED FROM LIST ARE\n ",s)
#creating Series using Predefined Dictionary
dic=({'rupali':[9826386977,'rupali@gmail.com'], 'purnendu':
[9826911972,'purnendup@gmail.com'],
'vedant':[788990,'vedant@gmail.com']})
s=pd.Series(dic)
print ("\nTHE VALUES IN SERIES CREATED FROM PRE-DEFINED
DICTIONARY ARE \n",s)
#creating series using User-defined Dictionary
key=input("Enter the Key")
value=int(input("enter the value"))
dict[key]=value
s=pd.Series(dict)
print ("\nTHE VALUES IN SERIES CREATED FROM USER-DEFINED
DICTIONARY ARE \n",s)
#change index in series
s=pd.Series(data,index=[1,2,3])
print (s)
#printing head and tail elements
print("\nTHE STARTING VALUES ARE\n",s.head(2)) #displays first 2 elements
print("\nTHE LAST VALUES ARE \n",s.tail(1)) #displays last 1 elements'''
#printing according to index position and condition
print(s[1])
print("According to Condition")
print(s[s==9826386977])
#Program8: Write a Program to enter data and show data in python using
dataFrames and pandas.

import pandas as pd
data = [['Rajiv',10],['Sameer',12],['Kapil',13]]
df = pd.DataFrame(data,columns=['Name','Age'])
print ("\nTHE VALUES IN DATAFRAME ARE \n",df)
data1 = {'Name':['Rajiv', 'Sameer', 'Kapil', 'Nischay'],'Age':[28,34,29,42],
'Designation':['Accountant','Cashier','Clerk','Manager']}
df1 = pd.DataFrame(data1)
print ("THE VALUES IN SECOND DATAFRAME ARE \n",df1)
#‘’’Program9: Write a Program to enter multiple values based data in
multiple columns/rows and show that data in python using statistical
functions on dataFrames and pandas.’’’

import pandas as pd
weather_data={
'day':
['01/01/2018','01/02/2018','01/03/2018','01/04/2018','01/05/2018','01/01/2018'],
'temperature':[42,41,43,42,41,40],
'windspeed':[6,7,2,4,7,2],
'event':['Sunny','Rain','Sunny','Sunny','Rain','Sunny']
}
df=pd.DataFrame(weather_data)
print("\nthe values in dataframe showing weather :\n",df)
print("\nNumber of Rows and Columns")
print(df.shape)
print(df.head())
print("Tail")
print(df.tail(2))
print("\nSpecified Number of Rows\n")
print(df[2:5])
print("\nPrint Everything\n")
print(df[:])
print("\nPrint Column Names:\n")
print(df.columns)
print("\nData from Individual Column:\n")
print(df['day']) #or df.day
print(df['temperature'])
print("Maximum Temperature : ", df['temperature'].max())
#‘’’Program10: Write a Program to enter multiple values based data in
multiple columns/rows and show that data in python using SORTING on
dataFrames and pandas.’’’

import pandas as pd
weather_data={
'day':
['01/01/2018','01/02/2018','01/03/2018','01/04/2018','01/05/2018','01/01/2018'],
'temperature':[42,41,43,42,41,40],
'windspeed':[6,7,2,4,7,2],
'event':['Sunny','Rain','Sunny','Sunny','Rain','Sunny']
}
df=pd.DataFrame(weather_data)
print("\nthe values in dataframe showing weather :\n",df)
print("\nPrinting According to Condition:\n")
print(df[df.temperature>41])
print("\nPrinting the row with maximum temperature:\n")
print(df[df.temperature==df.temperature.max()])
print("\nPrinting specific columns with maximum temperature\n")
print(df[['day','temperature']][df.temperature==df.temperature.max()])
print("\nAccording to index:\n")
print(df.loc[3])
print("Changing of Index:\n")
df.set_index('day',inplace=True)
print(df)
print("Searching according to new index:\n")
print(df.loc['01/03/2018'])
print("Resetting the Index:\n")
df.reset_index(inplace=True)
print(df)
print("Sorting\n:")
print(df.sort_values(by=['temperature'],ascending=False))
print("Sorting on Multiple Columns:\n")
print(df.sort_values(by=['temperature','windspeed'],ascending=True))
print("Sorting on Multiple Columns one in ascending, another in descending:\n")
print(df.sort_values(by=['temperature','windspeed'],ascending=[True,False]))
print("Sum Operations on Data Frame")
print(df['temperature'].sum())
print("Group By Operations:\n")
print(df.groupby('windspeed')['temperature'].sum())
#PROGRAM11: Write a program to show working of pivot() and
pivot_table() along with statistical functions

#import OrderedDict from pandas


#import DataFrame
import pandas as pd
import numpy as np
table={"item":['tv','tv','ac','ac'],
'company':['lg','videocon','lg','sony'],
'rupees':[12000,10000,15000,14000],
'usd':[700,650,800,750]}
d=pd.DataFrame(table)
print("DATA OF DATAFRAME")
print(d)
p=d.pivot(index='item',columns='company',values='rupees')
print("\n\nDATA AFTER PIVOT :")
print(p)
print(p[p.index=='tv'].lg.values)
p1=d.pivot_table(index='company',values='rupees',aggfunc='sum')
print("\n\nDATA IN PIVOT TABLE WITH SUM:\n")
print(p1)
p2=d.pivot_table(index=['item','company'],values=['usd'],aggfunc='mean')
print("\n\nDATA IN PIVOT TABLE WITH MEAN:\n")
print(p2)
#PROGRAM12: Write a program to show result of quantile and sorting of
values on two different dataframes

import pandas as pd
import numpy as np
df=pd.DataFrame(np.array([[1,1],[2,10],[3,100],[4,1000]]),columns=['a','b'])
print("the elements of dataframe1 are \n",df)
print("\nthe elements of dataframe1 with quantile are \n",df)
print(df.quantile(0.5))

unsorted_df=pd.DataFrame(np.random.randn(10,2),index=[1,4,6,2,3,5,9,8,0,7],col
umns=['col2','col1'])
sorted_df=unsorted_df.sort_index(ascending=False)
print("\nthe elements of dataframe1 after sorting are \n",sorted_df)
#Program13: Write a program to plot a line chart with title ,xlabel , ylabel
and line style.

import matplotlib.pyplot as p
a=[1,2,3,4]
b=[2,4,6,8]
p.plot(a,b)
p.xlabel("values")
p.ylabel("doubled values")
p.title("LINE CHART")
p.plot(a,b,ls="dashed",linewidth=4,color="r")
p.show()
#Program14: Write a program to plot bar chart having Cities along with their
Population on xaxis and yaxis.

import matplotlib.pyplot as p
a=["delhi","mumbai","kolkata","chennai"]
b=[423517,34200,63157,99282]
p.xlabel("cities")
p.ylabel("polpulation")
p.title("BAR CHART")
p.bar(a,b,color=["red","green"])
p.show()
#PROGRAM 15: Write a program to plot bar chart having data x,y on xaxis
and yaxis, showing in different color with different width.

import numpy as np
import matplotlib.pyplot as p1

x=[1,2,3,4,5]
y=[6,7,8,9,10]
p1.xlabel("DATA FROM A")
p1.ylabel("DATA FROM B")
p1.title("DATA ALL")
p1.bar(x,y,width=[0.3,0.2,0.4,0.1,0.5],color=["red","black","b","g","y",])
p1.show()
#PROGRAM 16: Write a program to plot SCATTER CHART having data
x,y on xaxis and yaxis, with marker and color attribute.

import matplotlib.pyplot as p1

x=[1,2,3,4,5,6,7,8,9,10]
y=[13,7,2,11,0,17,1,11,22,14]
print(x)
print(y)
p1.xlabel("Overs")
p1.ylabel("Score")
p1.title("IPL 2019")
p1.scatter(x,y,marker='x', color='y')
p1.show()
#Program17: Write a program to create boxplot having an ndarray with 10
values.

import numpy as np
import matplotlib.pyplot as p1
ary=[5,20,30,45,60,80,100,140,150,200,240]
p1.boxplot(ary)
p1.show()
#Program18: Write a program to plot HISTOGRAM from an ndarray with
14 bins(intervals)

import numpy as np
import matplotlib.pyplot as p1
ary=[5,20,30,45,60,80,100,140,150,200,240,260,275,290]
p1.hist(ary,bins=14)
p1.show()
#Program19: Write a program to plot CUMULATIVE HISTOGRAM of
BARSTACKED type from two ndarrays with 14 bins(intervals)

import numpy as np
import matplotlib.pyplot as p1
ary1=[5,20,30,45,60,80,100,140,150,200,240,260,275,290]
ary2=[10,25,35,50,70,90,110,130,150,220,25,280,295,310]
p1.hist([ary1,ary2],histtype='barstacked', cumulative=True)
p1.show()
#PROGRAM20: Write a program to plot a MULTI-LINE chart with title ,
xlabel , ylabel and line style.

import numpy as np
import matplotlib.pyplot as plt
data=[[5.,25.,45.,20.],[8.,13.,29.,27.,],[9.,29.,27.,39.]]
x=np.arange(4)
plt.plot(x,data[0],color='b',label='range1',linestyle=”dashed”)
plt.plot(x,data[1],color='g',label='range2',linestyle=”solid”)
plt.plot(x,data[2],color='r',label='range3',linestyle=”dotted”)
plt.legend(loc='upper left')
plt.title("multiRange line chart")
plt.xlabel('x')
plt.ylabel('y')
plt.show()

#PROGRAM21: Write a program to write dictionary data in CSV file

import csv
with open('example5.txt', 'w') as csvfile:
fieldnames = ['first_name', 'last_name', 'Grade']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerows([{'Grade': 'B', 'first_name': 'Alex', 'last_name': 'Brian'},
{'Grade': 'A', 'first_name': 'Rachael',
'last_name': 'Rodriguez'},
{'Grade': 'C', 'first_name': 'Tom', 'last_name': 'smith'},
{'Grade': 'B', 'first_name': 'Jane', 'last_name': 'Oscar'},
{'Grade': 'A', 'first_name': 'Kennzy', 'last_name': 'Tim'}])
print("writing complete")

#Program22: Write a Program to read CSV file and show its data in python
using dataFrames and pandas.’’’

import pandas as pd
df=pd.read_csv("student.csv", nrows=3)
print("\nTo display selected number of rows from beginning")
print(df)
df=pd.read_csv("student.csv")
print(df)
print("\nNumber of Rows and Columns : ",df.shape)
print("\nHead-Records from starting : ")
print(df.head(2))
print("\nTail-records from bottom :")
print(df.tail(2))
print("\nSpecified Number of Rows")
print(df[2:5])
print("\nPrint Everything")
print(df[:])
print("\nPrint Column Names")
print(df.columns)
print("\nData from Individual Column")
print(df.Name) #or df.Name
print(df['Marks'])
print("Maximum Marks : ", df['Marks'].max())
print("Printing According to Condition")
print(df[df.Marks>70])
print("Printing the row with maximum temperature")
print(df[df.Marks==df.Marks.max()])
print("Printing specific columns with maximum Marks")
print(df[['Name','Marks']][df.Marks==df.Marks.max()])
print("According to index")
print(df.loc[3])
print("Changing of Index")
df.set_index('Scno',inplace=True)
print(df)
#print("Searching according to new index")
#print(df.loc[4])
print("Resetting the Index")
df.reset_index(inplace=True)
print(df)
print("Sorting")
print(df.sort_values(by=['Marks'],ascending=False))
print("Sorting on Multiple Columns")
print(df.sort_values(by=['Class','Section'],ascending=True))
print("Sorting on Multiple Columns one in ascending, another in descending")
print(df.sort_values(by=['Marks','Name'],ascending=[False,True]))
print("Sum Operations on Data Frame")
print(df['Marks'].sum())
print("Group By Operations")
print(df.groupby('Class')['Marks'].sum())
#‘’’Program23: Write a Program to enter values in python using dataFrames
and show these values/rows in 4 different excel files .’’’

import pandas as pd
data = [['Rajiv',10],['Sameer',12],['Kapil',13]]
df = pd.DataFrame(data,columns=['Name','Age'])
print ("THE VALUES IN DATAFRAME ARE \n",df)
df.to_csv('new.csv')
df.to_csv('new1.csv', index=False)
df.to_csv('new2.csv', columns=['Name'])
df.to_csv('new4.csv', header=False)
#‘’’Program24: Write a Program to read Excel file and show its data in
python using dataFrames and pandas.’’’

import pandas as pd
df=pd.read_excel("studentdata.xlsx","Sheet1")
print(df)
weather_data={
'day':
['01/01/2018','01/02/2018','01/03/2018','01/04/2018','01/05/2018','01/06/2018'],
'temperature':[42,41,43,42,41,40],
'windspeed':[6,7,2,4,7,2],
'event':['Sunny','Rain','Sunny','Sunny','Rain','Sunny']
}
df1=pd.DataFrame(weather_data)
print(df1)
#df1.to_excel("weather.xlsx",sheet_name="weatherdata")
#df1.to_excel("weather.xlsx",sheet_name="weatherdata", startrow=1, startcol=2)
data1 = {'Name':['Rajiv', 'Sameer', 'Kapil', 'Nischay'],'Age':[28,34,29,42],
'Designation':['Accountant','Cashier','Clerk','Manager']}
df2 = pd.DataFrame(data1)
print (df2)
with pd.ExcelWriter('weather.xlsx') as writer:
df1.to_excel(writer, sheet_name="Weather")
df2.to_excel(writer, sheet_name="Employee")
#Program25: Write a program to show MySQL CONNECTIVITY for
inserting two tuples in table:"shelly" inside database:"python10"

import mysql.connector as m

db=m.connect(host="localhost",user="root",passwd="",database="python10")
cursor_obj=db.cursor()
cursor_obj.execute('INSERT INTO shelly VALUES("kamal4",1234,"NARELA")')
cursor_obj.execute('INSERT INTO shelly VALUES("kamal3",1234,"NARELA")')
db.commit()

print("record inserted")
#Program26: Write a Program to show database connectivity of python Data
Frames with mysql database.

def fetchdata():

import mysql.connector
try:
db = mysql.connector.connect(user='root', password='',
host='127.0.0.1',database='test')
cursor = db.cursor()
sql = "SELECT * FROM student"
cursor.execute(sql)
results = cursor.fetchall()
for cols in results:
nm = cols[0]
st = cols[1]
stream =cols[2]
av=cols[3]
gd=cols[4]
cl=cols[5]
print ("Name =%s, Stipend=%f, Stream=%s, Average Marks=%f, Grade=%s,
Class=%d" % (nm,st,stream,av,gd,cl ))
except:
print ("Error: unable to fecth data")
db.close()
def adddata():
import mysql.connector
nm=input("Enter Name : ")
stipend=int(input('Enter Stipend : '))
stream=input("Stream: ")
avgmark=float(input("Enter Average Marks : "))
grade=input("Enter Grade : ")
cls=int(input('Enter Class : '))
db = mysql.connector.connect(user='root', password='',
host='127.0.0.1',database='test')
cursor = db.cursor()
sql="INSERT INTO student VALUES ( '%s' ,'%d','%s','%f','%s','%d')" %(nm,
stipend, stream, avgmark, grade, cls)
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
def updatedata():
import mysql.connector
try:
db = mysql.connector.connect(user='root', password='tiger',
host='127.0.0.1',database='test')
cursor = db.cursor()
sql = "Update student set stipend=%d where name='%s'" % (500,'Arun')
cursor.execute(sql)
db.commit()
except Exception as e:
print (e)
db.close()
def udata():
import mysql.connector
try:
db = mysql.connector.connect(user='root', password='',
host='127.0.0.1',database='test')
cursor = db.cursor()
sql = "SELECT * FROM student"
cursor.execute(sql)
results = cursor.fetchall()
for cols in results:
nm = cols[0]
st = cols[1]
stream =cols[2]
av=cols[3]
gd=cols[4]
cl=cols[5]
print ("Name =%s, Stipend=%f, Stream=%s, Average Marks=%f, Grade=%s,
Class=%d" %
(nm,st,stream,av,gd,cl ))
except:
print ("Error: unable to fecth data")
temp=input("Enter Student Name to Updated : ")
tempst=int(input("Enter New Stipend Amount : "))
try:
#db = mysql.connector.connect(user='root', password='tiger',
host='127.0.0.1',database='test')
#cursor = db.cursor()
sql = "Update student set stipend=%d where name='%s'" % (tempst,temp)
cursor.execute(sql)
db.commit()
except Exception as e:
print (e)
db.close()
def deldata():
import mysql.connector
try:
db = mysql.connector.connect(user='root', password='',
host='127.0.0.1',database='test')
cursor = db.cursor()
sql = "SELECT * FROM student"
cursor.execute(sql)
results = cursor.fetchall()
for cols in results:
nm = cols[0]
st = cols[1]
stream =cols[2]
av=cols[3]
gd=cols[4]
cl=cols[5]
print ("Name =%s, Stipend=%f, Stream=%s, Average Marks=%f, Grade=%s,
Class=%d" %
(nm,st,stream,av,gd,cl ))
except:
print ("Error: unable to fecth data")
temp=input("Enter Student Name to deleted : ")
try:
#db = mysql.connector.connect(user='root', password='tiger',
host='127.0.0.1',database='test')
#cursor = db.cursor()
sql = "delete from student where name='%s'" % (temp)
ans=input("Are you sure you want to delete the record : ")
if ans=='yes' or ans=='YES':
cursor.execute(sql)
db.commit()
except Exception as e:
print (e)
try:
db = mysql.connector.connect(user='root', password='',
host='127.0.0.1',database='test')
cursor = db.cursor()
sql = "SELECT * FROM student"
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
nm = row[0]
st = row[1]
stream =row[2]
av=row[3]
gd=row[4]
cl=row[5]
print ("Name =%s, Stipend=%f, Stream=%s, Average Marks=%f, Grade=%s,
Class=%d" %
(nm,st,stream,av,gd,cl ))
except:
print ("Error: unable to fetch data")

You might also like