0% found this document useful (0 votes)
18 views49 pages

GR 12-Program List & Pgms With Output (1-22) Edit

The document outlines a list of programming tasks for the 2023-24 academic year, covering various topics such as file handling, data structures, and SQL integration. Each task includes a brief description and a sample code implementation in Python. The tasks range from basic operations like searching and string manipulation to more complex operations involving databases and file management.

Uploaded by

gaswath615
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views49 pages

GR 12-Program List & Pgms With Output (1-22) Edit

The document outlines a list of programming tasks for the 2023-24 academic year, covering various topics such as file handling, data structures, and SQL integration. Each task includes a brief description and a sample code implementation in Python. The tasks range from basic operations like searching and string manipulation to more complex operations involving databases and file management.

Uploaded by

gaswath615
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Program List (2023-24)

1. Write a Program to print all the numbers divisible by 3 and 5 from a Tuple & also find
its sum.
2. Write a Program to input a list of integers & search for a given number using Linear
Search.
3. Write a Python program to extract keywords from the list
4. Write a Program to Check if a value exists in Dictionary.
5. Write a Program to Input a string and determine whether it is a Palindrome or not.
6. Write a Random Number Generator that generates random numbers between 1
and 6 (simulates a dice).
7. Write a Program to find the sum of the digits of a random three-digit number.
8. Write a program with a user-defined function with string as a parameter which
replaces all vowels in the string with ‘*’.
9. Write a Program to Count the number of lines in a Text File which starts with an
Alphabet ‘C’.
10. Write a Program to remove all the lines that contain the character `a' in a file and
write it to another file.
11. Write a Program to Read a text file and display the number of vowels/
consonants/uppercase/ lowercase and other than character and digit in the file.
12. Write a Program to read a text file line by line and display each word separated by a
#.
13. Create a binary file with roll number, name and marks. Input a roll number and update
details.
14. Create a binary file with the name and roll number. Search for a given roll number
and display the name, if not found display appropriate message.
15. Create a CSV file by entering user-id and password, read, modify and search the
password for given user id.
16. Create a CSV file by entering empno, name, dept and salary, read & delete the record
for given empno.
17. Write a python program to implement a stack using list.
18. Write a program to Reverse a String using stack.
19. Integrate MySQL with Python by importing the MySQL module and add records of
student and display all the record.
20. Integrate MySQL with Python by importing the MySQL module to search student
using rollno, name, age, std and if present in table display the record, if not display
appropriate message.
21. Integrate SQL with Python by importing the MySQL module to search a student using
rollno & update the record.
22. Integrate SQL with Python by importing the MySQL module to search a student using
rollno & delete the record.
23. Data Definition Language Commands
24. Data Manipulation Language Commands
25. Constraints in SQL
26. SQL Operators
27. Aggregate Functions
28. SQL Clauses
29. SQL Joins
NUMBERS DIVISIBLE BY 3 AND 5 FROM A TUPLE & FIND ITS SUM
def Div3and5(t):
s=0
for i in t:
if i%3==0 and i%5==0:
s=s+i
print(i,end="\t")
return s
n=int(input("Enter the number of Elements for Tuple:"))
lst=[]
for i in range(0,n):
e=int(input("Enter the Element:"))
lst.append(e)
t=tuple(lst)
print("Entered Tuple:",t)
print("Numbers Divisible by 3 & 5 are:")
print("\nSum of numbers in tuple divisible by 3 & 5 is",Div3and5(t))

OUTPUT :
Enter the number of Elements for Tuple:5
Enter the Element:2
Enter the Element:3
Enter the Element:15
Enter the Element:6
Enter the Element:45
Entered Tuple: (2, 3, 15, 6, 45)
Numbers Divisible by 3 & 5 are:
15 45
Sum of numbers in tuple divisible by 3 & 5 is 60
LINEAR SEARCH
def linear(lst,n):
for i in range(len(lst)):
if lst[i]==n:
return i
return -1
n=int(input("Enter the number of Elements for List:"))
lst=[]
for i in range(0,n):
element=int(input("Enter the Element:"))
lst.append(element)
print("The List is:")
print(lst)
n = int(input("Enter searching element :"))
res = linear(lst,n)
if res==-1:
print("Element not found in the list")
else:
print( "Element ",n," is found at position:" ,res)

OUTPUT :
Enter the number of Elements for List:5
Enter the Element:56
Enter the Element:23
Enter the Element:78
Enter the Element:12
Enter the Element:90
The List is:
[56, 23, 78, 12, 90]
Enter searching element :23
Element 23 is found at position: 1

Enter searching element :10


Element not found in the list
EXTRACT KEYWORDS FROM THE LIST
from keyword import iskeyword
lst = ["C.Sc with Python", "Platform for Programmer","Maths and Science"]
print("List of Sentences:",end = " ")
print(lst)

kwdlst = []
for i in lst:
for words in i.split():
if iskeyword(words):
kwdlst.append(words)
print("Keywords Present in List:",end = " " )
print(kwdlst)

OUTPUT :
List of Sentences: ['C.Sc with Python', 'Platform for Programmer', 'Maths and Science']
Keywords Present in List: ['with', 'for', 'and']
CHECK IF A VALUE EXISTS IN DICTIONARY
dict={"Bhavana":1,"Richard":2,"Divya":3,"Robert":4}
val=int(input("Enter Value:"))
flag=0
for k in dict:
if val==dict[k]:
print("Value",val,"Found at Key",k)
flag=1
break
if flag==0:
print("Value",val,"Not Found")

OUTPUT :
Enter Value:3
Value 3 Found at Key Divya

Enter Value:5
Value 5 Not Found
PALINDROME
string=input('Enter a string:')
length=len(string)
mid=length//2
rev=-1
for a in range(mid):
if string[a]==string[rev]:
print(string,'is a palindrome.')
break
else:
print(string,'is not a palindrome.')
break

OUTPUT :
Enter a string:Malayalam
Malayalam is a palindrome.

Enter a string:Entertainment
Entertainment is not a palindrome.
RANDOM NUMBER GENERATOR
import random
def rolldice():
print(random.randint(1,6))
print("""Welcome to My Python Random Dice Program!
To start press Enter! Whenever you are over, type quit.""")
while True:
userprompt = input(">")
if userprompt.lower() == "quit":
break
else:
print("Rolling dice...\nYour number is:")
rolldice()

OUTPUT :
Welcome to My Python Random Dice Program!
To start press Enter! Whenever you are over, type quit.
>
Rolling dice...
Your number is:
4
>quit
SUM OF THE DIGITS OF A RANDOM THREE-DIGIT NUMBER
from random import random
n=random()*900+100
n=int(n)
print(n)
a=n//100
b=(n//10)%10
c=n%10
print(a+b+c)

OUTPUT :
787
22
REPLACES ALL VOWELS IN THE STRING WITH ‘*’
def strep(str):
strlst =list(str)
for i in range(len(strlst)):
if strlst[i] in 'aeiouAEIOU':
strlst[i]='*'
newstr = "".join(strlst)
return newstr

def main():
line = input("Enter string: ")
print("Orginal String")
print(line)
print("\nAfter replacing Vowels with '*'")
print(strep(line))
main()

OUTPUT :
Enter string: Python Programming Language
Orginal String
Python Programming Language

After replacing Vowels with '*'


Pyth*n Pr*gr*mm*ng L*ng**g*
COUNT THE NUMBER OF LINES IN A TEXT FILE WHICH STARTS WITH AN
ALPHABET ‘C’
f=open("top.txt","w")
for i in range(4):
s=input("Enter the Contents to be written in the file:")
f.write(s)
f.write("\n")
f.close()
print()

f=open("top.txt","r")
s=f.readlines()
c=0
print("Reading the Contents of File:")
for i in s:
print(i)
if i[0]=='C' or i[0]=='c':
c+=1
print("Number of lines starting with 'C'=",c)
f.close()
OUTPUT :
Enter the Contents to be written in the file:C Language
Enter the Contents to be written in the file:Click the Start Menu
Enter the Contents to be written in the file:central processing unit
Enter the Contents to be written in the file:trim tool

Reading the Contents of File:


C Language
Click the Start Menu
central processing unit
trim tool
Number of lines starting with 'C'= 3

Top.txt
C Language
Click the Start Menu
central processing unit
trim tool
REMOVE ALL THE LINES THAT CONTAIN THE CHARACTER `A' IN A FILE
f1 = open("char.txt")
f2 = open("copychar.txt","w")
for line in f1:
if 'a' not in line:
f2.write(line)
print('# File Copied Successfully! #')
f1.close()
f2.close()

f2 = open("copychar.txt","r")
print(f2.read())

OUTPUT:
# File Copied Successfully! #
Script Mode.
CSV Files.
Text Files.
Shortcut Key (Ctrl+N)

Char.txt
Interactive mode.
Script Mode.
The drawback of interactive mode is that we cannot save the commands that we type.
This can be overcome using the script mode.
CSV Files.
Text Files.
Shortcut Key (Ctrl+N)

Copychar.txt
Script Mode.
CSV Files.
Text Files.
Shortcut Key (Ctrl+N)
READ A TEXT FILE AND DISPLAY THE NUMBER OF VOWELS/ CONSONANTS/
UPPERCASE/ LOWERCASE / DIGITS AND OTHER CHARACTERS IN THE
FILE
f = open("vowel.txt",'r')
line = f.read()
vow=con=low=up=digit=splchar = 0
print(line)
print()
for ch in line:
if ch.isupper():
up +=1
if ch.islower():
low += 1
if ch in 'aeiouAEIOU':
vow += 1
if ch.isalpha() and ch not in 'aeiouAEIOU':
con += 1
if ch.isdigit():
digit += 1
if not ch.isalnum() and ch !=' ' and ch !='\n':
splchar += 1
print("Digits: ",digit)
print("Vowels: ",vow)
print("Consonants: ",con)
print("Upper Case: ",up)
print("Lower Case: ",low)
print("Special Characters: ",splchar)
f.close()
OUTPUT:
123--->A Text file consists of human readable characters, which can be opened by any text
editor. 456---> On the other hand, binary files are made up of non-human readable characters
& symbols, which require specific programs to access its contents---> 789.
Digits: 9
Vowels: 69
Consonants: 189
Upper Case: 3
Lower Case: 186
Special Characters: 19

Vowel.txt
123--->A Text file consists of human readable characters, which can be opened by any text
editor.
456---> On the other hand, binary files are made up of non-human readable characters &
symbols,
which require specific programs to access its contents---> 789.
READ A TEXT FILE LINE BY LINE AND DISPLAY EACH WORD SEPARATED
BY A #
f=open("mydoc.txt","w")
for i in range(4):
s=input("Enter the Contents to be written in the file:")
f.write(s)
f.write("\n")
f.close()
print()

print("Reading the Contents of the File:")


print("***************************")
f=open("Mydoc.txt",'r')
for line in f:
word=line.split()
for w in word:
print(w + '#',end ='')
print()
f.close()
OUTPUT:
Enter the Contents to be written in the file:Python Language
Enter the Contents to be written in the file:Interactive Mode
Enter the Contents to be written in the file:Script Mode
Enter the Contents to be written in the file:Structure of a Program
Reading the Contents of the File:
****************************
Python#Language#
Interactive#Mode#
Script#Mode#
Structure#of#a#Program#

Mydoc.txt
Python Language
Interactive Mode
Script Mode
Structure of a Program
BINARY FILE - INPUT A ROLL NUMBER AND UPDATE DETAILS
import pickle
def Writerecord(sroll,sname,sperc,sremark):
with open ('StudentRecord.dat','ab') as f:
srecord={"SROLL":sroll,"SNAME":sname,"SPERC":sperc,"SREMARKS":sremark}
pickle.dump(srecord,f)

def Readrecord():
with open ('StudentRecord.dat','rb') as f:
print("\n-------DISPLAY STUDENTS DETAILS--------")
print("\nRoll No.",' ','Name','\t',end='')
print('Percentage',' ','Remarks')
while True:
try:
rec=pickle.load(f)
print(' ',rec['SROLL'],'\t ' ,rec['SNAME'],'\t ',end='')
print(rec['SPERC'],'\t ',rec['SREMARKS'])
except EOFError:
break

def Input():
n=int(input("How many records you want to create :"))
for i in range(n):
sroll=int(input("Enter Roll No: "))
sname=input("Enter Name: ")
sperc=float(input("Enter Percentage: "))
sremark=input("Enter Remark: ")
Writerecord(sroll,sname,sperc,sremark)

def Modify(roll):
with open ('StudentRecord.dat','rb') as f:
newRecord=[]
while True:
try:
rec=pickle.load(f)
newRecord.append(rec)
except EOFError:
break
found=1
for i in range(len(newRecord)):
if newRecord[i]['SROLL']==roll:
name=input("Enter Name: ")
perc=float(input("Enter Percentage: "))
remark=input("Enter Remark: ")

newRecord[i]['SNAME']=name
newRecord[i]['SPERC']=perc
newRecord[i]['SREMARKS']=remark
found =1
else:
found=0
if found==0:
print("Record not found")
with open ('StudentRecord.dat','wb') as f:
for j in newRecord:
pickle.dump(j,f)

def main():
while True:
print('\nYour Choices are: ')
print('1.Insert Records')
print('2.Display Records')
print('3.Update Records')
print('4.Exit')
ch=int(input('Enter Your Choice: '))
if ch==1:
Input()
elif ch==2:
Readrecord()
elif ch==3:
r =int(input("Enter a Rollno to update: "))
Modify(r)
elif ch==4:
break
else:
print("Invalid Choice")
main()

OUTPUT :
Your Choices are:
1.Insert Records
2.Display Records
3.Update Records
4.Exit
Enter Your Choice: 1
How many records you want to create :3
Enter Roll No: 1
Enter Name: Arun
Enter Percentage: 98
Enter Remark: Excellent

Enter Roll No: 2


Enter Name: Raj
Enter Percentage: 80
Enter Remark: Good

Enter Roll No: 3


Enter Name: Sanjay
Enter Percentage: 75
Enter Remark: Good
Your Choices are:
1.Insert Records
2.Display Records
3.Update Records
4.Exit
Enter Your Choice: 2
-------DISPLAY STUDENTS DETAILS--------
Roll No. Name Percentage Remarks
1 Arun 98.0 Excellent
2 Raj 80.0 Good
3 Sanjay 75.0 Good

Your Choices are:


1.Insert Records
2.Display Records
3.Update Records
4.Exit
Enter Your Choice: 3
Enter a Rollno to update: 2
Enter Name: Ashwin
Enter Percentage: 83
Enter Remark: Good
Record not found

Your Choices are:


1.Insert Records
2.Display Records
3.Update Records
4.Exit
Enter Your Choice: 2
-------DISPLAY STUDENTS DETAILS--------
Roll No. Name Percentage Remarks
1 Arun 98.0 Excellent
2 Ashwin 83.0 Good
3 Sanjay 75.0 Good
Your Choices are:
1.Insert Records
2.Display Records
3.Update Records
4.Exit
Enter Your Choice: 4

StudentRecord.dat
€•F }”(ŒSROLL”KŒSNAME”ŒArun”ŒSPERC”G@X€ ŒSREMARKS”Œ
Excellent”u.€•C
}”(ŒSROLL”KŒSNAME”ŒAshwin”ŒSPERC”G@TÀ ŒSREMARKS”ŒGood”u.€•C
}”(ŒSROLL”KŒSNAME”ŒSanjay”ŒSPERC”G@RÀ
ŒSREMARKS”ŒGood”u.
BINARY FILE - SEARCH FOR A GIVEN ROLL NUMBER AND DISPLAY THE
NAME
import pickle
def Writerecord(sroll,sname):
with open ('StudRec.dat','ab') as f:
srecord={"SROLL":sroll,"SNAME":sname}
pickle.dump(srecord,f)

def Readrecord():
with open ('StudRec.dat','rb') as f:
print("\n-------DISPLAY STUDENTS DETAILS--------")
print("\nRoll No.",' ','Name','\t',end='')
print()
while True:
try:
rec=pickle.load(f)
print(' ',rec['SROLL'],'\t ' ,rec['SNAME'])
except EOFError:
break

def Input():
n=int(input("How many records you want to create :"))
for i in range(n):
sroll=int(input("Enter Roll No: "))
sname=input("Enter Name: ")
Writerecord(sroll,sname)

def SearchRecord(roll):
flag=False
with open ('StudRec.dat','rb') as f:
while True:
try:
rec=pickle.load(f)
if rec['SROLL']==roll:
print("Roll No:",rec['SROLL'])
print("Name:",rec['SNAME'])
flag=True
except EOFError:
break
if flag==False:
print("Record not found..............")
print("Try Again..............")

def main():
while True:
print('\nYour Choices are: ')
print('1.Insert Records')
print('2.Display Records')
print('3.Search Records (By Roll No)')
print('4.Exit')
ch=int(input('Enter Your Choice: '))
if ch==1:
Input()
elif ch==2:
Readrecord()
elif ch==3:
r=int(input("Enter a Rollno to Search: "))
SearchRecord(r)
elif ch==4:
break
else:
print("Invalid Choice")
main()
OUTPUT:
Your Choices are:
1.Insert Records
2.Display Records
3.Search Records (By Roll No)
4.Exit
Enter Your Choice: 1
How many records you want to create :2
Enter Roll No: 1
Enter Name: Robert
Enter Roll No: 2
Enter Name: Divya

Your Choices are:


1.Insert Records
2.Display Records
3.Search Records (By Roll No)
4.Exit
Enter Your Choice: 2
-------DISPLAY STUDENTS DETAILS--------
Roll No. Name
1 Robert
2 Divya

Your Choices are:


1.Insert Records
2.Display Records
3.Search Records (By Roll No)
4.Exit
Enter Your Choice: 3
Enter a Rollno to be Search: 2

Roll No: 2
Name: Divya
Your Choices are:
1.Insert Records
2 .Display Records
3.Search Records (By Roll No)
4.Exit
Enter Your Choice: 3
Enter a Rollno to be Search: 4
Record not found..............
Try Again..............

Your Choices are:


1.Insert Records
2. Display Records
3.Search Records (By Roll No)
4.Exit
Enter Your Choice: 5
Invalid Choice
Your Choices are:
1.Insert Records
2.Display Records
3.Search Records (By Roll No)
4.Exit
Enter Your Choice: 4

StudRec.dat:

€• }”(ŒSROLL”KŒSNAME”ŒRobert”u.€• }”(ŒSROLL”KŒSNAME”ŒDivya”u.
CSV FILE - MODIFY, SEARCH THE PASSWORD FOR GIVEN USER ID
import csv
# Write data into a file
field=["User Id","Password"]
data=[]
n=int(input("Enter the Number of Data:"))
for i in range(n):
uid=int(input("Enter the User Id:"))
pwd=input("Enter the Password:")
rec=[uid,pwd]
data.append(rec)

with open("log.csv","w",newline=' ') as f:


cw=csv.writer(f,delimiter=",")
cw.writerow(field)
cw.writerows(data)
print("Data Saved")

# Read data from a file


with open("log.csv","r") as f:
cr=csv.reader(f)
for row in cr:
print(row)
# Search
with open("log.csv","r") as f:
cr=csv.reader(f)
num=int(input("\nEnter the Id to Search:"))
next(cr)
for i in cr:
if int(i[0])==num:
print("Password:",i[1])
#print(i)
break
else:
print("Id Not Found")
# Modify/Update
with open("log.csv","r") as f:
field=["User Id","Password"]
data=[]
flag=0
cr=csv.reader(f)
num=int(input("\nEnter the Id to Modify:"))
next(cr)
for i in cr:
if int(i[0])==num:
print("Password:",i[1])
p=input("Enter New Password:")
data.append([num,p])
print("Record Modified")
flag=1
else:
data.append(i)
if flag==0:
print("Record Not Found")
else:
with open("log.csv","w",newline=''") as f:
cw=csv.writer(f,delimiter=",")
cw.writerow(field)
cw.writerows(data)
OUTPUT :
Enter the Number of Data:3
Enter the User Id:1
Enter the Password:Sri

Enter the User Id:2


Enter the Password:Jai

Enter the User Id:3


Enter the Password:Divya
Data Saved
['User Id', 'Password']
['1', 'Sri']
['2', 'Jai']
['3', 'Divya']

Enter the Id to Search:3


Password: Divya
Enter the Id to Modify:2
Password: Jai
Enter New Password:Hema
Record Modified

log.csv
User Id,Password
1,Sri
2,Jai
3,Divya

User Id,Password
1,Sri
2,Hema
3,Divya
CSV FILE - DELETE THE RECORD FOR GIVEN EMPNO
import csv
def addrec():
header=["Emp No","Emp Name","Dept","Salary"]
lst=[]
n=int(input("Enter the Number of Data:"))
for i in range(n):
eno=int(input("Enter the EmpNo:"))
ename=input("Enter the Name:")
dept=input("Enter the Department:")
sal=int(input("Enter the Salary:"))
rec=[eno,ename,dept,sal]
lst.append(rec)

with open("emp.csv","w",newline='') as f:
cw=csv.writer(f,delimiter=",")
cw.writerow(header)
cw.writerows(lst)
print("Data Saved\n")

def display():
with open("emp.csv","r") as f:
cr=csv.reader(f)
for i in cr:
print(i)

def showdept():
with open("emp.csv","r") as f:
cr=csv.reader(f)
dname=input("\nEnter the Dept Name:")
next(cr)
for i in cr:
if i[2]==dname.upper() or i[2]==dname.lower():
print("Dept Name:",i)
def delete():
with open("emp.csv","r") as f:
header=["Emp No","Emp Name","Dept","Salary"]
lst=[]
flag=0
cr=csv.reader(f)
num=int(input("\nEnter the EmpNo to Delete:"))
next(cr)
for i in cr:
if int(i[0])==num:
print("Record Deleted")
flag=1
else:
lst.append(i)
if flag==0:
print("Record Not Found")
else:
with open("emp.csv","w",newline='') as f:
cw=csv.writer(f,delimiter=",")
cw.writerow(header)
cw.writerows(lst)

while True:
print("1. Add Record")
print("2. Display")
print("3. Delete")
print("4. Showdept")
print("5. Exit")
ch=int(input("Enter Your Choice:"))
if ch==1:
addrec()
elif ch==2:
display()
elif ch==3:
delete()
elif ch==4:
showdept()
elif ch==5:
break
else:
print("Invalid Choice")

OUTPUT :
1. Add Record
2. Display
3. Delete
4. Showdept
5. Exit
Enter Your Choice:1
Enter the Number of Data:3
Enter the EmpNo:101
Enter the Name:Shalini
Enter the Department:CSE
Enter the Salary:25000

Enter the EmpNo:102


Enter the Name:Robert
Enter the Department:CSE
Enter the Salary:35000

Enter the EmpNo:103


Enter the Name:Priya
Enter the Department:IT
Enter the Salary:45000
Data Saved
1. Add Record
2. Display
3. Delete
4. Showdept
5. Exit
Enter Your Choice:2
['Emp No', 'Emp Name', 'Dept', 'Salary']
['101', 'Shalini', 'CSE', '25000']
['102', 'Robert', 'CSE', '35000']
['103', 'Priya', 'IT', '45000']

1. Add Record
2. Display
3. Delete
4. Showdept
5. Exit
Enter Your Choice:4
Enter the Dept Name:cse
Dept Name: ['101', 'Shalini', 'CSE', '25000']
Dept Name: ['102', 'Robert', 'CSE', '35000']

1. Add Record
2. Display
3. Delete
4. Showdept
5. Exit
Enter Your Choice:4
Enter the Dept Name:EEE
Record Not Found

1. Add Record
2. Display
3. Delete
4. Showdept
5. Exit
Enter Your Choice:3
Enter the EmpNo to Delete:102
Record Deleted

1. Add Record
2. Display
3. Delete
4. Showdept
5. Exit
Enter Your Choice:2
['Emp No', 'Emp Name', 'Dept', 'Salary']
['101', 'Shalini', 'CSE', '25000']
['103', 'Priya', 'IT', '45000']

1. Add Record
2. Display
3. Delete
4. Showdept
5. Exit
Enter Your Choice:3
Enter the EmpNo to Delete:104
Record Not Found
1. Add Record
2. Display
3. Delete
4. Showdept
5. Exit
Enter Your Choice:5

emp.csv
Emp No,Emp Name,Dept,Salary
101,Shalini,CSE,25000
102,Robert,CSE,35000
103,Priya,IT,45000
STACK USING LIST
n=int(input("Enter the number of Elements for List:"))
e=[]
while True:
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Peek")
print("5. Exit")
ch=int(input("Enter your Choice:"))
if(ch==1):
for i in range(0,n):
eid=int(input("\nEnter Employee No:"))
ename=input("Enter Employee Name:")
sal=int(input("Enter Salary:"))
emp=[eid,ename,sal]
e.append(emp)
elif(ch==2):
if(e==[]):
print("Stack Underflow")
else:
eid,ename,sal=e.pop()
print("Deleted Element is:",eid,ename,sal)
elif(ch==3):
if e==[]:
print("Stack is Empty")
else:
for i in range(len(e)-1,-1,-1):
print(e[i])
elif ch==4:
if e==[]:
print("Stack is Underflow")
else:
top=len(e)-1
print("Topmost Element is",e[top])
elif (ch==5):
break
else:
print("Invalid Choice")

OUTPUT :
Enter the number of Elements for List:3
1. Push
2. Pop
3. Display
4. Peek
5. Exit
Enter your Choice:1
Enter Employee No:101
Enter Employee Name:Raj
Enter Salary:25000

Enter Employee No:102


Enter Employee Name:Sam
Enter Salary:30000
Enter Employee No:103
Enter Employee Name:Divya
Enter Salary:35000
1. Push
2. Pop
3. Display
4. Peek
5. Exit
Enter your Choice:3
[103, 'Divya', 35000]
[102, 'Sam', 30000]
[101, 'Raj', 25000]
1. Push
2. Pop
3. Display
4. Peek
5. Exit
Enter your Choice:4
Topmost Element is [103, 'Divya', 35000]
1. Push
2. Pop
3. Display
4. Peek
5. Exit
Enter your Choice:2
Deleted Element is: 103 Divya 35000
1. Push
2. Pop
3. Display
4. Peek
5. Exit
Enter your Choice:3
[102, 'Sam', 30000]
[101, 'Raj', 25000]
1. Push
2. Pop
3. Display
4. Peek
5. Exit
Enter your Choice:5
REVERSE STRING USING STACK
def push(stk,element):
stk.append(element)

def pop(stk):
if stk==[]: return
return stk.pop()

def revstr(s):
n= len(s)
stk = []

for i in range(0,n,1):
push(stk,s[i])
s=""
for i in range(0,n,1):
s+=pop(stk)
return s

a=input("Enter the String:")


print ("Reversed string:",end=' ')
print (revstr(a))

OUTPUT :
Enter the String: Python Program
Reversed string: margorP nohtyP
PYTHON INTERFACE-ADD & DISPLAY RECORDS
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="sasi7282",database="
school")
if(mydb.is_connected()):
print('Successfully connected')
cur=mydb.cursor()

cur.execute(" create table stud(roll integer,name varchar(10),age integer,std varchar(5))")


print("Table Created")

n=int(input("Enter the No. of Records to Add:"))


L=[]
for i in range(n):
roll=int(input("\nEnter the Roll Number : "))
name=input("Enter the Name: ")
age=int(input("Enter Age of Student : "))
std=input("Enter the Standard : ")
s=[roll,name,age,std]
L.append(s)
sql="insert into stud (roll,name,age,std) values (%s,%s,%s,%s)"
cur.execute(sql,s)
print ("Record inserted successfully")
mydb.commit()
cur.execute("select * from stud")
rec=cur.fetchall()
for x in rec:
print(x)
cur.close();
mydb.close()
OUTPUT :
Successfully Connected
Table Created
Enter the No. of Records to Add:2

Enter the Roll Number : 1


Enter the Name: ss
Enter Age of Student : 12
Enter the Standard : 5
Record inserted successfully

Enter the Roll Number : 2


Enter the Name: hh
Enter Age of Student : 13
Enter the Standard : 6
Record inserted successfully
(1, 'ss', 12, '5')
(2, 'hh', 13, '6')
PYTHON INTERFACE-SEARCH RECORD
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="sasi7282",database="
school")
if(mydb.is_connected()):
print('Successfully connected')
cur=mydb.cursor()

def search():
while True:
print("Select the Search Criteria : ")
print("1. Roll")
print("2. Name")
print("3. Age")
print("4. Standard")
print("5. All")
print("6. Exit")

ch=int(input("Enter the Choice : "))


if ch==1:
s=int(input("Enter Roll No. : "))
rl=(s,)
sql="select * from stud where roll=%s"
cur.execute(sql,rl)
elif ch==2:
s=input("Enter Name : ")
rl=(s,)
sql="select * from stud where name=%s"
cur.execute(sql,rl)
elif ch==3:
s=int(input("Enter Age : "))
rl=(s,)
sql="select * from stud where age=%s"
cur.execute(sql,rl)
elif ch==4:
s=input("Enter Standard : ")
rl=(s,)
sql="select * from stud where std=%s"
cur.execute(sql,rl)
elif ch==6:
break
elif ch==5:
sql="select * from stud"
cur.execute(sql)
res=cur.fetchall()
print("Student Details are as Follows : ")
print("(Roll, Name, Age, Std)")
for x in res:
print(x)
search()

OUTPUT :
Successfully connected
Select the Search Criteria :
1. Roll
2. Name
3. Age
4. Standard
5. All
6. Exit
Enter the Choice : 1
Enter Roll No. : 2
Student Details are as Follows :
(Roll, Name, Age, Std)
(2, 'Robert', 15, '10')
Select the Search Criteria :
1. Roll
2. Name
3. Age
4. Standard
5. All
6. Exit
Enter the Choice : 2
Enter Name : Nisha
Student Details are as Follows :
(Roll, Name, Age, Std)
(3, 'Nisha', 16, '11')

Select the Search Criteria :


1. Roll
2. Name
3. Age
4. Standard
5. All
6. Exit
Enter the Choice : 3
Enter Age : 14
Student Details are as Follows :
(Roll, Name, Age, Std)
(1, 'Sam', 14, '9')
Select the Search Criteria :
1. Roll
2. Name
3. Age
4. Standard
5. All
6. Exit
Enter the Choice : 4
Enter Standard : 10
Student Details are as Follows :
(Roll, Name, Age, Std)
(2, 'Robert', 15, '10')

Select the Search Criteria :


1. Roll
2. Name
3. Age
4. Standard
5. All
6. Exit

Enter the Choice : 5


Student Details are as Follows :
(Roll, Name, Age, Std)
(1, 'Sam', 14, '9')
(2, 'Robert', 15, '10')
(3, 'Nisha', 16, '11')
Select the Search Criteria :
1. Roll
2. Name
3. Age
4. Standard
5. All
6. Exit
Enter the Choice : 6
PYTHON INTERFACE-UPDATE RECORD
import mysql.connector as mycon
mydb = mycon.connect(host='localhost',user='root',passwd="sasi7282",database="school")
cur = mydb.cursor()
print('Welcome to Student Details Update Screen... ')
rno = int(input("Enter Student's Roll Number to Edit :"))
query="select * from stud where roll={}".format(rno)
cur.execute(query)
res = cur.fetchall()

if cur.rowcount<=0:
print("NO MATCH FOUND")
else:
for row in res:
print(row[0],row[1],row[2],row[3])

ans = input("Want to Update ? (Y/N)")


if ans=="y" or ans=="Y":
n = input("Enter New Name to Update (Enter Old Value if not to Update) :")
a = int(input("Enter New Age to Update (Enter Old Value if not to Update) :"))
s = input("Enter New Std to Update (Enter Old Value if not to Update) :")
query="update stud set name='{}',age={},std={} where roll={}".format(n,a,s,rno)
cur.execute(query)
mydb.commit()
print("\nRECORD UPDATED")
OUTPUT :
Welcome to Student Details Update Screen...
Enter Student's Roll Number to Edit :2
2 hh 13 6
Want to Update ? (Y/N)y
Enter New Name to Update (Enter Old Value if not to Update) :jai
Enter New Age to Update (Enter Old Value if not to Update) :15
Enter New Std to Update (Enter Old Value if not to Update) :9

RECORD UPDATED
================= RESTART: C:/Users/Asus/Desktop/Impln Stack.py =====
Welcome to Student Details Update Screen...
Enter Student's Roll Number to Edit :3
NO MATCH FOUND
Want to Update ? (Y/N)n
PYTHON INTERFACE-DELETE RECORD
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="sasi7282",database="
school")
if(mydb.is_connected()):
print('Successfully Connected')
cur=mydb.cursor()

rno=int(input("Enter the Roll Number of the Student to Delete : "))


sql="Delete from stud where roll={}".format(rno)
cur.execute(sql)
print('Record Deleted!!!\n')
mydb.commit()

print("Records in Table After Deletion:")


cur.execute("select * from stud")
rec=cur.fetchall()
for x in rec:
print(x)

OUTPUT :
Successfully Connected
Enter the Roll Number of the Student to Delete : 2
Record Deleted!!!

Records in Table After Deletion:


(1, 'sri', 14, '7')
(3, 'sam', 13, '6')

You might also like