0% found this document useful (0 votes)
6 views23 pages

Cs Practical File Xii

The document outlines Python code for managing text and binary files, including user-defined functions for creating, viewing, and manipulating text files (STORY.TXT and NOTES.TXT) and binary files (ACCOUNTS.DAT and CANDIDATE.DAT). It includes menu-driven interfaces for user interaction, allowing operations such as adding content, displaying content, counting words, and managing account details. The code demonstrates practical applications of file handling, data storage, and basic data processing in Python.

Uploaded by

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

Cs Practical File Xii

The document outlines Python code for managing text and binary files, including user-defined functions for creating, viewing, and manipulating text files (STORY.TXT and NOTES.TXT) and binary files (ACCOUNTS.DAT and CANDIDATE.DAT). It includes menu-driven interfaces for user interaction, allowing operations such as adding content, displaying content, counting words, and managing account details. The code demonstrates practical applications of file handling, data storage, and basic data processing in Python.

Uploaded by

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

TEXT FILE CODES

1. Define the following user-defined functions


a. GetStory(), to create a text file named STORY.TXT, which should contain
text lines entered by the user.
b. ViewStory(), to read and display the entire content of text file STORY.TXT
on the screen.
c. Words(), to read and display each word of the text file STORY.TXT in
different lines on the screen.
d. AllWords(), to read, count and display number of words present in the
text file STORY.TXT Also, write menu driven code to call the above functions
using a loop.

Code

def getstory():
f = open('STORY.TXT', 'w')
while True:
a=input("enter the string")+"\n"
f.writelines(a)
n=input("do you want to add more")
if n.lower()=='no':
break
print("string inputted successfully")
f.close()
def viewstory():
f=open('STORY.TXT')
na=f.read()
print(na)
f.close()
def words():
f=open('STORY.TXT')
na=f.read()
s=na.split()
for i in s:
if i.isdigit()==False:
print(i)
f.close()
def allwords():
f = open('STORY.TXT')
na = f.read()
s = na.split()
d=0
for i in s:
if i.isdigit()==False:
print(i)
d+=1
print("no of words in text file are", d)
f.close()
while True:
print('''WELCOME TO MAIN MENU
[1];CREATE A TEXT FILE
[2];DISPLAY TEXT FILE
[3];DISPLAY EACH WORD OF TEXT FILE
[4];COUNT AND DISPLAY EACH WORD OF TEXT FILE
[5];EXIT''')
q=int(input("choose one"))
if q==1:
getstory()
elif q==2:
viewstory()
elif q==3:
words()
elif q==4:
allwords()
elif q==5:
print("thank you")
break
else:
print("invalid selection")

OUTPUT
WELCOME TO MAIN MENU
[1];CREATE A TEXT FILE
[2];DISPLAY TEXT FILE
[3];DISPLAY EACH WORD OF TEXT FILE
[4];COUNT AND DISPLAY EACH WORD OF TEXT FILE
[5];EXIT
choose one2
GOOD MORNING
Today is sunday
29 september

WELCOME TO MAIN MENU


[1];CREATE A TEXT FILE
[2];DISPLAY TEXT FILE
[3];DISPLAY EACH WORD OF TEXT FILE
[4];COUNT AND DISPLAY EACH WORD OF TEXT FILE
[5];EXIT
choose one3
GOOD
MORNING
Today
is
sunday
september
WELCOME TO MAIN MENU
[1];CREATE A TEXT FILE
[2];DISPLAY TEXT FILE
[3];DISPLAY EACH WORD OF TEXT FILE
[4];COUNT AND DISPLAY EACH WORD OF TEXT FILE
[5];EXIT
choose one4
GOOD
MORNING
Today
is
sunday
september
no of words in text file are 6
WELCOME TO MAIN MENU
[1];CREATE A TEXT FILE
[2];DISPLAY TEXT FILE
[3];DISPLAY EACH WORD OF TEXT FILE
[4];COUNT AND DISPLAY EACH WORD OF TEXT FILE
[5];EXIT
choose one5
thank you

2 Write a program with the following user-defined functions,


a. CreateNotes() - to create a text file NOTES.TXT to have text entered
by user as lines of text
b. CountAVD(), to read the contents of the text file NOTES.TXT and
count and print the number of Alphabets, Vowels and Digits
present in the file.
c. ShowNotes(), to display the contents of text file NOTES.TXT
d. RevText(), to read the contents of the text file NOTES.TXT, and
print the reverse of those lines which start with an alphabet ‘T’.
e. CountLines(), to read, count and display the number of lines
present in the text file NOTES.TXT
Also, write menu driven code to call the above functions using a loop.

CODE

def createnotes():
f = open('notes.txt', 'w')
while True:
a=input("enter the string")+"\n"
f.writelines(a)
n=input("do you want to add more")
if n.lower()=='no':
break
print("string inputted successfully")
f.close()
def shownotes():
f=open('notes.txt')
na=f.read()
print(na)
f.close()
def countAVD():
f=open('notes.txt')
na=f.read()
a=0
v=0
d=0
for i in range(len(na)):
if na[i] != ' ' and na[i].isdigit()==False:
a+=1
if na[i] in 'aeiouAEIOU':
v+=1
if na[i].isdigit():
d+=1
print("number of alphabets",a)
print("number of vowels",v)
print("number of digits",d)
f.close()
def revtext():
f=open('notes.txt')
na=f.read()
s=na.splitlines()
for i in s:
if i[0] in 't T':
print(i[::-1])
f.close()
def countlines():
f=open('notes.txt')
na=f.read()
s=na.splitlines()
print(s)
print(len(s))
while True:
print('''WELCOME TO MAIN MENU
[1];CREATE A TEXT FILE
[2];COUNT NUMBER OF ALPHABETS DIGITS AND VOWELS
[3];DISPLAY TEXT FILE
[4];REVERSE THOSE LINES STARTING WITH T
[5];COUNT NUMBER OF LINES
[6];EXIT''')
a=int(input('choose one'))
if a==1:
createnotes()
elif a==2:
countAVD()
elif a==3:
shownotes()
elif a==4:
revtext()
elif a==5:
countlines()
elif a==6:
print('thank you')
break
else:
print('invalid choice')

OUTPUT
WELCOME TO MAIN MENU
[1];CREATE A TEXT FILE
[2];COUNT NUMBER OF ALPHABETS DIGITS AND VOWELS
[3];DISPLAY TEXT FILE
[4];REVERSE THOSE LINES STARTING WITH T
[5];COUNT NUMBER OF LINES
[6];EXIT
choose one1
enter the stringGOOD MORNING
do you want to add moreyes
string inputted successfully
enter the stringThis is a text file
do you want to add moreyes
string inputted successfully
enter the stringToday is sunday
do you want to add moreyes
string inputted successfully
enter the string29 september
do you want to add moreno
WELCOME TO MAIN MENU
[1];CREATE A TEXT FILE
[2];COUNT NUMBER OF ALPHABETS DIGITS AND VOWELS
[3];DISPLAY TEXT FILE
[4];REVERSE THOSE LINES STARTING WITH T
[5];COUNT NUMBER OF LINES
[6];EXIT
choose one2
number of alphabets 52
number of vowels 18
number of digits 2
WELCOME TO MAIN MENU
[1];CREATE A TEXT FILE
[2];COUNT NUMBER OF ALPHABETS DIGITS AND VOWELS
[3];DISPLAY TEXT FILE
[4];REVERSE THOSE LINES STARTING WITH T
[5];COUNT NUMBER OF LINES
[6];EXIT
choose one3
GOOD MORNING
This is a text file
Today is sunday
29 september

WELCOME TO MAIN MENU


[1];CREATE A TEXT FILE
[2];COUNT NUMBER OF ALPHABETS DIGITS AND VOWELS
[3];DISPLAY TEXT FILE
[4];REVERSE THOSE LINES STARTING WITH T
[5];COUNT NUMBER OF LINES
[6];EXIT
choose one4
elif txet a si sihT
yadnus si yadoT
WELCOME TO MAIN MENU
[1];CREATE A TEXT FILE
[2];COUNT NUMBER OF ALPHABETS DIGITS AND VOWELS
[3];DISPLAY TEXT FILE
[4];REVERSE THOSE LINES STARTING WITH T
[5];COUNT NUMBER OF LINES
[6];EXIT
choose one5
['GOOD MORNING', 'This is a text file', 'Today is sunday', '29 september']
4
WELCOME TO MAIN MENU
[1];CREATE A TEXT FILE
[2];COUNT NUMBER OF ALPHABETS DIGITS AND VOWELS
[3];DISPLAY TEXT FILE
[4];REVERSE THOSE LINES STARTING WITH T
[5];COUNT NUMBER OF LINES
[6];EXIT
choose one6
thank you

BINARY FILE CODES


1. Write a Python code with the following functions performing
mentioned operations on a binary file “ACCOUNTS.DAT” containing
lists with [<Ano of type int>,<Name of type string>,<Balance of
type float>]
a. Register(), to add details of new account holders as
entered by the user in the binary file named
ACCOUNTS.DAT.
b. Transact( ), to perform a transaction i.e. Deposit or Withdraw an
Amount in an Account Holders Balance whose Acno is entered
by the user from ACCOUNTS.DAT. Note: an Account Holder must
always have a minimum Balance of Rs 500 in his/her Account.
c. DisplayAll( ) to display the details of all Account Holders from
ACCOUNTS.DAT
d. BankBalance() to find and return the sum of Balance of
all the account holders from ACCOUNTS.DAT
Also, write a menu driven code to call the above functions using a loop.

Code
import pickle
def register():
r=[]
data=[]
while True:
n=int(input("enter account number"))
a=input("enter customer name")
b=float(input("enter account balance"))
r=[n,a,b]
data.append(r)
s=input("do you want to add more")
if s.lower()=='n':
break
f=open('accounts.dat','ab')
pickle.dump(data,f)
f.close()
def transact():
f=open("accounts.dat",'rb+')
na=pickle.load(f)
found=0
n = int(input('enter account number'))
for i in na:
if i[0] == n:
found=1
print('''what do you want to do
[1];deposit
[2];withdraw''')
a=int(input('enter your choice'))
d=i[2]
if a==1:
s=float(input('enter amount to be deposited'))
i[2]=d+s
elif a==2:
if i[2]>=500:
w=float(input('enter amount to be withdrawn'))
if w>i[2]:
print('insufficient funds')
else:
i[2]=d-w
else:
print('insufficient funds')
else:
print('invalid choice')
if found==1:
f.seek(0)
pickle.dump(na,f)
f.close()
else:
print('account not found')
def displayall():
f=open('accounts.dat','rb')
na=pickle.load(f)
print(na)
f.close()
def bankbalance():
f=open('accounts.dat','rb')
na=pickle.load(f)
s=0
for i in na:
s+=i[2]
print('total balance=',s)
f.close()
while True:
print('''WELCOME TO MAIN MENU
[1];ENTER DETAILS OF NEW ACCOUNT HOLDERS
[2];DEPOSIT OR WITHDRAW AN AMOUNT
[3];DISPLAY ACCOUNT DETAILS
[4];TOTAL BALANCE
[5];EXIT''')
a=int(input('enter your choice'))
if a==1:
register()
elif a==2:
transact()
elif a==3:
displayall()
elif a==4:
bankbalance()
elif a==5:
print('thank you')
break
else:
print('invalid selection')

OUTPUT
WELCOME TO MAIN MENU
[1];ENTER DETAILS OF NEW ACCOUNT HOLDERS
[2];DEPOSIT OR WITHDRAW AN AMOUNT
[3];DISPLAY ACCOUNT DETAILS
[4];TOTAL BALANCE
[5];EXIT
enter your choice1
enter account number1
enter customer nameram
enter account balance670
do you want to add moreyes
enter account number2
enter customer nameamit
enter account balance450
do you want to add moreyes
enter account number3
enter customer nameakash
enter account balance1000
do you want to add moreno
WELCOME TO MAIN MENU
[1];ENTER DETAILS OF NEW ACCOUNT HOLDERS
[2];DEPOSIT OR WITHDRAW AN AMOUNT
[3];DISPLAY ACCOUNT DETAILS
[4];TOTAL BALANCE
[5];EXIT
enter your choice2
enter account number2
what do you want to do
[1];deposit
[2];withdraw
enter your choice2
insufficient funds
WELCOME TO MAIN MENU
[1];ENTER DETAILS OF NEW ACCOUNT HOLDERS
[2];DEPOSIT OR WITHDRAW AN AMOUNT
[3];DISPLAY ACCOUNT DETAILS
[4];TOTAL BALANCE
[5];EXIT
enter your choice2
enter account number2
what do you want to do
[1];deposit
[2];withdraw
enter your choice1
enter amount to be deposited400
WELCOME TO MAIN MENU
[1];ENTER DETAILS OF NEW ACCOUNT HOLDERS
[2];DEPOSIT OR WITHDRAW AN AMOUNT
[3];DISPLAY ACCOUNT DETAILS
[4];TOTAL BALANCE
[5];EXIT
enter your choice3
[[1, 'ram', 670.0], [2, 'amit', 850.0], [3, 'akash', 1000.0]]
WELCOME TO MAIN MENU
[1];ENTER DETAILS OF NEW ACCOUNT HOLDERS
[2];DEPOSIT OR WITHDRAW AN AMOUNT
[3];DISPLAY ACCOUNT DETAILS
[4];TOTAL BALANCE
[5];EXIT
enter your choice4
total balance= 2520.0
WELCOME TO MAIN MENU
[1];ENTER DETAILS OF NEW ACCOUNT HOLDERS
[2];DEPOSIT OR WITHDRAW AN AMOUNT
[3];DISPLAY ACCOUNT DETAILS
[4];TOTAL BALANCE
[5];EXIT
enter your choice5
thank you

2 Write a Python code with the following functions performing


mentioned operations on a binary file “CANDIDATE.DAT”
containing lists with [<Candidate no of type int>,<Cname of type
string>,<Score of type float>]
a. Enrol(), to add details of new CANDIDATEs from the user and
save in “CANDIDATE.DAT”.
b. GetPass(), to read content from “CANDIDATE.DAT” and
display details of those candidates whose Score is>=50
c. ShowAll(), to display the entire content of “CANDIDATE.DAT”
d. AverageScore(), to find and return the average of Score from
“CANDIDATE.DAT” Also, write menu driven options to call
the above functions using a loop.

CODE
import pickle
def enrol():
r=[]
data=[]
while True:
n=int(input("enter candidate number"))
a=input("enter candidate name")
b=float(input("enter candidate score"))
r=[n,a,b]
data.append(r)
s=input("wanna add more")
if s.lower()=='n':
break
f=open('candidate.dat','wb')
pickle.dump(data,f)
f.close()
def getpass():
f=open("candidate.dat",'rb')
na=pickle.load(f)
for i in na:
if i[2]>=50:
print('candidates with score greater than 50 are',i)
f.close()
def showall():
f=open('candidate.dat','rb')
na=pickle.load(f)
print(na)
f.close()
def averagescore():
f=open('candidate.dat','rb')
na=pickle.load(f)
s=0
for i in na:
s+=i[2]
print('average score=',s)
f.close()
while True:
print('''WELCOME TO MAIN MENU
[1];CREATE A BINARY FILE
[2];CANDIDATES WITH SCORE GREATER THAN 50
[3];DISPLAY BINARY FILE
[4];AVERAGE SCORE
[5];EXIT''')
a=int(input('enter your choice'))
if a==1:
enrol()
elif a==2:
getpass()
elif a==3:
showall()
elif a==4:
averagescore()
elif a==5:
print('thank you')
break
else:
print('invalid selection')
OUTPUT
WELCOME TO MAIN MENU
[1];CREATE A BINARY FILE
[2];CANDIDATES WITH SCORE GREATER THAN 50
[3];DISPLAY BINARY FILE
[4];AVERAGE SCORE
[5];EXIT
enter your choice1
enter candidate number1
enter candidate nameamit
enter candidate score67.7
wanna add moreyes
enter candidate number2
enter candidate nameakash
enter candidate score45.5
wanna add moreyes
enter candidate number3
enter candidate namerohit
enter candidate score89.7
wanna add moreyes
enter candidate number4
enter candidate namemohit
enter candidate score32.3
wanna add moreno
WELCOME TO MAIN MENU
[1];CREATE A BINARY FILE
[2];CANDIDATES WITH SCORE GREATER THAN 50
[3];DISPLAY BINARY FILE
[4];AVERAGE SCORE
[5];EXIT
enter your choice2
[1, 'amit', 67.7]
[3, 'rohit', 89.7]
WELCOME TO MAIN MENU
[1];CREATE A BINARY FILE
[2];CANDIDATES WITH SCORE GREATER THAN 50
[3];DISPLAY BINARY FILE
[4];AVERAGE SCORE
[5];EXIT
enter your choice3
[[1, 'amit', 67.7], [2, 'akash', 45.5], [3, 'rohit', 89.7], [4, 'mohit',
32.3]]
WELCOME TO MAIN MENU
[1];CREATE A BINARY FILE
[2];CANDIDATES WITH SCORE GREATER THAN 50
[3];DISPLAY BINARY FILE
[4];AVERAGE SCORE
[5];EXIT
enter your choice4
average score= 58.8
WELCOME TO MAIN MENU
[1];CREATE A BINARY FILE
[2];CANDIDATES WITH SCORE GREATER THAN 50
[3];DISPLAY BINARY FILE
[4];AVERAGE SCORE
[5];EXIT
enter your choice5
thank you

CSV FILE CODES


1. Write a Python code with the following functions performing
mentioned operations on a CSV file “STUDENTS.CSV” containing
lists with [<Roll no of type int>,<Class of type string>,<Name of
type string>,<marks of type int>]
a. Getcsv(), to add details of new students as entered by the
user in the CSV file named STUDENTS.CSV.
b. Showcsv( ), to display the details of CSV file.
c. Countcsv( ) to count number of records in CSV file.
d. Removerec() to delete a record from CSV file.
e. Editmarks(),to edit marks of a student in CSV file.

CODE
import csv
def getcsv():
r=['Roll','Class','Name','Marks']
data=[]
while True:
a=int(input("enter roll number"))
b=input("enter class")
c=input("enter name")
d=int(input("enter marks obtained"))
rc=[a,b,c,d]
data.append(rc)
e=input("do you want to add more")
if e.lower()=='no':
break
with open('students.csv','w',newline='') as f:
s=csv.writer(f,delimiter=',')
s.writerow(r)
for i in data:
s.writerow(i)
print('file created successfully')

def showcsv():
with open('students.csv','r') as f:
na=csv.reader(f)
for i in na:
print(','.join(i))
def countcsv():
with open('students.csv','r') as f:
na=csv.reader(f)
rc=[]
v=0
for i in na:
if na.line_num == 0:
continue
rc.append(i)
v=len(list(na))
print("number of records in csv file are",v)
def removerec():
n=int(input("enter student roll number whose record to be deleted"))
l=[]
with open('students.csv','r') as f:
next(f)
na=csv.reader(f)
for i in na:
if int(i[0])!=n:
l.append(i)
f=open('students.csv','w',newline='')
x=csv.writer(f)
x.writerows(l)
print('record deleted')
f.close()
def editmarks():
n=input("enter student name whose marks are to be edited")
l=[]
found=0
with open('students.csv','r') as f:
na=csv.reader(f)
for i in na:
if i[2]==n:
s=int(input("enter new marks"))
i[3]=str(s)
found=1
l.append(i)
if found==1:
with open('students.csv','w',newline='') as f:
x=csv.writer(f)
x.writerows(l)
print("marks updated successfully")
else:
print("record does not exist")
while True:
print('''WELCOME TO MAIN MENU
[1];CREATE A CSV FILE
[2];DISPLAY ALL RECORDS OF CSV FILE
[3];DISPLAY NUMBER OF RECORDS
[4];DELETE A RECORD
[5];EDIT MARKS
[6];EXIT''')
a=int(input('enter your choice'))
if a==1:
getcsv()
elif a==2:
showcsv()
elif a==3:
countcsv()
elif a==4:
removerec()
elif a==5:
editmarks()
elif a==6:
print('thank you')
break
else:
print('invalid selection')

OUTPUT
WELCOME TO MAIN MENU
[1];CREATE A CSV FILE
[2];DISPLAY ALL RECORDS OF CSV FILE
[3];DISPLAY NUMBER OF RECORDS
[4];DELETE A RECORD
[5];EDIT MARKS
[6];EXIT
enter your choice1
enter roll number1
enter classXII
enter nameamit
enter marks obtained89
do you want to add moreyes
enter roll number2
enter classXII
enter nameakash
enter marks obtained76
do you want to add moreyes
enter roll number3
enter classXII
enter namemohit
enter marks obtained75
do you want to add moreyes
enter roll number4
enter classXII
enter nameram
enter marks obtained85
do you want to add moreno
file created successfully
WELCOME TO MAIN MENU
[1];CREATE A CSV FILE
[2];DISPLAY ALL RECORDS OF CSV FILE
[3];DISPLAY NUMBER OF RECORDS
[4];DELETE A RECORD
[5];EDIT MARKS
[6];EXIT
enter your choice2
Roll,Class,Name,Marks
1,XII,amit,89
2,XII,akash,76
3,XII,mohit,75
4,XII,ram,85
WELCOME TO MAIN MENU
[1];CREATE A CSV FILE
[2];DISPLAY ALL RECORDS OF CSV FILE
[3];DISPLAY NUMBER OF RECORDS
[4];DELETE A RECORD
[5];EDIT MARKS
[6];EXIT
enter your choice3
number of records in csv file are 4
WELCOME TO MAIN MENU
[1];CREATE A CSV FILE
[2];DISPLAY ALL RECORDS OF CSV FILE
[3];DISPLAY NUMBER OF RECORDS
[4];DELETE A RECORD
[5];EDIT MARKS
[6];EXIT
enter your choice4
enter student roll number whose record to be deleted1
record deleted
WELCOME TO MAIN MENU
[1];CREATE A CSV FILE
[2];DISPLAY ALL RECORDS OF CSV FILE
[3];DISPLAY NUMBER OF RECORDS
[4];DELETE A RECORD
[5];EDIT MARKS
[6];EXIT
enter your choice2
2,XII,akash,76
3,XII,mohit,75
4,XII,ram,85
WELCOME TO MAIN MENU
[1];CREATE A CSV FILE
[2];DISPLAY ALL RECORDS OF CSV FILE
[3];DISPLAY NUMBER OF RECORDS
[4];DELETE A RECORD
[5];EDIT MARKS
[6];EXIT
enter your choice5
enter student name whose marks are to be editedakash
enter new marks85
marks updated successfully
WELCOME TO MAIN MENU
[1];CREATE A CSV FILE
[2];DISPLAY ALL RECORDS OF CSV FILE
[3];DISPLAY NUMBER OF RECORDS
[4];DELETE A RECORD
[5];EDIT MARKS
[6];EXIT
enter your choice2
2,XII,akash,85
3,XII,mohit,75
4,XII,ram,85
WELCOME TO MAIN MENU
[1];CREATE A CSV FILE
[2];DISPLAY ALL RECORDS OF CSV FILE
[3];DISPLAY NUMBER OF RECORDS
[4];DELETE A RECORD
[5];EDIT MARKS
[6];EXIT
enter your choice6
thank you

STACK CODE
1. Write a Python code with the following functions performing
mentioned operations on a stack containing lists with [<Item code
of class int >,<name of type string>,<quantity of type int>]
a. push(), to add details of items in a stack.
b. pop( ), to delete element from stack.
c. display( ) to display stack.

CODE
s=[]
def push():
while True:
a=int(input('enter item number'))
b=input('enter item name')
c=int(input("enter item price"))
r=[a,b,c]
s.append(r)
a=input("do you want to add more")
if a.lower()=='no':
break
print("element inputted successfully")
def pop():
if len(s)==0:
print("underflow")
else:
print("element removed",s.pop())
def display():
for i in range(len(s)-1,-1,-1):
print(s[i])
while True:
print(''' MAIN MENU
[1];ENTER ELEMENT TO STACK
[2];DELETE AN ELEMENT FROM STACK
[3];DISPLAY STACK
[4];EXIT''')
a=int(input("enter your choice"))
if a==1:
push()
elif a==2:
pop()
elif a==3:
display()
elif a==4:
break
print("thank you")
else:
print("invalid choice")

OUTPUT
MAIN MENU
[1];ENTER ELEMENT TO STACK
[2];DELETE AN ELEMENT FROM STACK
[3];DISPLAY STACK
[4];EXIT
enter your choice1
enter item number1
enter item namemilk
enter item price40
do you want to add moreyes
enter item number2
enter item namenoodles
enter item price30
do you want to add moreyes
enter item number3
enter item namebread
enter item price45
do you want to add moreno
MAIN MENU
[1];ENTER ELEMENT TO STACK
[2];DELETE AN ELEMENT FROM STACK
[3];DISPLAY STACK
[4];EXIT
enter your choice3
[3, 'bread', 45]
[2, 'noodles', 30]
[1, 'milk', 40]
MAIN MENU
[1];ENTER ELEMENT TO STACK
[2];DELETE AN ELEMENT FROM STACK
[3];DISPLAY STACK
[4];EXIT
enter your choice2
element removed [3, 'bread', 45]
MAIN MENU
[1];ENTER ELEMENT TO STACK
[2];DELETE AN ELEMENT FROM STACK
[3];DISPLAY STACK
[4];EXIT
enter your choice3
[2, 'noodles', 30]
[1, 'milk', 40]
MAIN MENU
[1];ENTER ELEMENT TO STACK
[2];DELETE AN ELEMENT FROM STACK
[3];DISPLAY STACK
[4];EXIT
enter your choice4
Thank you

LIST CODES
1. Write a Python code with the following functions:
a. AddValues(L) - To add integer values entered by the user in the list
L
b. DispValues(L) - To display values of L
c. SwapPair(L) - To re-arrange the content of L by swapping each
pair of adjacent neighbouring values
d. SwapHalf(L) - To re-arrange content of L by swapping first half of
the list with second half of the list
Also, call the above functions in the order as a, b, c, b, d and b.

CODE
def addvalues(l):
while True:
a=int(input("enter element"))
l.append(a)
n=input("do you want to add more")
if n.lower()=='no':
break
def dispvalues(l):
print(l)
def swapair(l):
if len(l)%2==0:
for i in range(0,len(l),2):
l[i],l[i+1]=l[i+1],l[i]
else:
for i in range(0,len(l)-1,2):
l[i],l[i+1]=l[i+1],l[i]
def swaphalf(l):
n=len(l)//2
for i in range(n):
l[i],l[n+i]=l[n+i],l[i]
l=[]
addvalues(l)
dispvalues(l)
swapair(l)
dispvalues(l)
swaphalf(l)
dispvalues(l)

OUTPUT
enter element1
do you want to add moreyes
enter element2
do you want to add moreyes
enter element3
do you want to add moreyes
enter element4
do you want to add moreyes
enter element5
do you want to add moreno
[1, 2, 3, 4, 5]
[2, 1, 4, 3, 5]
[4, 3, 2, 1, 5]

2 Write a Python code to perform the following on a tuple


T=(10,40,20,30,50,70)
a. To display the content of T in reverse order
b. To add and display the sum of values stored in T
c. To find and display minimum and maximum values present in T
d. To display sum of each adjacent pair of values
e. To find those pair (any pair 1st-2nd, 1st-5th, 3rd-6th,...) of
values from the content of T, whose sum is same as one of
the values in T

CODE
t=(10,40,20,30,50,70)
print('Content of T in reverse order is',end="")
print(t[::-1])
s=0
for i in t:
s+=i
print("Sum of values stored in T =",s)
min=t[0]
max=t[0]
for i in range(len(t)):
if t[i]<min:
min=t[i]
if t[i]>max:
max=t[i]
print("Minimum value of T is",min)
print("Maximum value of T is",max)
print("Sum each adjacent pair of value")
s=0
for i in range(0,len(t),2):
s=t[i]+t[i+1]
print(s,end=",")
s=0
print()
s=0
l=[]
for i in t:
a=t.index(i)
for j in t:
b=t.index(j)
s=i+j
if s in t:
v=[a+1,b+1]
l.append(v)
print("Those pair whose sum is present in the tuple are ",l)

OUTPUT
Content of T in reverse order is(70, 50, 30, 20, 40, 10)
Sum of values stored in T = 220
Minimum value of T is 10
Maximum value of T is 70
Sum each adjacent pair of value
50,50,120,
Those pair whose sum is present in the tuple are [[1, 1], [1, 2], [1,
3], [1, 4], [2, 1], [2, 4], [3, 1], [3, 3], [3, 4], [3, 5], [4, 1], [4,
2], [4, 3], [5, 3]]

PYTHON MySQL INTERFACE


Q; Create a MySQL table named EMPLOYEE using MySQL python interface

1. Addrec(),to add records to table EMPLOYEE.


2. Displayrec(),to display records in the table EMPLOYEE.
3. Editsalary(),to edit salary of an employee.
4. Removerec(),to delete a record from table EMPLOYEE.

CODE
Establishing python MySQL connectivity and creating a database:-

import mysql.connector as c
con=c.connect(user='root',password='keshav',host='localhost',database='project')
cur=con.cursor()
query="create table employee(EMP_NO int primary key, EMP_NAME varchar(20),DEPARTMENT
varchar(20),SALARY int);"
cur.execute(query)
con.commit()
cur.close()
con.close()

Working on the table:-

import mysql.connector as c
con=c.connect(user='root',password='keshav',host='localhost',database='project')
cur=con.cursor()

def addrec():
a=int(input("enter employee number"))
b=input("employee Name")
c=input("department")
d=input("salary")
query='insert into employee values({},"{}","{}",{})'.format(a,b,c,d)
cur.execute(query)
con.commit()
print("Record inserted successfully")
def displayrec():
query="select * from employee"
cur.execute(query)
s=cur.fetchall()
print("records inserted in table are")
print('emp_no \t Name \t department \tsalary')
for i in s:
for j in i:
print(j,end='\t')
print()
def editsalary():
a=int(input("enter employee number whose salary is updated"))
b=input("enter new salary")
query='update employee set SALARY="{}" where EMP_NO={}'.format(b,a)
cur.execute(query)
con.commit()
print("\n salary updated")

def removerec():
a=int(input("Which employee's record to delete :-"))
query='Delete from employee where EMP_NO={}'.format(a)
cur.execute(query)
con.commit()
print("\n Record deleted")

while True:
print('''EMPLOYEE RECORDS
[1];ADD NEW RECORD
[2];DISPLAY RECORDS
[3];EDIT EMPLOYEE SALARY
[4];DELETE A RECORD
[5];EXIT''')
na= input("Enter your choice ")
if na == '1':
addrec()
elif na == '2':
displayrec()
elif na == '3':
editsalary()
elif na == '4':
removerec()
elif na == '5':
print("thank you")
break
else:
print("Invalid choice")
cur.close()
con.close()

OUTPUT
EMPLOYEE RECORDS
[1];ADD NEW RECORD
[2];DISPLAY RECORDS
[3];EDIT EMPLOYEE SALARY
[4];DELETE A RECORD
[5];EXIT
Enter your choice 1
enter employee number1
employee Nameamit
departmentACCOUNTS
salary56000
Record inserted successfully
EMPLOYEE RECORDS
[1];ADD NEW RECORD
[2];DISPLAY RECORDS
[3];EDIT EMPLOYEE SALARY
[4];DELETE A RECORD
[5];EXIT
Enter your choice 1
enter employee number2
employee Nameakash
departmentIT
salary80000
Record inserted successfully
EMPLOYEE RECORDS
[1];ADD NEW RECORD
[2];DISPLAY RECORDS
[3];EDIT EMPLOYEE SALARY
[4];DELETE A RECORD
[5];EXIT
Enter your choice 1
enter employee number3
employee Namemohit
departmentHR
salary60000
Record inserted successfully
EMPLOYEE RECORDS
[1];ADD NEW RECORD
[2];DISPLAY RECORDS
[3];EDIT EMPLOYEE SALARY
[4];DELETE A RECORD
[5];EXIT
Enter your choice 2
records inserted in table are
emp_no Name department salary
1 amit ACCOUNTS 56000
2 akash IT 80000
3 mohit HR 60000
EMPLOYEE RECORDS
[1];ADD NEW RECORD
[2];DISPLAY RECORDS
[3];EDIT EMPLOYEE SALARY
[4];DELETE A RECORD
[5];EXIT
Enter your choice 3
enter employee number whose salary is updated1
enter new salary70000
salary updated
EMPLOYEE RECORDS
[1];ADD NEW RECORD
[2];DISPLAY RECORDS
[3];EDIT EMPLOYEE SALARY
[4];DELETE A RECORD
[5];EXIT
Enter your choice 2
records inserted in table are
emp_no Name department salary
1 amit ACCOUNTS 70000
2 akash IT 80000
3 mohit HR 60000
EMPLOYEE RECORDS
[1];ADD NEW RECORD
[2];DISPLAY RECORDS
[3];EDIT EMPLOYEE SALARY
[4];DELETE A RECORD
[5];EXIT
Enter your choice 4
enter employee number whose record is to be deleted2
Record deleted
EMPLOYEE RECORDS
[1];ADD NEW RECORD
[2];DISPLAY RECORDS
[3];EDIT EMPLOYEE SALARY
[4];DELETE A RECORD
[5];EXIT
Enter your choice 2
records inserted in table are
emp_no Name department salary
1 amit ACCOUNTS 70000
3 mohit HR 60000
EMPLOYEE RECORDS
[1];ADD NEW RECORD
[2];DISPLAY RECORDS
[3];EDIT EMPLOYEE SALARY
[4];DELETE A RECORD
[5];EXIT
Enter your choice 5
thank you

You might also like