GR 12-Program List & Pgms With Output (1-22) Edit
GR 12-Program List & Pgms With Output (1-22) Edit
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
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
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
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()
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
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
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..............
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)
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
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
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
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()
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")
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')
if cur.rowcount<=0:
print("NO MATCH FOUND")
else:
for row in res:
print(row[0],row[1],row[2],row[3])
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()
OUTPUT :
Successfully Connected
Enter the Roll Number of the Student to Delete : 2
Record Deleted!!!