Grade 12 Lab Tasks
Instructions:
1.Dont Write the program and output in record note
2.Write only Aim,Algorithm and Result in Record .
3.Program is given for reference purpose.
Ex. no.1. Word separation in text file
Aim:
To write a python program to read a text file line by line and display each word separated by a #.
Algorithm:
Step 1:Open the file "Story.txt" in read mode.
Step 2:Read all lines of the file into a list called Contents.
Step 3:For each line in Contents:
Split the line into words using split().
For each word in words:
Append a # to the word.
Print the modified word
After processing all words in the line, print a newline character to move to the next line.
Step 4:Close the file after processing all the lines.
Program:
Result:
Thus, the Python program to read a text file line by line and display each word separated by a # is
written, executed successfully and the output is verified.
Ex. no.2. Display Characters in text file
Aim: To write a python program to read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file.
Algorithm:
Step 1:Open the file "Story.txt" in read mode.
Step 2:Initialize variables Vowels, Consonants, Lower_case, and Upper_case to 0. These will be used to keep
track of the number of vowels, consonants, lowercase letters, and uppercase letters, respectively.
Step 3:Read the entire content of the file into the variable Contents.
Step 4:For each character ch in Contents:
o If ch is a vowel (i.e., it is in 'aeiouAEIOU'), increment the Vowels counter by 1.
o If ch is a consonant (i.e., it is in 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ'),
increment the Consonants counter by 1.
o If ch is a lowercase letter (using ch.islower()), increment the Lower_case counter by 1.
o If ch is an uppercase letter (using ch.isupper()), increment the Upper_case counter by 1.
Step 5:Close the file after processing all characters.
Step 6:Print the total number of vowels, consonants, uppercase letters, and lowercase letters found in the file.
Program:
Result:
Thus, the Python program to read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file is written, executed successfully and
the output is verified.
Ex. no.3. Creating new file from source file
Aim:To write a python program to remove all the lines that contain the character 'a' in a file and write it to
another file.
Algorithm:
step 1:Define the Remove() Function to handle the file operations.
Step 2:Open the file "SampleOld.txt" in read mode (fo).Open a new file "SampleNew.txt" in write mode (fn).
Step 3:Initialize an empty list L to store lines that do not contain the letter 'a'.
Step 4:Read all lines from "SampleOld.txt" into a list called lines.
Step 5:For each line in lines:
->if the line contains the letter 'a', write the line to "SampleNew.txt".
->Otherwise:Append the line to the list L.
Step 6:Open "SampleOld.txt" in write mode (fo).
Step 7:Write the lines stored in the list L back to "SampleOld.txt".
Step 8:Close both files "SampleOld.txt" and "SampleNew.txt".
Step 9:Call the Remove() function to execute the operations.
Program;
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 written, executed successfully and the output is verified.
Ex.No.4. Searching data in a binary file
Aim:
To write a python program to create a binary file with name and roll number. Search for a given roll
number and display the name, if not found display appropriate message.
Algorithm:
create() Function:
step 1:Import the pickle module for handling binary file operations.
Step 2:Open a binary file named "student.dat" in write-binary mode ("wb").
Step 3:Set a variable ch to 'y' to control the loop for data entry.
Step 4:Use a while loop to allow continuous input of student data as long as ch equals 'y'.
Step 5:Inside the loop:
Prompt the user to input the student's roll number (roll_no).
Prompt the user to input the student's name (name).
Store these values in a list L, where the first element is roll_no and the second is name.
Step 6:Serialize and save the list L to the binary file using pickle.dump().
Step 7:Ask the user if they want to add more data by prompting them with a message to press 'y' for yes or 'n'
for no.
Step 8:If the user inputs 'n', exit the loop.
Step 9:After exiting the loop, close the binary file.
search() Function:
step 1:Open the binary file "student.dat" in read-binary mode ("rb").
Step 2:Ask the user to input the roll number (r) they want to search for.
Step 3:Set a variable found to False to keep track of whether the roll number is found.
Step 4:Initialize an empty list student to temporarily hold student data during the search.
Step 5:Use a while True loop to continuously read records from the binary file.
Step 6:Load each record from the file using pickle.load() and store it in the list student.
Step 7:Check if the first element of student (i.e., student[0], which represents the roll number) matches r.
Step 8:If a match is found, print the details of the student and set found to True.
Step 9:Break out of the loop once the roll number is found.
Step 10:If the end of the file is reached (indicated by EOFError), close the file.
Step 11:If found is still False, print "Sorry! Roll number not found".
Step 12:Close the binary file after searching.
Main program:
Call the create()and search() function to execute the operations .
Program:
import pickle
def create( ):
f=open('student.dat','wb')
ch=’y’
while ch==’y’:
roll_no = int(input("Enter Roll Number :"))
name= input("Enter Name :")
L=[ roll_no,name]
pickle.dump(L,f)
ch=input("Do you want to AddMore ? press(y/n)")
f.close()
def search( ):
f=open('student.dat','rb')
r = int(input("Enter Roll number to search :"))
student=[ ]
found=False
try:
while True:
student = pickle.load(f)
if s[0]==r:
print("The searched rollno is found and the details are",s)
found=True
break
except EOFError:
f.close()
if found==False:
print("Sorry! Roll number not found")
#main program
create( )
search( )
Result:
Thus, the Python program to create a binary file with name and roll number and to search for a given
roll number and display the name, if not found display appropriate message is written, executed
successfully and the output is verified.
Ex.No.5. Updating Data in binary file
Aim:
To write a python program to create a binary file with roll number, name and marks. Input a roll number
and update the marks.
Algorithm:
Write( ) Function
Step1:Open a file named "Studentdetails.dat" in binary write mode ('wb').
Step 2:Set the variable ch to 'y' (yes) to enter the loop.
Step 3:While ch is 'y':
i)Prompt the user to input a roll number, name, and marks.
ii)Store these inputs in a list named record.
iii)Use pickle.dump() to write the record list to the file.
iv)Prompt the user to ask if they want to enter more records.
Step 4:Close the file after exiting the loop.
Update() function
Step 1:Open the file "Studentdetails.dat" in binary read/write mode ('rb+').
Step 2:Prompt the user to enter the roll number of the student whose marks need to be updated.
Step 3:Set a variable found to False.
Step 4:Use a while loop to continuously read records:
Step 5:Use f.tell() to get the current file position and store it in pos.
Step 6:Use pickle.load() to read a record from the file.
Step 7:If the roll number from the record matches the input roll number:
i)Print the record details.
ii)Prompt the user to input new marks.
iii)Update the marks in the record.
iv)Use f.seek(pos) to move the file pointer back to the position of the updated record.
v)Use pickle.dump() to write the updated record back to the file.
vi)Set found to True and print the updated details.
vii)Break the loop to stop searching.
Step 8:If EOFError is raised, close the file and check if found is still False.
Step 9:If found is False, print a message saying the roll number was not found.
Main Program
1. Call Write() and Update()to Execute the operations
Program:
import pickle
def Write( ):
f = open("Studentdetails.dat", 'wb')
ch=’y’
while ch==’y’:
r =int(input ("Enter Roll no : "))
n = input("Enter Name : ")
m = int(input ("Enter Marks : "))
record = [r,n,m]
pickle.dump(record,f)
ch = input("Do you want to enter more ?(Y/N)")
f.close( )
def Update( ):
f = open("Studentdetails.dat", 'rb+')
rollno = int(input("Enter roll no whoes marks you want to update"))
found =False
try:
while True:
pos=f.tell()
rec = pickle.load(f)
if rec[0]==rollno:
print(“The searched rollno is found and the details are”,rec)
num = int(input("Enter the mark to be updated:"))
rec[2]=num
f.seek(pos)
pickle.dump(rec,f)
found=True
f.seek(pos)
print(“Marks updated successfully and the details are:”,rec)
break
except EOFError:
f.close()
if found==False:
print("Sorry! Roll number not found")
#main program
Write()
Update()
Result:
Thus, the Python program to create a binary file with roll number, name and marks and input a roll
number to update the marks is written, executed successfully and the output is verified.
Ex.no.6. Searching data in CSV file
Aim:
To write a python program to create a CSV file by entering user-id and password, read and search the
password for given user- id.
Algorithm:
Write()Function
Step1:Open a file named "details.csv" in write mode ("w").
Step 2:Create a CSV writer object to handle writing to the file.
Step 3:Write a header row with the columns ["User Id", "password"] to the CSV file.
Step 4:Set the variable ch to 'y' (yes) to enter the loop.
Step 5:While ch is 'y':
i)Prompt the user to input a user ID and password.
ii)Store these inputs in a list named record.
iii)Use the CSV writer object to write the record list to the file.
iv)Prompt the user to ask if they want to enter more records.
Step 6:Close the file after exiting the loop.
Search()Function:
Step 1:Open the file "details.csv" in read mode ("r").
Step 2:Create a CSV reader object to handle reading from the file.
Step 3:Set a variable found to False.
Step 4:Prompt the user to input the user ID they want to search for.
Step 5:Use next(ro) to skip the header row in the CSV file.
Step 6:Iterate over each row in the CSV:
Step 7:If the user ID in the current row matches the input user ID:
i)Print the password associated with that user ID.
ii)Set found to True.
iii)Break the loop.
Step 8:After completing the loop, if found is still False, print a message saying "Sorry! Record not found."
Step 9:Close the file after completing the search.
Main Program
Call Write()and Search function to execute the operations
Program:
import csv
def Write( ):
f=open("details.csv", "w"):
wo= csv.writer(f)
wo.writerow(["User Id", "password"])
ch=’y’
while ch==’y’:
user_id = input("enter id: ")
password = input("enter password: ")
record = [user_id, password]
wo.writerow(record)
ch = input("Do you want to enter more ?(Y/N)")
f.close( )
def Search( ):
fo=open("details.csv", "r")
ro= csv.reader(fo)
found=False
u= input("enter the user id to be searched\n")
next(ro)
for i in ro:
if i[0] == u:
print(i[1])
found=True
break
fo.close()
if found==False:
print("Sorry! Record not found")
#Main program
Write( )
Search( )
Result:
Thus, the Python program to create a CSV file by entering user-id and password, read and search the
password for given user- id is written, executed successfully and the output is verified.
Ex.NO.7. Navigations of cursor position in text file
Aim:
To write a python program to know the cursor position and print the text according to below-
given specifications:
1. Print the initial position
2. Move the cursor to 4th position
3. Display next 5 characters
4. Move the cursor to the next 10 characters
5. Print the current cursor position
6. Print next 10 characters from the current cursor position
Algorithm :
Step 1:Define the navigation() Function to handle the file operations.
Step 2:Open a file named "merge.txt" in binary read/write mode ("rb+").
Step 3:Use f.tell() to get and print the current file position (which is 0 at the start).
Step 4:Use f.seek(4, 0) to move the file pointer to the position 4 bytes from the start of the file (absolute
position).
Step 5:Use f.read(5) to read 5 bytes of data starting from the current file pointer position.
Step 6:Print the data read.
Step 7:Use f.seek(10, 1) to move the file pointer 10 bytes forward from the current position (relative
position).
Step 8:Use f.tell() to get and print the current file position (which should now be the new position after the move).
Step 9:Use f.read(10) to read 10 bytes of data starting from the current file pointer position.
Step 10:Print the data read and close the file .
Step 11:In the main program, call the navigation( ) function
Source Code:
def navigation( ):
f=open("merge.txt","rb+")
print(f.tell())
f.seek(4,0)
print(f.read(5))
f.seek(10,1)
print(f.tell())
print(f.read(10))
f.close( )
navigation()
Sample output:
Content in merge.txt
A computer network is a set of computers sharing resources located on or provided by network nodes
======== RESTART: C:\Users\USER\Desktop\sample.py ========
0
b 'mpute'
19
b 'is a set o'
Result:
Thus, the Python program to know the cursor position and print the text according to given
specification is written, executed successfully and the output is verified.
Ex.NO.8. Operations in CSV file
Aim:
To write a python program that defines and calls the following user defined functions:
a)add( ) – To write a nested python list to a CSV file ‘furdata.csv’ in one go. Each record consists of a list
with field elements as fid, fname and fprice to store furniture id, furniture name and furniture price
respectively.
b)create( ) – To read a CSV file ‘furdata.csv’ and create another CSV file ‘furniture.csv’ with the records of
the furniture whose price is more than 10000 with a different delimiter
c)count( ) – To display the number of records and column names present in the file ‘furniture.csv’
Algorithm:
insert() Function:
step 1:Open a file named "furdata.csv" in write mode ("w"), with newline="" to avoid extra blank lines between
rows.
Step 2:Create a CSV writer object to handle writing to the file.
Step 3:Write the header row ['fid', 'fname', 'fprice'] to the CSV file.
Step 4:Initialize an empty list L to store the data.Set the variable ch to 'y' to enter the loop.
Step 5:While ch is 'y':
i)Prompt the user to input fid (furniture ID), name (furniture name), and price (furniture price).
ii)Store these inputs in a list data.
iii)Append the data list to the list L.
iv)Prompt the user to ask if they want to continue entering records.
Step 6:Use wo.writerows(L) to write all the records from list L to the CSV file.
Step 7:Close the file after writing all records.
create() Function:
step 1:Open "furdata.csv" in read mode ("r") and "furniture.csv" in write mode ("w")
Step 2:Create a CSV reader object to read from "furdata.csv".
Step 3:Create a CSV writer object to write to "furniture.csv" with delimiter="$".
Step 4:Use next(ro) to skip the header row in "furdata.csv".
Step 5:Iterate over each row in the CSV reader.
Step 6:If the value in the price column (third column) is greater than 10000, write the row to "furniture.csv".
Step 7:Close both files after processing.
count()Function:
step 1:Open "furniture.csv" in read mode.
Step 2:Create a CSV reader object to read from "furniture.csv" with delimiter='$'.
Step 3:Convert the reader object to a list of records rec.
Step 4:Print the list rec.
Step 5:Print the number of columns in the first record by checking the length of the first item in rec.
Step 6:Print the number of rows in the list rec.
Step 7:Close the file after counting records.
Main Program
Call insert(),create(),count()functions to execute the operations
Program:
import csv
def insert():
f1=open("furdata.csv","w",newline=” “)
wo=csv.writer(f1)
wo.writerow(['fid','fname','fprice'])
L=[]
ch='y'
while ch=='y':
fid=int(input("Enter furnitureid:"))
name=input("Enter furniture name:")
price=int(input("Enter furniture price:"))
data=[fid,name,price]
L.append(data)
ch=input("Do you want to continue? press y/n:")
wo.writerows(L)
f1.close()
def create ():
f2=open("furdata.csv","r",newline='\r\n')
f3=open("furniture.csv",'w',newline=” ”)
wo=csv.writer(f3,delimiter="$")
ro=csv.reader(f2)
next(ro)
for i in ro:
if int(i[2])>10000:
wo.writerow(i)
f2.close()
f3.close()
def count():
f3=open("furniture.csv",'r')
ro=csv.reader(f3,delimiter='$')
rec=list(ro)
print(rec)
for i in rec:
print("no of col:",len(i))
break
print("no of row:",len(rec))
f3.close()
#main program
insert()
create()
count( )
Result:
Thus, the Python program to perform the given CSV operations is written, executed successfully
and the output is verified.
Ex.NO.9. Menu driven program to check numbers
Aim:
To write a menu-driven python program using different functions for the following menu:
1. Check no. is Palindrome or not
2. Check no. is Armstrong or not
3. Check no. is Prime or not
4. Check no. is even or odd
5. Exit
Algorithm:
primecomp(num) Function:
step 1:Loop through integers i from 2 to num - 1.
Step 2:If num % i == 0 (i.e., num is divisible by i):
Print that num is a composite number and exit the loop.
Step 3:Else Print that num is a prime number.
palindrome(num) Function:
step 1:Convert the number num to a string x.
step 2:If x is equal to its reverse (x[::-1]):
Print that num is a palindrome.
Step 3:Otherwise:Print that num is not a palindrome.
evenno(num) Function:
step 1:If num % 2 == 0 (i.e., num is divisible by 2):
Print that num is an even number.
Step 2:Otherwise:Print that num is not an even number.
armstrong(num) Function:
step 1:Convert the number num to a string a.
step 2:Determine the length of the string a and store it in x.
step 3:Initialize count to 0.
Step 4:For each character i in string a:
Convert i to an integer and raise it to the power of x.
Add the result to count.
Step 5:If count is equal to num:Print that num is an Armstrong number.
Step 6:Otherwise:Print that num is not an Armstrong number.
Main Program
Step 1:Begin a while True loop to continuously provide options to the user.
Step 2:Display Menu:Print a welcome message and the options.
Step 3:Prompt the user to enter a choice for the operation (ch).
Step 4:Prompt the user to enter a number to check (num).
Step 5:If ch is 1:Call primecomp(num).
If ch is 2:Call palindrome(num).
If ch is 3:Call evenno(num).
If ch is 4:Call armstrong(num).
If ch is any other value:Print "Thank you" and exit the loop.
Program:
def primecomp(num):
for i in range(2, num):
if num % i == 0:
print(num, "is a composite number")
break
else:
print(num, "is a prime number")
def palindrome(num):
x=str(num)
if x==x[: :-1]:
print(num,"is palindrome")
else:
print(num,"is not palindrome")
def evenno(num):
if num%2==0:
print(num,"is an even number")
else:
print(num,"is not an even number")
def armstrong(num):
a=str(num)
x=len(a)
count=0
for i in a:
count+=(int(i)**x)
if count==num:
print("is an armstrong number")
else:
print("is not an armstrong number")
#main program
While True:
print("Welcome to mini calculator")
print("We can check")
print("1.Prime or composite number")
print("2.Palindrome or not")
print("3.Even or odd")
print("4.Armstrong number or not")
print("5.Exit")
ch=int(input("Enter the operation u want to perform:"))
num=int(input("Enter a number to check:"))
if ch==1:
primecomp(num)
elif ch==2:
palindrome(num)
elif ch==3:
evenno(num)
elif ch==4:
armstrong(num)
else:
print("Thank you")
break
Result:
Thus, the Python program to display Menu driven program to check numbers is written, executed
successfully and the output is verified.
Ex. No.10. Random number generator
Aim:
To Write a python program which uses random number generator concept that generates random
numbers between 1 and 6 (simulates a dice).
Algorithm:
Step 1:Print a header:
Print a row of 88 asterisks (*).
Print a row of 57 percentage signs (%).
Print a row with 37 equal signs (=), followed by the text "ROLLING DICE", and then another 37 equal
signs.
Print another row of 57 percentage signs (%).
Print another row of 88 asterisks (*).
Step 2:Set the variable a to "y" to start the loop.
Step 3:While a is equal to "y":
o Generate a random integer x between 1 and 6 (inclusive).
Step 4:If x is 1, print the value of x and the message
If x is 2, print the value of x and the message
If x is 3, print the value of x and the message
If x is 4, print the value of x and the message
If x is 5, print the value of x and the message
If x is 6, print the value of x and the message
Step 5:Ask the user if they want to roll the dice again by printing the message "Do you want to roll once
more? (y/n):" and store their input in the variable a.
Step 6:The loop continues as long as the user inputs "y". If the user inputs anything else, the loop terminates.
Program:
import random
print("*"*88)
print("%"*57)
print("="*37,"ROLLING DICE","="*37)
print("%"*57)
print("*"*88)
a="y"
while (a=="y"):
x=random.randint(1,6)
if x==1:
print(x,"ahh... It's OK try once more")
elif x==2:
print(x,"Come on don't give up")
elif x==3:
print(x,"Better luck next time")
elif x==4:
print(x,"Niceeee.... ")
elif x==5:
print(x,"good try!!")
else:
print(x,"Congratulations!!!!! You've got 6!!!!")
a=input("Do you want roll once more?(y/n):")
Result:
Thus, the Python program which uses random number generator concept that generates random
numbers between 1 and 6 is written, executed successfully and the output is verified.
EX.NO.11. Function with variable length arguments
Aim:
To Write a python program to demonstrate the concept of variable length argument to calculate the sum
and product of the first 10 numbers.
Algorithm:
Step 1:Define a function sum_prod(*f):The function takes a variable number of arguments and stores
them as a tuple in the parameter f.
Step 2:Inside the function, initialize add to 0. This will hold the sum of the numbers.
Step 3:Initialize prod to 1. This will hold the product of the numbers.
Step 4:For each number i in the tuple f:
Add the value of i to add.
Multiply the value of i with prod and update prod with the result.
Step 5:After the loop ends, return the values of add (sum) and prod (product).
Step 6:Pass the numbers 1 through 10 to the sum_prod function and store the returned values in
variables a (sum) and b (product).
Step 7:Display the values of a(sum) and b(product)
Program:
def sum_prod(*f):
add=0
prod=1
for i in f:
add+=i
prod=prod*i
return add, prod
a,b=sum_prod(1,2,3,4,5,6,7,8,9,10)
print("The sum of 1st 10 numbers is:",a)
print("The product of 1st 10 numbers is:",b)
Result:
Thus, the Python program to demonstrate the concept of variable length argument to calculate the sum
and product of the first 10 numbers is written, executed successfully and the output is verified.
Ex.No.12. Python String functions
Aim:
To Write a python program that inputs a main string and creates an encrypted string by embedding a
short symbol based string after each character. The program should also be able to produce the decrypted
string from encrypted string.
Algorithm:
Step 1: Prompt the user to enter a string s.
Step 2:Prompt the user to enter a symbol symbol for encryption.
step 3:Define encryptdecrypt( ) function
Step 4:Encryption Process:
i) Join each character of the string s with the symbol symbol.
ii) Store the result in the variable y.
iii) Print the encrypted string as "Encrypted string is: y".
Step 5:Decryption Process:
i)Replace all occurrences of the symbol symbol in the string s with an empty string "".
ii) Store the result in the variable v.
iii)Print the decrypted string as "Decrypted string is: v".
step 6:Call encryptdecrypt( ) function to perform the operations,
program:
def encryptdecrypt(s,symbol):
y=symbol.join(s)
print("Encrypted string is:",y)
v=s.replace(symbol,"")
print("Decrypted string is:",v)
s=input("Enter a string :")
symbol=input("Enter symbol to encrypt:")
encryptdecrypt(s,symbol)
Result :
Thus, the Python program to perform String functions is written, executed successfully and the
output is verified.
Ex.No.13 Implementation of Stack operations
Aim:
To Write a Python program to implement a stack using list.
Algorithm:
Step 1:Create an empty list stack = [] and set top = None.
Step 2:Print the available stack operations
Step 3: Prompt the user to choose an operation by entering a number between 1 and 5.
Step 4:If the user chooses 1 (Push):
o Prompt the user to enter an item to push onto the stack.
o Call the push function to add the item to the stack.
Step 5:If the user chooses 2 (Pop):
o Call the pop function to remove the top item from the stack.
o If the stack is empty, print "Stack is empty".
o Else, print the popped item.
Step 6:If the user chooses 3 (Peek):
o Call the peek function to retrieve the top item without removing it.
o If the stack is empty, print "Stack is empty".
o Else, print the topmost item.
Step 7:If the user chooses 4 (Display):
o Call the display function to print all items in the stack.
o If the stack is empty, print "Stack is empty".
Step 8:If the user chooses 5 (Exit):
o Terminate the program.
Step 9:If the user enters an invalid choice:
o Print "Invalid choice" and return to the menu.
Step 10:Continue to display the menu and process user input until the user chooses to exit.
program:
def empty(stk):
if stk==[]:
return True
else:
return False
def push(stk,item):
stk.append(item)
top=len(stk)-1
def pop(stk):
if empty(stk):
return "underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
return item
else:
top=len(stk)-1
return item
def peek(stk):
if empty(stk):
return "underflow"
else:
top=len(stk)-1
return stk[top]
def display(stk):
if empty(stk):
return "underflow"
else:
top=len(stk)-1
print(stk[top],"<-top")
for i in range(top-1,-1,-1):
print(stk[i])
stack=[ ]
top=None
while True:
print("STACK OPERATIONS")
print("WE HAVE.........")
print("1. Push")
print("2.Pop")
print("3.Peek")
print("4.Display")
print("5.Exit")
a=int(input ("What do you want to perform(1-5):"))
if a==1:
item=int(input("Enter an item:"))
push(stack,item)
if item=="underflow":
print("Stack is empty")
elif a==2:
item=pop(stack)
if item=="underflow":
print("Stack is empty")
else:
print("popped item is",item)
elif a==3:
item=peek(stack)
if item=="underflow":
print("Stack is empty")
else:
print("Topmost item is",item)
elif a==4:
display(stack)
elif a==5:
break
else:
print("invalid choice")
Result :
Thus, the Python program to implement a stack using list is written, executed successfully and
the output is verified.
Ex.No.14 Implementation of Stack for employee details
Aim:
To Write a Python program to implement a stack for the employee details (empno, name).
Algorithm:
Step 1:Create an empty list stack = [] and set top = None.
Step 2:Print the available stack operations
Step 3: Prompt the user to choose an operation by entering a number between 1 and 5.
Step 4:If the user chooses 1 (Push):
o Prompt the user to enter an employee number emp_no.
o Prompt the user to enter an employee name name.
o Combine emp_no and name into a list item = [emp_no, name].
o Call the push function to add the item (employee details) to the stack.
o If item equals "underflow", print "Stack is empty".
Step 5:If the user chooses 2 (Pop):
o Call the pop function to remove the top item from the stack.
o If the stack is empty, print "Stack is empty".
o Else, print "Popped item is", followed by the popped item.
Step 6:If the user chooses 3 (Peek):
o Call the peek function to retrieve the top item without removing it.
o If the stack is empty, print "Stack is empty".
o Else, print "Topmost item is", followed by the topmost item.
Step 7:If the user chooses 4 (Display):
o Call the display function to print all items in the stack.
o If the stack is empty, print "Stack is empty".
Step 8:If the user chooses 5 (Exit):
o Terminate the program.
Step 9:If the user enters an invalid choice:
o Print "Invalid choice" and return to the menu.
Step 10:Continue to display the menu and process user input until the user chooses to exit.
program:
def empty(stk):
if stk==[]:
return True
else:
return False
def push(stk,item):
stk.append(item)
top=len(stk)-1
def pop(stk):
if empty(stk):
return "underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
return item
else:
top=len(stk)-1
return item
def peek(stk):
if empty(stk):
return "underflow"
else:
top=len(stk)-1
return stk[top]
def display(stk):
if empty(stk):
return "underflow"
else:
top=len(stk)-1
print(stk[top],"<-top")
for i in range(top-1,-1,-1):
print(stk[i])
stack=[]
top=None
while True:
print("STACK OPERATIONS")
print("WE HAVE.........")
print("1. Push")
print("2.Pop")
print("3.Peek")
print("4.Display")
print("5.Exit")
a=int(input ("What do you want to perform(1-5):"))
if a==1:
emp_no=int(input("Enter employee number:"))
name=input("Enter employee name:")
item=[emp_no,name]
push(stack,item)
if item=="underflow":
print("Stack is empty")
elif a==2:
item=pop(stack)
if item=="underflow":
print("Stack is empty")
else:
print("popped item is",item)
elif a==3:
item=peek(stack)
if item=="underflow":
print("Stack is empty")
else:
print("Topmost item is",item)
elif a==4:
display(stack)
elif a==5:
break
else:
print("invalid choice")
Result :
Thus, the Python program to implement a stack for the employee details using list is written,
executed successfully and the output is verified.
Ex.No.15 To reverse a string using stack.
Aim:
To Write a python program to reverse a string using stack.
Algorithm:
Step 1:Create an empty list stack = [].
Step 2:Prompt the user to enter a string s.
Step 3:Push Characters onto Stack:
i)Iterate over each character i in the string s.
ii)Call the push function to add character i to the stack.
Step 4:Display Stack:Print the current contents of the stack.
Step 5:Reverse the String:
i)Iterate j times, where j is the length of the stack.
ii)Call the pop function to remove the top character x from the stack.
ii)Print character x without a newline.
program:
def push(stk,a):
stk.append(a)
def pop(stk):
return stk.pop()
stack=[]
strg=input("Enter a string:")
for i in strg:
push(stack,i)
print(stack)
print("The reversed string will be:")
for j in range(len(stack)):
x=pop(stack)
print(x,end=" ")
Result :
Thus, the Python program to to reverse a string using stack is written, executed successfully and
the output is verified.