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

Final Python Journal 112

The document provides an index of programming practical assignments including creating a program to calculate when a user turns 100, checking if a number is even or odd, generating a Fibonacci series, reversing a number with a function, checking if a number is Armstrong or a palindrome with functions, and more. The assignments cover topics like functions, conditionals, loops, strings, lists, files, classes, inheritance, and exceptions. Sample code is provided for some of the assignments.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Final Python Journal 112

The document provides an index of programming practical assignments including creating a program to calculate when a user turns 100, checking if a number is even or odd, generating a Fibonacci series, reversing a number with a function, checking if a number is Armstrong or a palindrome with functions, and more. The assignments cover topics like functions, conditionals, loops, strings, lists, files, classes, inheritance, and exceptions. Sample code is provided for some of the assignments.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 51

RAJ VADHAN

53003190112

INDEX
Sr. no                                             Titles of  Practical    Page 
1.a  To create a program that asks the user to enter their name   4
and their age.Print out a message addressed to them that tells them the
year that they will turn 100 years old. 
 
1.b  To enter the number from the user and depending on whether the number  
is even or odd, print out an appropriate message to the user. 
 
1.c  To write a program to generate a  fibonacci  series.   
 
1.d  To write a function that reverses the user define value   
 
1.e  To write a function to check the input value is Armstrong and also write  
the function for Palindrome. 
 
1.f  To write a recursive function to print the factorial for a given numbers.   
2.a  To write a function that takes a character (i.e. a string of length 1) and  10
returns true if its is vowel,False otherwise. 
2.b  To write a function  that computes the length of a string or a list.   
2.c  To define  a procedure histogram() that takes a list of integers and prints a  
histogram  to the screen. For example , histogram([4,9,7]) should print the
following: 
**** 
********* 
******* 
 
3.a  To write a function to check a sentence to see if it is a pangram or not.   13
 
3.b  To write a program  that prints out all the elements of the list that are less  
than 5. 
 
     
4.a  To write a program that takes two list and returns True if they  15
have atleast one common member. 
 
4.b  To write a python program  to print a specified list after removing the list  
0th ,2nd,4th,and 5th elements. 
4.c  To write a python program to clone or copy a list   
 
5.a  To write a python script  to concatenate following dictionary to create a  17
new one. 
5.b  To write a python script  to concatenate following dictionary to create a  
new one. 
 
5.c  To write a python program to  sum all the items in a dictionary.   
6.a  To write a python program to read an entire text file   19

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
 
6.b  To write a python program to append text to a file and display the text   
6.c  To write a python program to read last n lines of a file.   
7.a  To design a class  that store the information  of student and display.   22

7.b Implement the concept of inheritance using python


7c Create a class called Numbers, which has a single class attribute called
MULTIPLIER, and a constructor which takes the parameters x and y
(these should all be numbers).

i. Write a method called add which returns the sum of the attributes x and
y.

ii. Write a class method called multiply, which takes a single number
parameter a and returns the product of a and MULTIPLIER.

iii. Write a static method called subtract, which takes two number
parameters, b and c, and returns b - c.

iv. Write a method called value which returns a tuple containing the
values of x and y. Make this method into a property, and write a setter and
a deleter for manipulating the values of x and y.

8.a. Open a new file in IDLE (“New Window” in the “File” menu) and save it 27
as geometry.py in the directory where you keep the files you create for
this course. Then copy the functions you wrote for calculating volumes
and areas in the “Control Flow and Functions” exercise into this file and
save it.

Now open a new file and save it in the same directory. You should now be
able to import your own module like this:

importgeometry

Try and add print dir(geometry) to the file and run it.

Now write a function pointyShapeVolume(x, y, squareBase) that


calculates the volume of a square pyramid if squareBase is True and of a
right circular cone if squareBase is False. x is the length of an edge on a
square if squareBase is True and the radius of a circle when squareBase is
False. y is the height of the object. First use squareBase to distinguish the
cases. Use the circleArea and squareArea from the geometry module to
calculate the base areas.

8.b. Write a program to implement exception handling.

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
9.a. Try to configure the widget with various options like: bg=”red”, 30
family=”times”, size=18.
9.b. Try to change the widget type and configuration options to experiment
with other widget types like Message, Button, Entry, Checkbutton,
Radiobutton, Scale etc.

10.a. Design a simple database application that stores the records and retrieve 34
the same.
10.b. Design a database application to search the specified record from the
database.
10.c. Design a database application to that allows the user to add, delete and
modify the records.

PYTHON
1st Practical [A]
Aim- Create a program that asks the user to enter their
name and their age. Print out a message addressed to them
that tells them the year that they will turn 100 years old.
CODE:
import datetime
name = input("Hello! Please enter your name: ")
print("Hello " + name)
age = int(input("Enter your age: "))
year_now = datetime.datetime.now()
# print(year_now.year)

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

print("You will turn 100 in " + str(int(100-age) +


int(year_now.year)))
OUTPUT:

1st Practical[B]
Aim-Enter the number from the user and depending on
whether the number is even or odd, print out an appropriate
message to the user.
CODE :
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("{0} is Even".format(num))

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

else:
print("{0} is Odd".format(num)
OUTPUT:

1st Practical [C]


AIM: Write a program to generate the Fibonacci series.
CODE:
# Program to display the Fibonacci sequence up to n-th term where n
is providedby the user

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

# change this value for a different result


nterms = 10
# uncomment to take input from the user
#nterms = int(input("How many terms? "))
# first two terms
n1 = 0
n2 = 1
count = 2
# check if the number of terms is valid
if nterms<= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence upto",nterms,":")
print(n1,",",n2,end=', ')
while count <nterms:
nth = n1 + n2
print(nth,end=' , ')
# update values
n1 = n2

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

n2 = nth
count += 1
OUTPUT:

1st Practical [D]


Aim: Write a function that reverses the user defined value.

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

CODE:
# Python Program to Reverse a Number using While loop by using function

def reverse_number(number):

reverse = 0

while(number > 0):

reminder = number %10

reverse = (reverse *10) + reminder

number = number //10

print("Reverse number is ", reverse)

reverse_number(11184756392856487)

OUTPUT:

1st practical [E]


RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

AIM: Write a function to check the input value is Armstrong


and also write the function for Palindrome.
CODE:
# Python program to check if the number provided by the user is an Armstrong number or
not

def armstrong(num):

sum=0

# find the sum of the cube of each digit

temp = num

while temp > 0:

digit = temp % 10

sum += digit ** 3

temp //= 10

# display the result

if num == sum:

print(num,"is an Armstrong number")

else:

print(num,"is not an Armstrong number")

def palindrome(num):

n = num

rev = 0

while num != 0:

rev = rev * 10

rev = rev + int(num%10)

num = int(num / 10)

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
if n == rev:

print(n,"is palindrome number")

else:

print(n,"is not a palin")

# take input from the user

num = int(input("Enter a number to chk it is armstrong or not: "))

armstrong(num)

# take input from the user

num = int(input("Enter a number to chk it is palindrome or not: "))

palindrome(num)

OUTPUT:

1st practical [F]


Aim: Write a recursive function to print the factorial for a given
number.
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

CODE:
# Python program to find the factorial of a number using recursion

def recur_factorial(n):

"""Function to return the factorial

of a number using recursion"""

if n == 1:

return n

else:

return n*recur_factorial(n-1)

#take input from the user

num = int(input("Enter a number: "))

# check is the number is negative

if num < 0:

print("Sorry, factorial does not exist for negative numbers")

elif num == 0:

print("The factorial of 0 is 1")

else:

print("The factorial of",num,"is",recur_factorial(num))

OUTPUT:

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

Practical 2[A]
A. Write a function that takes a character (i.e. a string of length 1) and
returns True if it is a vowel, False otherwise.

Code:
def find_vowel(s):

l=['a','e','i','o','u']

for i in s:

if i in l:

print('true')

else:

print('false')

s='god is great'

find_vowel(s)

OUTPUT:

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

Practical 2[B]
[B] Define a function that computes the length of a given list or string.

CODE:
def len_s(s):

count=0

for i in s:

if i !='':

count+=1

print('the total length of the string',count)

s='god is great'

len_s(s)

OUTPUT:

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

Practical 2[C]
[C] Define a procedure histogram() that takes a list of integers and prints a histogram to the
screen. For example, histogram([4, 9, 7]) should print the following:

****
*********
*******
CODE:

l = [2, 4, 5] 

def histogram(l): 

    for i in l: 

        print('*'*i) 

histogram(l) 

OUTPUT:

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

Practical 3[A]
[A] AIM: A pangram is a sentence that contains all the letters of the English
alphabet at least once, for example: The quick brown fox jumps over the lazy
dog. Your task here is to write a function to check a sentence to see if it is a
pangram or not.

CODE:

import string, sys

if sys.version_info[0] < 3:

input = raw_inp

def ispangram(sentence, alphabet=string.ascii_lowercase):

alphaset = set(alphabet)

return alphaset<= set(sentence.lower())

print ( ispangram(input('Sentence: ')) )

OUTPUT:

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

Practical 3[B]
Aim: Take a list, say for example this one: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list that are less
than 5.

CODE:
l1=[1,1,2,3,5,8,13,21,34,55,89]

l2=[]

for i in l1:

if i <5:

l2.append(i)

print (l2)

OUTPUT:

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

Practical 4[A]
AIM: Write a program that takes two lists and returns True if they have at
least one common member.

CODE:

11=[1,2,3,4,5,6,]

l2=[11,12,13,14,15,6]

for i in l1:

for j in l2:

if i==j:

print ('The 2 list have at least one common element')

OUTPUT:

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

Practical 4[B]
AIM: Write a Python program to print a specified list after removing the 0th,
2nd, 4th and 5th elements.

CODE:

1=[1,2,3,4,5,6,7,8,9,0]

print("Original List is",l1)

print("According to question we have to remove 0th->1,2nd->3,4th->5,5th->6")

l1.remove(l1[0]) #this line will remove 1 from the list, Therefore l1[0]=2

print("After Removal of 0th element Now List is",l1)

print("Now we have to remove 3 from list which is at 1th position of index")

l1.remove(l1[1])

print("After Removal of 1st element of New List (original 2nd index element)
is",l1)

print("Now we have to remove 5 from list which is at 2nd position of index")

l1.remove(l1[2])

print("After Removal of 3rd element of New List (original 4th index element)
is",l1)

print("Now we have to remove 6 from list which is at 2nd position of index")

l1.remove(l1[2])

print (l1)

OUTPUT:

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

Practical 4[C]
AIM: Write a Python program to clone or copy a list.

CODE:

11=[2, 4, 7, 8, 9, 0]

print ("Original List is", l1)

l2=l1

print ("Clone List is ",l2)

OUTPUT:

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

Practical 5[A]
AIM: Write a Python script to sort (ascending and descending) a dictionary by
value.

CODE:

released={'Python 3.6': 2017,'Python 1.0': 2002, 'Python 2.3': 2010}

for key,value in sorted(released.items()):

print (key,value)

OUTPUT:

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

Practical 5[B]
AIM: Write a Python script to concatenate following dictionaries to create a new
one.Sample Dictionary : dic1={1:10, 2:20} dic2={3:30, 4:40}
dic3={5:50,6:60}Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50,

6: 60}

CODE:

dic1={1:10,2:20}

dic2={3:30,4:40}

dic3={5:50,6:60}

dic1.update(dic2)

print (dic1)

{1: 10, 2: 20, 3: 30, 4: 40}

dic1.update(dic3)

print (dic1)

OUTPUT:

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

Practical 5[C]
AIM: Write a Python program to sum all the items in a dictionary.

CODE:

my_dict = {'data1':10,'data2':20,'data3':30}

print(sum(my_dict.values()))

OUTPUT:

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

PRACTICAL 6[A]
Write the program for the following: (File handling)

AIM: Write a Python program to read an entire text file.

CODE:

def file_read(fname):

txt = open(fname)

print(txt.read())

file_read('practical6.txt')

OUTPUT:

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

Practical 6[B]
AIM: Write a Python program to append text to a file and display the text.
CODE:

def file_read(fname):

from itertools import islice

with open(fname, "w") as myfile:

myfile.write("Python Exercises\n")

myfile.write("Java Exercises")

txt = open(fname)

print(txt.read())

file_read('practical6.txt')

OUTPUT:

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

Practical 6[C]
AIM: Write a Python program to read last n lines of a file.

CODE:

import sys

import os

def file_read_from_tail(fname,lines):

bufsize = 8192

fsize = os.stat(fname).st_size

iter = 0

with open(fname) as f:

if bufsize>fsize:

bufsize = fsize-1

data = []

while True:

iter +=1

f.seek(fsize-bufsize*iter)

data.extend(f.readlines())

if len(data) >= lines or f.tell() == 0:

print(''.join(data[-lines:]))

break

file_read_from_tail('practical6.txt',2)

OUTPUT:

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

Practical 7[A]
AIM:Design a class that store the information of student and display the

CODE:

sameclass student:

def disp(self,Name,Sapid,Gender,Course):

self.Name=Name

self.Sapid=Sapid

self.Gender=Gender

print ('Name:',Name)

print ('Sapid:',Sapid)

print ('Gender:',Gender)

print ('Course:',Course)

s1=student()

s1.disp('Mahendra Singh Bisht','53003190126','M','SYBSC-IT')

OUTPUT:

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

Practical 7[B]
AIM: Implement the concept of inheritance using python

CODE:

class Shape:

author= 'Mahendra Singh Bisht'

def _init_(self,x,y):

self.x=x

self.y=y

def area(self,x,y):

self.x=x

self.y=y

a=self.x*self.y

print ('Area of a rectangle',a)

print (author)

class Square(Shape): #class Square inherits class Shape.

def _init_(self,x):

self.x=x

def area(self,x):

self.x=x

a= self.x*self.x

print('Area of a square',a)

OUTPUT:

class Shape: 
    def _init_(self,x,y): 
        self.x=x 
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
        self.y=y 
    def area(self,x,y): 
        self.x=x 
        self.y=y 
        a=self.x*self.y 
        print('Area of a rectangle',a); 
 
class Square(Shape): 
    def _init_(self,x): 
        self.x=x 
    def area(self,x): 
        self.x=x 
        a= self.x*self.x 
        print('Area of a square',a) 
 
 
r=Shape() 
r.area(12,34) 
s=Square() 
s.area(34) 
 
Output:- 

 
 
 
 
 

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

Practical 7[C]
AIM:. Create a class called Numbers, which has a single class attribute called
MULTIPLIER, and a constructor which takes the parameters x and y (these
should all be numbers).  
Write a method called add which returns the sum of the attributes x and y.  
Write a class method called multiply, which takes a single number parameter a
and returns the product of a and MULTIPLIER. 
Write a static method called subtract, which takes two number parameters, b
and c, and returns b - c. 
Write a method called value which returns a tuple containing the values of x and
y. Make this method into a property, and write a setter and a deleter for
manipulating the values of x and y. 

CODE:

class Numbers(object): 
    def _init_(self,x,y): 
        self.x=x 
        self.y=y 
    def add(self,x, y): 
        self.x=x 
        self.y=y 
        return self.x+self.y 
    def multiply(self,x): 
        MULTIPLIER=7.4 
        self.x=x 
        return self.x*MULTIPLIER 
    @staticmethod 
    def subtract(self,x,y): 
        self.x=x 
        self.y=y 
        return self.x-self.y 
 
OUTPUT:

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

Practical 8[A]
AIM:

Open a new file in IDLE (“New Window” in the “File” menu) and save it as
geometry.py in the directory where you keep the files you create for this course.
Then copy the functions you wrote for calculating volumes and areas in the
“Control Flow and Functions” exercise into this file and save it.

Now open a new file and save it in the same directory. You should now be able
to import your own module like this:

importgeometry

Try and add print dir(geometry) to the file and run it.

Now write a function pointyShapeVolume(x, y, squareBase) that calculates the


volume of a square pyramid if squareBase is True and of a right circular cone if
squareBase is False. x is the length of an edge on a square if squareBase is True
and the radius of a circle when squareBase is False. y is the height of the object.
First use squareBase to distinguish the cases. Use the circleArea and squareArea
from the geometry module to calculate the base areas.

CODE:

geometry.py

def circleArea(r):

PI = 3.142

return PI * (r*r);

def squareArea(s):

return s*s;

main.py

import geometry

def pointyShapeVolume(x, h, square):

if square:

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
base = geometry.squareArea(x)

else:

base = geometry.circleArea(x)

return (h * base / 3.0)

print("Area of Circle:",geometry.circleArea(2))

print("Area of Square:",geometry.squareArea(2))

print (dir (geometry))

print (pointyShapeVolume(4, 2, True))

print (pointyShapeVolume(4, 2, False))

OUTPUT:

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

Practical 8[B]
AIM:

Write a program to implement exception handling.

CODE:

class InvalidData(Exception):

def __init__(self, data):

self.data=data

def errorMsg(self):

print("Invalid data, your number must be in range of 10 to 20 ")

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

v=InvalidData(number)

try:

if number<10 or number>20:

raise v

except InvalidData:

print(v.errorMsg())

print("user defined exception")

OUTPUT:

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

Practical 9[A]

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
AIM: Try to configure the widget with various options like: bg=”red”,
family=”times”, size=18.

CODE:

import tkinter

from tkinter import *

root=Tk()

O=Canvas(root,bg="sky blue", width=250, height=300)

n = Label(root,text="Welcome",font=('Verdana',20))

O.pack()

n.pack()

root.mainloop()

OUTPUT:

Practical 9[B]

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
AIM: Try to change the widget type and configuration options to experiment
with other widget types like Message, Button, Entry, Checkbutton, Radiobutton,
Scale etc.

CODE:

import tkinter as t

import tkinter.font as f

mf=t.Tk()

mf.geometry('100x100')

fnt=f.Font(family="Arial",size=10, weight="bold", slant="italic")

#message

msgctrl = t.Message(mf, text = "Happy Diwali!")

msgctrl.config(bg='pink', font=('Calibri', 24, 'italic'),)

msgctrl.grid(row=0,column=3)

#entry#Label

lbl1 = t.Label(mf, text="Enter your name:")

lbl1.grid(row=1,column=2)

e1=t.Entry(mf,text="Enter the name",relief='ridge',


foreground="#00ff00",background='#008080')

e1.grid(row=1,column=3)

# text box

#Label

lbl2 = t.Label(mf, text="Enter your address:")

lbl2.grid(row=2,column=2)

txt1=t.Text(mf,height=5, width=20)

txt1.grid(row=2,column=3)

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
#radiobutton

#Label

lbl3 = t.Label(mf, text="Select Gender:")

lbl3.grid(row=4,column=2)

def rb_show():

print('Radio btn1 ',rv1.get())

rv1 = t.IntVar()

#rv1.set(1)

rb1 = t.Radiobutton(mf, text="Male", command=rb_show, variable=rv1


,value=1)

#rv2 = t.IntVar()

rb2 = t.Radiobutton(mf, text="Female ", command=rb_show, variable=rv1,


value=2)

rb1.grid(row=4,column=3)

rb2.grid(row=4,column=4)

#checkbox code

#Label

lbl3 = t.Label(mf, text="Select Hobby:")

lbl3.grid(row=5,column=2)

v1=t.BooleanVar()

chk1=t.Checkbutton(mf,text='Singing', onvalue=1, variable=v1)

v2=t.IntVar()

chk2=t.Checkbutton(mf,text="Dancing", variable=v2)

v3=t.IntVar()

chk3=t.Checkbutton(mf,text="Reading", variable=v3)

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
chk1.grid(row=5,column=3)

chk2.grid(row=5,column=4)

chk3.grid(row=5,column=5)

# button demo

def disp():

print("saved the content")

b1=t.Button(mf, text="Save", command=disp, relief='raised', width=10,


font=fnt)

b1.grid(row=7,column=3)

mf.mainloop()

Output:

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

Practical 10[A]
AIM: Design a simple database application that stores the records and retrieve the same.

CODE:
import mysql.connector

db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='n it')

# prepare a cursor object using cursor() method cursor = db.cursor()

# Drop table if it already exist using execute() method.

cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")

# Create table as per requirement

sql = """CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL,

LAST_NAME CHAR(20),

AGE INT,

SEX CHAR(1), INCOME FLOAT )""" cursor.execute(sql)

print("Table Created Successfully");

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
# disconnect from server
db.close()

import mysql.connector

db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='p
ython_mysql')

# prepare a cursor object using cursor() method cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database. sql = """INSERT INTO
EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME)

VALUES ('Nitesh', 'Shukla', 23, 'M', 20000)""" try:

# Execute the SQL command

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
cursor.execute(sql) print ("Data Inserted Successfully...!") # Commit your changes in the
database db.commit() except:

# Rollback in case there is any error db.rollback()

# disconnect from server db.close()

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

Practical 10[B]
AIM:Design a database application to search the specified record from the database.

CODE:
import mysql.connector

db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='n it')

# prepare a cursor object using cursor() method cursor = db.cursor()

sql = "SELECT * FROM EMPLOYEE \

WHERE INCOME > '%d'" % (1000) try:

# Execute the SQL command

cursor.execute(sql)

# Fetch all the rows in a list of lists. results = cursor.fetchall() for row in results:

fname = row[0] lname = row[1] age = row[2] sex = row[3] income = row[4]

# Now print fetched result

print ("Fname=%s,Lname=%s,Age=%d,Sex=%s,Income=%d" % \

(fname, lname, age, sex, income )) except: print ("Error: unable to fecth data")

# disconnect from server

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
db.close()

Practical 10[C]
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
AIM: Design a database application to that allows the user to add, delete and modify the
records. DataAdd.py

CODE:
import mysql.connector

db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='n it')

# prepare a cursor object using cursor() method cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.

sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \

LAST_NAME, AGE, SEX, INCOME) \

VALUES ('%s', '%s', '%d', '%c', '%d' )" % \ ('Ashwin', 'Mehta', 23, 'M', 22000) try:

# Execute the SQL command cursor.execute(sql) print("Data Added Successfully") #


Commit your changes in the database db.commit() except:

# Rollback in case there is any error

db.rollback() # disconnect from server

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
db.close()

Delete.py import mysql.connector

db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='n it')

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
# prepare a cursor object using cursor() method cursor = db.cursor()

# Prepare SQL query to UPDATE required records sql = "DELETE FROM EMPLOYEE WHERE
AGE < '%d'" % (20) try:

# Execute the SQL command

cursor.execute(sql) print "Data Deleted SuccessFully..!" # Commit your changes in the


database db.commit() except:

# Rollback in case there is any error db.rollback()

# disconnect from server db.close()

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

Update.py

import mysql.connector

db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='n it')

# prepare a cursor object using cursor() method cursor = db.cursor()

# Prepare SQL query to UPDATE required records sql = "DELETE FROM EMPLOYEE WHERE
AGE < '%d'" % (20) try:

# Execute the SQL command

cursor.execute(sql) print ("Data Deleted SuccessFully..!") # Commit your changes in the


database db.commit() except:

# Rollback in case there is any error db.rollback()

# disconnect from server

db.close()

RAJ VADHAN
53003190112
RAJ VADHAN
53003190112

RAJ VADHAN
53003190112

You might also like