Sunteți pe pagina 1din 32

List of programmes for class XII-Computer Science with Python (083)

# Program 1: Write a program to enter name and display as “Hello, Name”.

nm=input("Enter Your Name: ")

print("Hello, ",nm)

#Program2: Program to enter two numbers and print the arithmetic operations like +,1,*,/,// and %.

p=int(input("Enter Number-1: "))

q=int(input("Enter Number-2: "))

r=p+q

print(("Sum of %d and %d is %d")%(p,q,r))

r=p-q

print(("Subtraction of %d and %d is %d")%(p,q,r))

r=p*q

print(("Product of %d and %d is %d")%(p,q,r))

r=p/q

print(("Division of %d and %d is %f")%(p,q,r))

r=p//q

print(("Integer Division of %d and %d is %d")%(p,q,r))

r=p%q

print(("Remainder of %d and %d is %d")%(p,q,r))

#Program3: Program to enter age and print the eligibility to vote or not.

age=int(input("Enter age : "))

if age>=60:

print ("Eligible to Vote and happy retired life")

elif age>=18:

print("Eligible to Vote")
else:

print("Not Eligible to Vote")

#Program4: Program to find maximum out of entered 3 numbers.

name=input("Enter your name : ")

var1=float(input("Enter First Number : "))

var2=float(input("Enter Second Number : "))

var3=float(input("Enter Third Number :"))

if var1>var2 and var1>var3:

print('Variable one is greatest')

elif var2>var1 and var2>var3:

print('Variable two is greatest')

elif var3>var1 and var3>var1:

print('Third number is greatest')

else:

print('Either two numbers are equal or all nos are equal')

print (name)

#Program5: Write a Program to check if the entered number is Armstrong or not.

no=int(input("Enter any number to check : "))

no1 = no

sum = 0

while(no>0):

ans = no % 10;

sum = sum + (ans * ans * ans)

no = int (no / 10)

if sum == no1:

print("Armstrong Number")
else:

print("Not an Armstrong Number")

#Program6: Write a Program to find factorial of the entered number .

def fact(no):

f=1;

while no>0:

f=f*no

no=no-1

return f

#Program7: Write a Program to enter the number of terms and to print the Fibonacci Series.

no1=1

no2=2

print('' ,+ no1)

print('\n',+no2)

x=1

while(x<=10):

no3=no1+no2

no1=no2

no2=no3

print ('\n',+no3)

x=x+1

#Program8: Write a Program to enter a number and to print its table.

no=int(input("Enter Number : "))

for i in range(1, 11):

print(i*no,end='\n')
#Program9: Write a Program to enter the numbers and to print greatest number using loop.

big=0

for x in range(1,11):

no=int(input("Ente Number to Check : "))

if no>big:

big=no

print ("The greatest Number is : ",big)

#Program10: Write a Program to enter the string and to check if it’s palindrome or not using loop.

msg=input("Enter any string : ")

newlist=[]

newlist[:0]=msg

l=len(newlist)

ed=l-1

for i in range(0,l):

if newlist[i]!=newlist[ed]:

print ("Given String is not a palindrome")

break

if i>=ed:

print ("Given String is a palindrome")

break

l=l-1

ed = ed – 1

#Program11: Write a Program to show the outputs based on entered list.

my_list = ['p','r','o','b','e']
# Output: p

print(my_list[0])

# Output: o

print(my_list[2])

# Output: e

print(my_list[4])

# Error! Only integer can be used for indexing

# my_list[4.0]

# Nested List

n_list = ["Happy", [2,0,1,5]]

# Nested indexing

# Output: a

print(n_list[0][1],n_list[0][2],n_list[0][3])

# Output: 5

print(n_list[1][3])

#Program12: Write a Program to enter the numbers in a list and to show the greatest element using
#loop in the entered list.

my_list = [10,50,100,258,656,126,486,268,486,105]

x=len(my_list)

big=0

for no in range(0, x):

if my_list[no]>big:

big=my_list[no]

print (big)

#Program13: Write a Program to enter the numbers in a list using split() and to use all the functions
related to list.

# numbers = [int(n, 10) for n in input().split(",")]


# print (len(numbers))

memo=[]

for i in range (5):

x=int(input("enter no. \n"))

memo.insert(i,x)

i+=1

print(memo)

memo.append(25)

print("Second List")

print(memo)

msg=input("Enter any string : ")

newlist=[]

newlist[:0]=msg

l=len(newlist)

print(l)

‘’’Program14: Write a Program to enter the number and print the Floyd’s Triangle in decreasing
order.’’’

n=int(input(‘Enter the number :’))

for i in range(5,0,-1):

for j in range(5,i-1,-1):

print (j,end=' ')

print('\n')

#Program15: Write a Program to enter the number and print whether the number is odd or even.

n=int(input('Enter the number:'))

for i in range(1,n+1):

if i%2==0:

print ('The number'+str(i)+'is even')


else:

print ('The number'+str(i)+'is odd')

#Program16: Write a Program to enter the 5 subjects numbers and print the grades A/B/C/D/E.

no1=int(input("Enter First Subject Marks : "))

no2=int(input("Enter Second Subject Marks : "))

no3=int(input("Enter Third Subject Marks : "))

no4=int(input("Enter Fourth Subject Marks : "))

no5=int(input("Enter Fifth Subject Marks : "))

total=no1+no2+no3+no4+no5

perc=total/5

print('Total Marks : ', + total, '\nAverage Marks : ',+ perc)

if perc<33:

print("Retest")

elif perc>=33 and perc<50:

print("D Grade")

elif perc>=50 and perc<60:

print("C Grade")

elif perc>=60 and perc<70:

print("B Grade")

else:

print("A Grade")

#Program17: Write a Program to show the outputs based on menu options for Matrix sum and exit.

import matrix_sum_function as myfile

print("""List Menu

1. Addition

2. Exit""")
option=int(input("Enter your choice:"))

while(option!=0):

if option==1:

myfile.matrix_sum()

option=int(input("Enter your choice:"))

else:

exit()

#Program18: Write a Program to find factorial of entered number using library function fact().

import factfunc

x=int(input("Enter value for factorial : "))

ans=factfunc.fact(x)

print (ans)

‘’’Program19: Write a Program to enter the numbers and find Linear Search, Binary Search, Lowest
Number and Selection Sort using array code.’’’

arr=[]

def array_operation():

ch=1

while ch!=10 :

print('Various Array operation\n')

print('1 Create and Enter value\n')

print('2 Print Array\n')

print('3 Reverse Array\n')

print('4 Linear Search\n')

print('5 Binary Search\n')

print('6 Lowest Number \n')


print('7 Selection Sort\n')

print('10 Exit\n')

ch=int(input('Enter Choice '))

if ch==1 :

appendarray()

elif ch==2 :

print_array()

elif ch==3 :

reverse_array()

elif ch==4 :

linear_search()

elif ch==5 :

binary_search()

elif ch==6 :

min_number()

elif ch==7 :

selection_sort()

def appendarray():

for i in range(0,10):

x=int(input('Enter Number : '))

arr.insert(i,x)

#-----------------------------------------------------------------------------------------------------------------------------------------

def print_array():

for i in range(0,10):

print(arr[i]),
#-----------------------------------------------------------------------------------------------------------------------------------------

def reverse_array():

for i in range(1,11):

print(arr[-i]),

#-----------------------------------------------------------------------------------------------------------------------------------------

def lsearch():

try:

x=int(input('Enter the Number You want to search : '))

n=arr.index(x)

print ('Number Found at %d location'% (i+1))

except:

print('Number Not Exist in list')

#-----------------------------------------------------------------------------------------------------------------------------------------

def linear_search():

x=int(input('Enter the Number you want to search : '))

fl=0

for i in range(0,10):

if arr[i]==x :

fl=1

print ('Number Found at %d location'% (i+1))

break

if fl==0 :

print ('Number Not Found')

#-----------------------------------------------------------------------------------------------------------------------------------------

def binary_search():

x=int(input('Enter the Number you want to search : '))

fl=0

low=0
heigh=len(arr)

while low<=heigh :

mid=int((low+heigh)/2)

if arr[mid]==x :

fl=1

print ('Number Found at %d location'% (mid+1))

break

elif arr[mid]>x :

low=mid+1

else :

heigh=mid-1

if fl==0 :

print ('Number Not Found')

#-----------------------------------------------------------------------------------------------------------------------------------------

def min_number():

n=arr[0]

k=0

for i in range(0,10):

if arr[i]<n :

n=arr[i]

k=i

print('The Lowest number is %d '%(n))

#-----------------------------------------------------------------------------------------------------------------------------------------

def selection_sort():

for i in range(0,10):

n=arr[i]
k=i

for j in range(i+1,10):

if arr[j]<n :

n=arr[j]

k=j

arr[k]=arr[i]

arr[i]=n

#Program20: Write a Program to call great function to find greater out of entered 2 numbers.

import greatfunc

a=int(input("Enter First Number : "))

b=int(input("Enter Second Number : "))

ans=greatfunc.chknos(a, b)

print (ans)

#Program21: Write a Program to check if file is imported or not.

import importfile1 as ifile

y=ifile.x

print(y)

#Program22: Write a Program to show whether the entered number is prime or not.

no=int(input("Enter Number : "))

for i in range(2,no):

ans=no%i

if ans==0:

print ('Non Prime')

break

elif i==no-1:
print('Prime Number')

#Program23: Write a Program to show whether entered numbers are prime or not in the given range.

lower=int(input("Enter lowest number as lower bound to check : "))

upper=int(input("Enter highest number as upper bound to check: "))

for i in range(lower, upper+1):

for j in range(2, i):

ans = i % j

if ans==0:

print (i,end=' ')

break

#Program24: Write a Program to reverse the entered numbers.

no=int(input("Enter Number : "))

while no>0:

print(no % 10)

no=int(no / 10)

#Program25: 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 (s)

data1 = np.array(['a','b','c','d'])

s1 = pd.Series(data1,index=[100,101,102,103])

print (s1)
#Program26: 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])

“””Program27: Write a Program to create series using pre-defined array/ create series using user-
defined 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(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(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(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 (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 (s)

#change index in series

s=pd.Series(data,index=[1,2,3])

print (s)

#printing head and tail elements

print(s.head(2)) #displays first 2 elements

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

#Program28: Write a Program to use series with text file.

import pandas as pd

f=open("mydata.txt",'r')
contents=f.readlines()

data=[]

times=0

for line in contents:

text=line.split()

for each in text:

#print (each)

data.append(each)

times+=1

myseries=pd.Series(data)

print(myseries)

#Program29: Write a Program to show series with text file checking.

import pandas as pd

myseries=pd.Series({'Ankur':76,'Yash':45,'Harsh':82,'Shekhar':71,'Madhav':63})

print(myseries)

big=0

l=myseries.size

print (l)

for i in range(0,l):

if(myseries[i]>big):

big=myseries[i]

print (big)

#Program30: Write a Program to show series with text file searching.

import pandas as pd

f=open("mydata.txt",'r')

contents=f.readlines()
data=[]

times=0

for each in contents:

data.append(each.split())

times+=1

myseries=pd.Series(data)

print(myseries)

name = input("Enter Name to Search : ")

l=myseries.size

for i in range(0,l):

if name in myseries[i]:

print(myseries[i])

#Program31: Write a Program to show sum of even numbers till n.

sum=0

n=int(input(‘Enter number’))

for i in range(2,n+1,2):

sum=sum+i

print (i)

print (sum)

#Program32: Write a Program to show the Two Dimensional List.

x=[[10,20,30],[40,50,60],[70,80,90]]

for i in range(0,3):

for j in range(0,3):

print (x[i][j],end=' ')

print("\n")
#Program33: Write a Program to show Sum of Diagonals (major and minor) in Two Dimensional List.

r=int(input("Enter Number of Rows : "))

c=int(input("Enter Number of Columns : "))

mylist=[]

for i in range(0, r):

mylist.append([])

for i in range(0, r):

for j in range(0, c):

mylist[i].append(j)

# mylist[i][j]=0

for i in range(0, r):

for j in range(0, c):

print("Enter Value : ")

mylist[i][j]=int(input())

for i in range(0, r):

for j in range(0, c):

print (mylist[i][j], end=' ')

print("\n")

sumd1=0

sumd2=0

j=2

for i in range(0,3):

sumd1=sumd1+mylist[i][i]

sumd2=sumd2+mylist[i][j]

j=j-1

print ("The sum of diagonal 1 is : ", sumd1)

print ("The sum of diagonal 2 is : ", sumd2)


#Program34: 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 (df)

data1 = {'Name':['Rajiv', 'Sameer', 'Kapil', 'Nischay'],'Age':[28,34,29,42],


'Designation':['Accountant','Cashier','Clerk','Manager']}

df1 = pd.DataFrame(data1)

print (df1)

‘’’Program35: Write a Program to enter multiple values based data in multiple columns/rows and
show that data in python using 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(df)

print("Number of Rows and Columns")

print(df.shape)

print(df.head())

print("Tail")

print(df.tail(2))

print("Specified Number of Rows")

print(df[2:5])

print("Print Everything")
print(df[:])

print("Print Column Names")

print(df.columns)

print("Data from Individual Column")

print(df['day']) #or df.day

print(df['temperature'])

print("Maximum Temperature : ", df['temperature'].max())

print("Printing According to Condition")

print(df[df.temperature>41])

print("Printing the row with maximum temperature")

print(df[df.temperature==df.temperature.max()])

print("Printing specific columns with maximum temperature")

print(df[['day','temperature']][df.temperature==df.temperature.max()])

print("According to index")

print(df.loc[3])

print("Changing of Index")

df.set_index('day',inplace=True)

print(df)

print("Searching according to new index")

print(df.loc['01/03/2018'])

print("Resetting the Index")

df.reset_index(inplace=True)

print(df)

print("Sorting")

print(df.sort_values(by=['temperature'],ascending=False))

print("Sorting on Multiple Columns")

print(df.sort_values(by=['temperature','windspeed'],ascending=True))

print("Sorting on Multiple Columns one in ascending, another in descending")


print(df.sort_values(by=['temperature','windspeed'],ascending=[True,False]))

print("Sum Operations on Data Frame")

print(df['temperature'].sum())

print("Group By Operations")

print(df.groupby('windspeed')['temperature'].sum())

‘’’Program36: 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("To display selected number of rows from beginning")

print(df)

df=pd.read_csv("student.csv")

print(df)

print("Number of Rows and Columns")

print(df.shape)

print(df.head())

print("Tail")

print(df.tail(2))

print("Specified Number of Rows")

print(df[2:5])

print("Print Everything")

print(df[:])

print("Print Column Names")

print(df.columns)

print("Data 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[4862])

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())
‘’’Program37: 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 (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)

‘’’Program38: 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/01/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")

‘’’Program39: Write a Program to read data from data file and show Data File Handling related
functions utility in python.’’’

f=open("test.txt",'r')

print(f.name)

#f_contents=f.read()

#print(f_contents)

#f_contents=f.readlines()

#print(f_contents)

#f_contents=f.readline()

#print(f_contents)

#for line in f:

# print(line, end='')

#f_contents=f.read(50)

#print(f_contents)

size_to_read=10

f_contents=f.read(size_to_read)

while len(f_contents)>0:

print(f_contents)

print(f.tell())

f_contents=f.read(size_to_read)

‘’’Program40: Write a Program to read data from data file in append mode and use writeLines function
utility in python.’’’

af=open("test.txt",'a')
lines_of_text = ["One line of text here”, “and another line here”, “and yet another here”, “and so on and
so forth"]

af.writelines('\n' + lines_of_text)

af.close()

‘’’Program41: Write a Program to read data from data file in read mode and count the particular word
occurrences in given string, number of times in python.’’’

f=open("test.txt",'r')

read=f.readlines()

f.close()

times=0 #The variable has been created to show the number of types the loop runs

times2=0 #The variable has been created to show the number of types the loop runs

chk=input("Enter String to search : ")

count=0

for sentence in read:

line=sentence.split()

times+=1

for each in line:

line2=each

times2+=1

if chk==line2:

count+=1

print("The search String ", chk, "is present : ", count, "times")

print(times)

print(times2)

‘’’Program42: Write a Program to read data from data file in read mode and append the data in given
file in python.’’’

f=open("test.txt",'r')
read=f.readlines()

f.close()

id=[]

for ln in read:

if ln.startswith("T"):

id.append(ln)

print(id)

#Program43: Write a Program to show MySQL database connectivity in python.

import pymysql

con=pymysql.connect(host='local',user='root',password='tiger',db='test')

stmt=con.cursor()

query='select * from student;'

stmt.execute(query)

data=stmt.fetchone()

print(data)

#Program44: 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 fecth data")

S-ar putea să vă placă și