You are on page 1of 53

EX.

NO : 01 READ A TEXT FILE LINE BY LINE AND DISPLAY EACH WORD


DATE: SEPARATED BY A #.

Aim:
To write Python Program to Read a text file line by line and display each word
separated by a #.

Algorithm:
Step 1: Start

Step 2: Open text file in read mode

Step 3: Create string variable

Step 4: Inside of string variable read text file by using of readlines() function.

Step 5: Inside of the looping statements split lines into words using split() then add
string “#” to each word and print.

Step 6: Close text file.

Step 7: Stop

Program:

filein = open("C:\Program Files\Python38\story.txt",'r')


line =" "
while line:
line = filein.readline()
for w in line:
if w == ' ':
print('#',end = '')
else:
print(w,end = '')
filein.close()

1
Input Text File :

OUTPUT:

Result:
Thus the Python program to Read a text file line by line and display each word
separated by a # is executed successfully and the output is verified.

2
EX.NO : 02 READ A TEXT FILE AND DISPLAY THE NUMBER OF VOWELS
DATE: /CONSONANTS /UPPERCASE/LOWERCASE CHARACTERS IN THE
FILE.

Aim:
To write Python Program to read a text file and display the number of vowels/
consonants/uppercase/lowercase characters in the file.
Algorithm:
Step 1: Start

Step 2: Open text file in read mode using open() method

Step 3: Read the content of the file using read() method

Step 4:Write the logic for counting the Vowels,Consonants,Upper case letters,Lower
case letters using islower(),isupper(),ch in [‘a’,’e’,’i’,’o’,’u’], ch in
['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']

Step 5: Close the file using close() method

Step 6: Print the Counting data.

Step 7: Stop

Program:
def cnt():
f=open("C:\\Users\\DSPS ONLINE 01\\Desktop\\DAWN.txt","r")
cont=f.read()
print(cnt)
v=0
cons=0
l_c_l=0
u_c_l=0
for ch in cont:
if (ch.islower()):
l_c_l+=1
elif(ch.isupper()):

3
u_c_l+=1
ch=ch.lower()
if( ch in ['a','e','i','o','u']):
v+=1
elif (ch in ['b','c','d','f','g',
'h','j','k','l','m',
'n','p','q','r','s',
't','v','w','x','y','z']):
cons+=1
f.close()
print("Vowels are : ",v)
print("consonants are : ",cons)
print("Lower case letters are : ",l_c_l)
print("Upper case letters are : ",u_c_l)
#main program
cnt()

Input Text File :

4
OUTPUT:

Result:
Thus the Python program to read a text file and display the number of vowels/
consonants/uppercase/lowercase characters in the file is executed successfully and the
output is verified.

5
EX.NO : 03 REMOVE ALL THE LINES THAT CONTAIN THE CHARACTER 'A'
DATE: IN A FILE AND WRITE IT TO ANOTHER FILE.

Aim:
To write Python Program to remove all the lines that contain the character 'a' in a file
and write it to another file.
Algorithm:
Step 1: Start
Step 2: Open old text file that contain original text lines in read mode
Step 3: read new text file line by line using .readlines() function
Step 4: Inside of string variable read text file by using of readlines() function.
Step 5: inside of the looping statement check if the line not contain ‘a’ then write that line to
new text file.
Step 6: Close old and new text file
Step 7: Stop

Program:

fin=open("C:\\Users\\DSPS ONLINE 01\\Desktop \\old.txt","r")


fout=open("C:\\Users\\DSPS ONLINE 01\\Desktop \\new.txt","a")
s=fin.readlines()
for j in s:
if 'a' not in j:
fout.write(j)
fin.close()
fout.close()

6
Input Text File :

OUTPUT:
After Python Program Execution (new.txt) file contain text after remove all the lines that contain
‘a’ :

Result:
Thus the Python Program to remove all the lines that contain the character 'a' in a file
and write it to another file is executed successfully and the output is verified.

7
EX.NO : 04 WRITE A PYTHON PROGRAM TO CREATE A BINARY FILE WITH
DATE: NAME AND ROLL NUMBER AND PERFORM SEARCH BASED ON
ROLL NUMBER.

Aim:
To write a python program to create a binary file with name and roll number and
perform search based on roll number.

Algorithm:
Algorithm:
Step 1: Start
Step 2: Create a User defined function write() and open the file in write mode.
2.1 create an empty list insid write() and use while loopwith condition as True
2.2 Get the no.of students as an input from the user
2.3 Take the student data as input from user using for loop and
Step 3: Create a list having student data that is inserted using For loop in step:2 and to
existing list using append()
Step 4: Based on the choice of input from the user, loop either continues to work or stops its
Execution.
Step6: Save this list of students in binary file using dump method
file=open(“pathoffile”,”wb”),pickle.dump(list_of_students, file)
Step 7: Read the rollno from user to search
Step 8:Create a User defined function search() and read the rollno from user to search
Step 9: open the file in read mode and use load () method to get the list_of_students object
that we have stored in step4 file=open (“pathfile”,”rb”) list_of_students =pickle.load(file)
Step 10: Search into the list_of_students for given rollno
Step 11: Create a user defined function read() to display the information from the file. Stepp
12: call write (), read (), search ()

Program:
import pickle
def write():
f=open("C:\\Users\\DSPS ONLINE 01\\Desktop\\dawn.dat","wb")
record=[]
while True:
rno=int(input("Enter the rollno:"))
name=input("Enter the name:")
8
marks=int(input("Enter the marks:"))
d=[rno,name,marks]
record.append(d)
ch=input("Do you want to enter more records?(y/n)")
if ch=="n" or ch=="N":
break
pickle.dump(record,f)
print("Records written successfully")
f.close()

# Search based on the roll number


def search():
f=open("C:\\Users\\DSPS ONLINE 01\\Desktop\\dawn.dat","rb")
s=pickle.load(f)
#print(s)
rno=int(input("Enter the rollno to be searched.."))
found=0
for i in s:
if i[0]==rno:
print("Record found successfully")
print(i)
found=1
if found==0:
print("Record not found ....Please try again...")

# function to read the content of binary file


def read():
print("LIST OF STUDENT DETAILS :")
print("******************************")
f=open("C:\\Users\\DSPS ONLINE 01\\Desktop\\dawn.dat", "rb")
s=pickle.load(f)
for i in s:
print(i)
y=True
while (y==True):
print("Enter your choice no 1.Insert, 2. search, 3. read, 4.exit")
x=int(input())
if x==1:
write()
elif x==2:
search()
elif x==3:
read()

9
elif x==4:
break
else:
print("enter valid input")

OUTPUT:

Result:
Thus the Python program to create a binary file with name and roll number and
perform search based on roll number is executed successfully and the output is verified.

10
EX.NO : 05 WRITE A PYTHON PROGRAM TO CREATE A BINARY FILE WITH
DATE: ROLL NUMBER, NAME AND MARKS AND UPDATE THE MARKS
USING THEIR ROLL NUMBERS.
Aim:
To write a python program to create a binary file with roll number, name and marks
and update the marks using their roll numbers.
Algorithm:
Step 1: Start
Step 2: Create a User defined function write() and open the file in write mode.
2.1 create an empty list insid write() and use while loopwith condition as True
2.2 Get the no.of students as an input from the user
2.3 Take the student data as input from user using for loop and
Step 3: Create a list having student data that is inserted using for loop in step:2 and to
existing list using append()
Step 4: Based on the choice of input from the user ,loop either continues to work or stops its
Execution.
Step5: Save this list of students in binary file using dump method
file=open(“pathoffile”,”wb”),pickle.dump(list_of_students, file)
Step 6: Create a user defined function update() and open the file in rb+(read and write)mode
and Use load() method to get the list_of_students object that we have stored in step 5
File=open(“Binaryfile.dat”,”rb+”)List_of_students=pickle.load(file)
Step 7: Initialize a variable found=0.
7.1 Get the input from the user for rollno.
7.2 Use for loop to iterate the file contents.
7.3 Place an if condition to check for rollno in the file matches with the input provided
by the user,if it matches then current marks can be modified with new marks.
7.4 After updating,reassign variable found=1
Step 8: Use f.seek(0) to place the file pointer at the start of the file and dump() to update the
content in the file.
Step 9: Create a user defined function read() to display the information from the file.
Step 10: call write (), read (), update ()
Step11:Stop

Program:
import pickle
def write():
f=open("C:\\Users\\DSPS ONLINE 01\\Desktop\\dawn1.dat","wb")
record=[]
11
while True:
rno=int(input("Enter roll no:"))
name=input("Enter name:")
marks=int(input("Enter marks:"))
data=[rno,name,marks]
record.append(data)
ch=input("Do you want to enter more records?(y/n)")
if ch=='n':
break
pickle.dump(record,f)
print("data written successfully")

def read():
f=open("C:\\Users\\DSPS ONLINE 01\\Desktop\\dawn1.dat","rb")
s=pickle.load(f)
print("STUDENT DETAILS")
print("***************")
for i in s:
print(i)

def update():
f=open("C:\\Users\\DSPS ONLINE 01\\Desktop\\dawn1.dat","rb+")
print("\n")
s=pickle.load(f)
found=0
rno=int(input("Enter rollno whose record you want to update:"))
for i in s:
if rno==i[0]:
print("current marks :",i[2])
i[2]=int(input("enter new marks:"))
found=1
break
if found==0:
print("record not found..please try again")

else:
f.seek(0)
pickle.dump(s,f)
print("records updated successfully")
f.close()
y=True
while (y==True):
print("Enter your choice no 1.Insert, 2. read(), 3.Update, 4.exit")
x=int(input())
12
EX.NO : 06 RANDOM NUMBER GENERATION THAT GENERATES RANDOM
DATE: NUMBERS BETWEEN 1 TO 6 (SIMULATES A DICE).
if x==1:
write()
elif x==2:
read()
elif x==3:
update()
elif x==4:
break
else:
print("enter valid input")

OUTPUT:

Result:
Thus the python program to create a binary file with roll number, name and marks
and update the marks using their roll numbers is executed successfully and the output is
verified.

13
EX.NO : 07 TAKE A SAMPLE OF TEN PHISHING E-MAILS (OR ANY TEXT
DATE: FILE) AND FIND MOST COMMONLY OCCURRING WORD(S)
USING PYTHON PROGRAM.
Aim:
To write a python program to random number generation that generates random
numbers between 1 to 6 (simulates a dice).
Algorithm:
Step 1: Start
Step 2: Import random module
Step 3: Under while loop write a random number generate that will generate number from 1
to 6 using randint() method.
Step 4: Print the random generate number
Step 5: Stop

Program:
import random
while(True):
choice=input("Enter 'r' to roll dice or press any other key to quit: ")
if(choice!="r"):
break
n=random.randint(1,6)
print(n)

OUTPUT:

Result:
Thus the python program to random number generation that generates random numbers
between 1 to 6 (simulates a dice) is executed successfully and the output is verified.

14
Aim:
To write Python Program to Take a sample of ten phishing e-mails (or any text file)
and find most commonly occurring word(s).
Algorithm:
Step 1: Start
Step 2: import collections library
Step 3: Inside of a variable, open email text file in read mode.
Step 4: read file and using. read() function and assign read value to variable.
Step 5: create empty dictionary
Step 6: convert all the words in the text file into lowercase and split each word
Step 7: Replace all the special symbols
Step 8: Add each different word and count no.of times its occurrence into the dictionary.
Step 9: Print most frequent word used in the mail as.
Step 10: Close text file.
Step 11: Stop.

Program:
import collections
fin = open("C:\\Users\\DSPS ONLINE 01\\Desktop\\email.txt",'r')
a= fin.read()
d={ }
L=a.lower().split()
for word in L:
word = word.replace(".","")
word = word.replace(",","")
word = word.replace(":","")
word = word.replace("\"","")
word = word.replace("!","")

15
word = word.replace("&","")
word = word.replace("*","")
for k in L:
key=k
if key not in d:
count=L.count(key)
d[key]=count
n_print = int(input("How many most common words to print: "))
print("\nOK. The {} most common words are as follows\n".format(n_print))
word_counter = collections.Counter(d)
for word, count in word_counter.most_common(n_print):
print(word, ": ", count)
fin.close()

SAMPLE TEXT FILE:

OUTPUT:
16
EX.NO : 08 A PYTHON PROGRAM USING FUNCTION TO FIND THE
DATE: FACTORIAL OF A NATURAL NUMBER.

Result:
Thus the python program to take a sample of ten phishing e-mails (or any text file)
and find most commonly occurring word(s) is executed successfully and the output is
verified.

17
EX.NO : 09 A MENU DRIVEN PROGRAM IN PYTHON USING USER DEFINED
DATE: FUNCTION THAT TAKE A LIST AS PARAMETER AND RETURN
MAXIMUM, MINIMUM AND SUM OF THE ELEMENTS IN A LIST.
Aim:
To Write a Python program using function to find the factorial of a natural number.
Algorithm:
Step 1: Start
Step 2: Create user defined function name factorial write following steps Initialize counter
variable i to 1 and fact to 1
Write for loop range(1,n+1) Calculate fact=fact*i
Return fact
Step 3: Read x value from user. Step 4: Call the factorial()
Step 5: Print the result.
Step 6: Stop

Program:
def factorial(n):
fact=1
for i in range(1,n+1):
fact=fact*i
return fact
x=int(input("Enter number: "))
result=factorial (x)
print("Factorial of " ,x, " is :", result) (n)

OUTPUT:

Result:
Thus the python program using function to find the factorial of a natural number is
executed successfully and the output is verified.

Aim:

18
To write a menu driven program in python using user defined function that take a list
as parameter and return maximum, minimum and sum of the elements in a list.
Algorithm:
Step 1: Start
Step 2: Create user defined function named max_check and pass list as a parameter.
2.1 Assign the value from index 0 into variable named “max_check”.
2.2 Use for loop to iterate over elements of a list
2.3 Use if statement to check for maximum number and return a value.
STEP 3: Create user defined function named min_check and pass list as a parameter.
3.1 Assign the value from index 0 into variable named “min_check”.
3.2 Use for loop to iterate over elements of a list
3.3 Use if statement to check for minimum number and return a value.
STEP 4: Create user defined function named sum_list and pass list as a parameter.
4.1 Initialize a variable named sum_numbers=0
4.2 Use for loop to iterate over elements of a list
4.3 Add the elements of list and return a value.
STEP 5: Create an empty list using list()
STEP 6: Get the size of list and the elements of list as input from the user.
STEP 7:Use for loop to add the elements in to list using append().
STEP 8: call the function max_check(),min_check() ,sum_list().
STEP 9:Print the result.
STEP 10:Stop.

Program:
#Pass a list to this function to check for maximum number
def max_check(x):
max_val=x[0]
for check in x:
if check>max_val:
max_val=check
return max_val
#Pass a list to this function to check for minimum number
def min_check(x):
min_val=x[0]
for check in x:
if check<min_val:

19
min_val=check
return min_val
#Pass a list to this function to find sum of elements in list
def sum_list(A):
sum_numbers=0
for x in A:
sum_numbers+=x
return sum_numbers
#List
A=list()
n=int(input("Enter the size of the List:"))
print("Enter the Elements:")
for i in range(int(n)):
k=int(input(""))
A.append(k)
while (True):
x=int(input("Enter your choice 1.Find Maximum in the list,2.Find Maximum in the
list,3.Find the Sum of the elements in the list,4.Exit:\n"))
if x==1:
p=max_check(A)
print("Maximum of the List :",p)
elif x==2:
q=min_check(A)
print("Minimum of the List :",q)
elif x==3:
r=sum_list(A)
print("Sum of elements in List:",r)
elif x==4:
break
else:
print("Enter Valid option")print("Factorial of " ,x, " is :", result) (n)

OUTPUT:

20
EX.NO : 10 A FUNCTION WHICH TAKES N AS AN ARGUMENT AND PRINT
DATE: FIBONACCI NUMBERS UP TO N

Result:
Thus the menu driven program in python using user defined function that take a list
as parameter and return maximum, minimum and sum of the elements in a list is executed
successfully and the output is verified.

21
Aim:
To write a function which takes n as an argument and print Fibonacci numbers up to
n.
Algorithm:
Step 1: Start
Step 2: Create user defined function name Fibonacci(n) write following steps
• Initialize counter variable a=0 and b=1
• If n < 0 return invalid input
• If n =0 return 0
• If n=1 return 1 else
• run for loop range(n-2)
• compute next number in series: c=a+b
• swap a=b
• b=c
• Return b value
Step 3: Read x value from user.
Step 4: Call the function fibonacci(x)
Step 5: Print the nth Fibonacci series.
Step 6: Stop

Program:
def fibonacci(n):
a=0
b=1
if n<0:
print ("incorrect input:")
elif n==0:
print(a)
return a
elif n==1:
print(a,b)
return b
else:
print(a,b,end=" ")
for i in range(n-2):
c=a+b
print(c,end=" ")
22
EX.NO : 11 A PYTHON PROGRAM TO IMPLEMENT PYTHON
DATE: MATHEMATICAL FUNCTIONS.
a=b
b=c
return b
print("*Printing Fibonacci Series*")
x=int(input("How many numbers you want to display : "))
print("The Fibonacci Series is: ")
fibonacci(x)

OUTPUT:

Result:
Thus the python program a function which takes n as an argument and print
Fibonacci numbers up to n is executed successfully and the output is verified.

Aim:
23
EX.NO : 12 A PYTHON PROGRAM TO MAKE USER DEFINED MODULE AND
DATE: IMPORT SAME IN ANOTHER MODULE OR PROGRAM.
To write a Python program to implement python mathematical functions.
Algorithm:
Step 1: Start
Step 2: Import math module
Step 3: perform operation by calling functions inside of math module
Step 4: Stop
Program:
import math
print("The value of 5^8: " + str(math.pow(5, 8)))
print("Square root of 786: " + str(math.sqrt(786)))
print("The value of 6^e: " + str(math.exp(6)))
print("The value of log(722), base 5: " + str(math.log(722, 5)))
print('The Floor value of 6.25 are:' + str(math.floor(6.25)))
print('The Ceiling value of 6.25 are:' + str(math.ceil(6.25)))
print('Absolute value of -94 and 54 are:',str(math.fabs(-94)),str(math.fabs(54)))
print("The value of sin(45 degree): " + str(math.sin(math.radians(45))))

OUTPUT:

Result:
Thus the Python program to implement Python mathematical functions is executed
successfully and the output is verified.

Aim:

24
To write a Python program to make user defined module and import same in another
module or program.
Algorithm:
Step 1: Start
Step 2: Create module and store with .py extension
Step 3: Create new python program and import existing module
Step 4: Call function available in existing imported module.
Step.5: Stop
Program:
#ex12a
#code to calculate Area of Square
def Square():
number=int(input("Enter the length of one side:"))
area=number*number
print("Area of Square:",area)

#ex12b
#code to calculate Area of Rectangle
def Rectangle():
l=int(input("Enter the Length: "))
b=int(input("Enter the Breadth: "))
area=l*b
print("Area of Rectangle:" ,area)

#ex12c , in this program only we import existing module ex12a and ex12b
import ex12a,ex12b
print("**********************")
print("Area of Square")
print("**********************")
ex12a.Square()
print("\n")
print("**********************")
print("Area of Recatngle")
print("**********************")
ex12b.Rectangle()

OUTPUT:

25
EX.NO : 13 A PYTHON PROGRAM TO ENTER THE STRING AND TO CHECK
DATE: IF IT’S PALINDROME OR NOT USING LOOP

Result:
Thus the Python program to make user defined module and import same in another module
or program is executed successfully and the output is verified.

Aim:
26
EX.NO : 14 A PYTHON PROGRAM THAT COUNTS THE NUMBER OF
DATE: ALPHABETS AND DIGITS,UPPERCASE LETTERS, LOWERCASE
To Write a Python program to enter the string and to check if it’s palindrome or not
using loop.
Algorithm:
Step 1: Start
Step 2: Get input as string
Step 3: Check string==reverse of string
Step 4: if string==reverse of string condition is true then print String is Palindrome else
print String is not palindrome
Step 5: Stop

Program:
def ispalindrome(s):
return s==s[::-1]
s=str(input("Enter your string :\n"))
ans=ispalindrome(s)
if ans:
print("Entered String is Palindrome")
else:
print("Entered String is Not Palindrome")

OUTPUT:

Result:
Thus the Python program to enter the string and to check if it’s palindrome or not using
loop is executed successfully and the output is verified.

Aim:

27
To Write a Python program that counts the number of alphabets and digits, uppercase
letters, lowercase
Algorithm:
Step 1: Start
Step 2: Create Count Character function with for loop that counts upper, lower and special
characters
Step 3: Get input as string
Step 4: Call count character function and pass input string as a parameter
Step 5: return upper, lower and special character count to where the function is called
Step 6: Print upper, lower and special character count of inputted string.

Program:
def count_chars(str):
upper_ctr, lower_ctr, number_ctr, special_ctr = 0, 0, 0, 0
for i in range(len(str)):
if str[i] >= 'A' and str[i] <= 'Z': upper_ctr += 1
elif str[i] >= 'a' and str[i] <= 'z': lower_ctr += 1
elif str[i] >= '0' and str[i] <= '9': number_ctr += 1
else: special_ctr += 1
return upper_ctr, lower_ctr, number_ctr, special_ctr

str = str(input("Enter Your string: \n"))


print("Original Substrings:",str)
u, l, n, s = count_chars(str)
print('\nUpper case characters: ',u)
print('Lower case characters: ',l)
print('Number case: ',n)
print('Special case characters: ',s)

OUTPUT:

28
Result:
Thus the Python program that counts the number of alphabets and digits, uppercase letters,
lowercase is executed successfully and the output is verified.

29
EX.NO : 15 A MENU DRIVEN PROGRAM IN PYTHON TO INSERT, DELETE
DATE: NAME OF A STUDENT,PHONE NUMBER FROM DICTIONARY
AND TO SEARCH PHONE NO OF A STUDENT BY STUDENT
NAME.

Aim:
To write a menu driven program in python to insert, delete name of a student, phone
number from dictionary and to search phone no of a student by student name.
Program:
phonebook=dict()
while True:
print("******MENU\*******n")
print('1:Inserting name and phone number to Phonebook/Dictionary')
print('2:Deleting data to Phonebook/Dictionary')
print('3:Search Phone number using name from Phonebook/Dictionary')
print('4:Exit\n')
ch=int(input('Enter your choice:'))
if ch==1:
n=int(input("Enter total number of friends:"))
i=1
while(i<=n):
a=input("enter name :")
b=int(input("enter phone number:"))
phonebook[a]=b
i=i+1
print(phonebook)
print('---------------------------------')
if ch==2:
name=input("Enter name to delete:")
del phonebook[name]
k=phonebook.keys()
print("Phonebook Information")
print('---------------------')
print("Name",'\t',"Phone number")
for i in k:
print(i,'\t',phonebook[i])
if ch==3:
name=input("Enter name to search:")
f=0
k=phonebook.keys()
for i in k:
if(i==name):
print("Phone number= ",phonebook[i])
f=1
30
if (f==0):
print("Given name not exist")

if ch==4:
break

OUTPUT:

Result:
Thus the menu driven program in python to insert, delete name of a student, phone
number from dictionary and to search phone no of a student by student name is executed
successfully and the output is verified.

31
EX.NO : 16 A PYTHON PROGRAM TO IMPLEMENT A STACK USING LIST
DATE: (PUSH, POP AND PEEK OPERATION ON STACK).
Aim:
To Write a Python program to implement a stack using list (PUSH, POP and PEEK
Operation on Stack).

Algorithm:
Step 1: To create an empty stack for storing elements
Step 2: Insert elements up to the stack is full
Step 3: If the stack is full, not possible to insert the element
Step 4: To remove an element at a time if the stack has element
Step 5: If the stack has no elements, not possible to remove any element
Step 6: While on insertion each element to be stored at top of the stack
Step 7: While on removing an element then remove the element from top of the stack
Program:
def isEmpty(s):
if len(s)==0:
return True
else:
return False

def push(s,item):
s.append(item)
top=len(s)-1

def pop(s):
if isEmpty(s):
return 'Underflow occurs'
else:
val=s.pop()
if len(s)==0:
top=None
else:
top=len(s)-1
return val

def peek(s):
if isEmpty(s):
return 'Underflow occurs'
else:
32
top=len(s)-1
return s[top]

def show(s):
if isEmpty(s):
print('no item found')
else:
t=len(s)-1
print(s[t],"<-top")
for i in range(t-1,-1,-1):
print(s[i])

s=[]
top=None
while True:
print('****** STACK IMPLEMENTATION USING LIST ******')
print('1: PUSH')
print('2: POP')
print('3: PEEK')
print('4: Show')

print('0: Exit')
ch=int(input('Enter choice:'))
if ch==1:
val=int(input('Enter no to push:'))
push(s,val)
elif ch==2:
val=pop(s)
if val=='Underflow':
print('Stack is empty')
else:
print('\nDeleted item is:',val)
elif ch==3:
val=peek(s)
if val=='Underflow':
print('Stack is empty')
else:
print('\nTop item is:',val)
elif ch==4:
show(s)
elif ch==0:
print('Bye')
break

33
OUTPUT:

Result:

34
Thus the Python program to implement a stack using list (PUSH, POP and PEEK Operation on
Stack) is executed successfully and the output is verified.

EX.NO : 17 A PYTHON PROGRAM TO IMPLEMENT A STACK FOR STUDENT-


DATE: DETAILS

Aim:

To write a Python program to implement a stack for student-details

Algorithm:
Step 1: To create an empty stack for storing Student details.
Step 2: Insert elements up to the stack is full
Step 3: If the stack is full, not possible to insert the Student details
Step 4: To remove a Student detail at a time if the stack has element
Step 5: If the stack has no Student detail, not possible to remove any Student detail
Step 6: While on insertion each Student details to be stored at top of the stack
Step 7: While on removing a Student details then remove the Student details from top of the
stack
Step 8: Stop
Program:
def isEmpty(stk):
if stk == []:
return True
else:
return False

def add(stk,item):
stk.append(item)
top = len(stk)-1

def remove(stk):
if(stk==[]):
print("Stack empty;UNderflow")
35
else:
print("Deleted student is :",stk.pop())

def display(stk):
if isEmpty(stk):
print("Stack empty ")
else :
top = len(stk)-1
print(stk[top],"<-top")
for a in range(top-1,-1,-1):
print(stk[a])
stack=[]
top = None
while True:
print("STACK OPERATION:")
print("1.ADD student")
print("2.Display stack")
print("3.Remove student")
print("4.Exit")
ch = int(input("Enter your choice(1-4):"))
if ch==1:
rno = int(input("Enter Roll no to be inserted :"))
sname = input("Enter Student name to be inserted :")
item = [rno,sname]
add(stack,item)
input()
elif ch==2:
display(stack)
input()
elif ch==3:
remove(stack)
input()
elif ch==4:
break
else:
print("Invalid choice ")
input()

OUTPUT:

36
37
EX.NO : 18 EACH NODE OF STACK CONTAINS THE FOLLOWING
DATE: INFORMATION :
I) PIN CODE OF A CITY II) NAME OF CITY
WRITE A PYTHON PROGRAM TO IMPLEMENT FOLLOWING
OPERATIONS IN ABOVE STACK
A) PUSH() TO PUSH A NODE INTO A STACK
B) POP() TO REMOVE A NODE FROM STACK

Result:
Thus the Python program to implement a stack for student-details is executed successfully and the
output is verified.

Aim:
Each node of stack contains the following information:
i) pin code of a city ii) Name of city
To Write a python program to implement following operations in above stack
a) PUSH() To push a node into a stack b) POP() To remove a node from stack
Algorithm:
Step 1: To create an empty stack for storing City details.
Step 2: Insert elements up to the stack is full
Step 3: If the stack is full, not possible to insert the City details
Step 4: To remove a City details at a time if the stack has City details
Step 5: If the stack has no City details, not possible to remove any element
Step 6: While on insertion each City details to be stored at top of the stack
Step 7: While on removing a City details then remove the City details from top of the stack

Program:
def isEmpty(stk):
if stk == []:
return True
else:
return False

def push(stk,item):
stk.append(item)
38
top = len(stk)-1

def pop(stk):
if(stk==[]):
print("Stack empty;UNderflow")
else:
print("Deleted City is :",stk.pop())

stack=[]
top = None
while True:
print("STACK OPERATION:")
print("1.ADD City")
print("2.REMOVE City")
print("3.Exit")
ch = int(input("Enter your choice(1-3):"))
if ch==1:
pincode = int(input("Enter Pin Code of a city to be inserted :"))
cname = input("Enter City Name to be inserted :")
item = [pincode,cname]
push(stack,item)
input()
elif ch==2:
pop(stack)
input()
elif ch==3:
break
else:
print("Invalid choice ")
input()

OUTPUT:

39
40
EX.NO : 19 SQL QUERY TO CREATE STUDENT ACADEMIC RECORD TABLE, INSERT
DATE: RECORD TO THE TABLE, DISPLAY RECORDS IN A TABLE , FIND
MINIMUM, MAXIMUM AND AVERAGE OF THE INDIVIDUAL STUDENT
MARKS FROM A TABLE.

Result:
Thus the python program to implement push and pop operations in stack contains
city details is executed successfully and the output is verified.

Aim:
To write SQL query to create student academic record table, insert record to the table,
display records in a table, find minimum, maximum and average of the individual student marks
from a table.

Sample Table format


Table Name : student

Stu_id Name Eng Mat Phy Chem CS Total Avg

SQL Queries

(i)Create a student’s academic table in SQL

SQL Query :

create table student(stu_id int primary key,name varchar(15),eng int,mat int,phy int,chem
int,cs int,total int);

41
(ii)Insert values to the table student

SQL Query :
Insert into student value(1001, ‘Boopathi’,83,93,72,79,73,400)
Insert into student value(1002,'Jaisin',86,96,70,71,72,395);
Insert into student value(1003,'Hariprasath',80,86,64,73,81,384);
Insert into student value(1004,'Hariharan.M',96,95,91,93,96,471);
Insert into student value(1005,'Hariharan.K',87,90,76,83,74,410);
Insert into student value(1006,'Kathirvel',86,74,71,89,66,386);
Insert into student value(1007,'Shajan',66,71,74,81,63,355);
Insert into student value(1008,'Sumith',83,82,81,75,80,401);

(iii)Display records to the table student

(a) Display all the records in the table student


SQL Query :
Select*from student;

42
(b)Display Stu_id, name and total field records in the table student
SQL Query :
select stu_id,name,total from student;

(iv)Find records who secured minimum total in the table student

SQL Query :
select*from student where total=(select min(total)from student);

(v)Find records who secured maximum total in the table student

SQL Query :
select*from student where total=(select max(total)from student);

43
EX.NO : 20 WRITE SQL QUERY FOR (A) TO (F) ON THE BASIS OF TABLE
DATE: HOSPITAL.

(vi) Find Average mark of individual student in the table student

SQL Query:
select*,(total/5)as Average from student;

Result:
Thus the SQL query to create student academic record table, insert record to the table,
display records in a table, finding minimum, maximum and average of the individual student marks
from a table is executed successfully and the output is verified.

TABLE NAME: hospital

44
(A) To show all information about the patients of cardiology department.
(B) To list the names of female patients who are in orthopedic dept.
(C) To list names of all patients with their date of admission in ascending order.
(D) To display Patient’s Name, Charges, age for male patients only.
(E) To count the number of patients with age >20.
(F) To insert a new row in the HOSPITAL table with the following
11,”nikil”,37,”ENT”,(25/02/98},250,”M”
Aim:
To write SQL query for above questions (A) to (F) on the basis of the above table
hospital.
SQL Queries

(A) To show all information about the patients of cardiology department.


Ans: SELECT * FROM hospital WHERE department=’Cardiology’;

(B) To list the names of female patients who are in orthopedic dept.
Ans: SELECT name FROM hospital WHERE sex=’F’ AND department=’Orthopedic’;

45
(C) To list names of all patients with their date of admission in ascending order.
Ans.: SELECT name, dateofadm FROM hospital ORDER BY dateofadm;

(D) To display Patient’s Name, Charges, age for male patients only.
Ans: SELECT name, charges, age FROM hospital WHERE sex=’M’;

(E) To count the number of patients with age >20.


Ans.: SELECT COUNT(age) FROM hospital WHERE age>20;

46
EX.NO : 21 SQL QUERY TO ALTER TABLE, UPDATE TABLE AND GROUP BY
DATE:

(F) To insert a new row in the HOSPITAL table with the following
11,”Sivaprakasam”,37,”ENT”,’2022-02-14,25000,”M”

Ans.: INSERT INTO hospital VALUES (11, ‘Sivaprakasam’, 37, ‘ENT’, ‘2022-02-14,
25000, ‘M’);

Result:
Thus the SQL query for above questions (a) to (f) on the basis of the above table
hospital is executed successfully and the output is verified.

Aim:
47
To write SQL query to alter table, update table and group by for the following table
student.

SQL Queries

(A) Add column ‘city’ after column ‘name’ of the table ‘student’ by using of Alter
query
Ans: ALTER TABLE STUDENT ADD COLUMN city varchar(15) after name;
OUTPUT

(B) Update column city with values


Ans:
48
UPDATE STUDENT SET city='Pennagaram' WHERE stu_id=1001;
UPDATE STUDENT SET city='Kambainallur' WHERE stu_id=1002;
UPDATE STUDENT SET city='Dharmapuri' WHERE stu_id=1003;
UPDATE STUDENT SET city='Palacode' WHERE stu_id=1004;
UPDATE STUDENT SET city='Dharmapuri' WHERE stu_id=1005;
UPDATE STUDENT SET city='Pennagaram' WHERE stu_id=1006;
UPDATE STUDENT SET city='Salem' WHERE stu_id=1007;
UPDATE STUDENT SET city='Chennai' WHERE stu_id=1008;

OUTPUT

49
(B) Group by city and Count the number of students from different cities.
Ans:
SELECT city,COUNT(*) FROM STUDENT GROUP BY city;
OUTPUT

Result:
Thus the SQL query to alter table, update table and group by for above table student
is executed successfully and the output is verified.

50
EX.NO : 21 A Program to integrate SQL with Python by importing the MySQL
DATE: module and create a table employee, add record , update record, delete
record, search record and display the records.

Aim:
To write a Program to integrate SQL with Python by importing the MySQL module
and create a table employee, add record, update record, delete record, search record and
display the records.
Algorithm:
Step 1: Import MYSQL connector.
Step 2: Connect python with MYSQL database by using of user id and password.
Step 3: Create cursor instant to execute MYSQL query in python.
Step 4: Create employee database if not exists.
Step 5: Create function to add, update, delete and display record to employee database.
Step6: Stop
Program:
import mysql.connector as mcr
cn = mcr.connect(host='127.0.0.1',user='root',password="dspsdpi")
cr = cn.cursor()
cr.execute("create database if not exists compane")
cr.execute("use compane")
cr.execute("create table if not exists employee(empno int(12) unique NOT NULL,empname
varchar(50),edept varchar(30),salary decimal(12,2))")
cn.commit()
while True:
print("Employee Information System")
choice=int(input("1. ADD RECORD 2. UPDATE RECORD 3.DELETE RECORD 4.
SEARCH 5.DISPLAY 6.EXIT : "))
if choice==1: #INSERTING A RECORD
e = int(input("Enter Employee Number :"))
n = input("Enter Name :")
d = input("Enter Department :")
s = int(input("Enter Salary :"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
cr.execute(query)
cn.commit()
print("A RECORD INSERTED...")

51
elif choice == 2: #UPDATING A RECORD
eno=int(input("Enter employee number to be updated "))
sal=int(input("Enter salary to be updated "))
query="update employee set salary={} where empno={}".format(sal,eno)
cr.execute(query)
print("A Record Updated ")
cn.commit()

elif choice == 3: #DELETING A RECORD


eno=int(input("Enter employee number to be deleted"))
query="delete from employee where empno={}".format(eno)
cr.execute(query)
print("Record(s) Deleted ")
cn.commit()

elif choice == 4: #SEARCHING A RECORD


eno=int(input("Enter employee number to be searched"))
query="select * from employee where empno={}".format(eno)
cr.execute(query)
result = cr.fetchall()
if cr.rowcount==0:
print("Record not found")
else:
print("EMPNO","NAME","DEPARTMENT","SALARY")
for row in result:
print(row[0],row[1],row[2],row[3])
cn.commit()

elif choice == 5: #DISPLAYING RECORDS


query="select * from employee"
cr.execute(query)
result = cr.fetchall()
print("EMPNO","NAME","DEPARTMENT","SALARY")
for row in result:
print(row[0],row[1],row[2],row[3])
cn.commit()

elif choice==6: #CLOSING DATABASE


cn.close()
print("File closed successfully...")
break
else:
print("Invalid Choice...")
continue
52
53

You might also like