python programs
python programs
1. Write a function LShift(Arr,n) in Python, which accepts a list Arr of numbers and n is a
numeric value by which all elements of the list are shifted to left.
2. Write a function that receives an octal number and prints the equivalent number in other
number bases i.e., in decimal, binary and hexadecimal equivalents.
Output :-
Enter an octal number :12345
Passed octal number : 12345
Number in Decimal: 5349
Number in Binary: 0b1010011100101
Number in Hexadecimal : 0x14e5
3. Write a program to get roll numbers, names and marks of the students of a class (get from
user) and store these details in a file called “Marks.txt”.
OUTPUT:
4. WAP to add two or more students details to the file created in above program.
OUTPUT:
5. WAP to get student data(roll no, name, and marks) from user and write onto a binary file.
The program should be able to get data from the user and write onto the file as long as the
user wants.
import pickle
stu = {}
stufile = open('Stu.dat', 'wb')
ans = 'y'
while ans == 'y':
rno = int(input("Enter roll number:"))
name = input("Enter name:")
marks = float(input("Enter marks:"))
stu['Rollno'] = rno
stu['Marks'] = marks
stu['Name'] = name
pickle.dump(stu,stufile)
ans = input("Want to enter more record y/n....?")
stufile.close()
6. WAP to open the file created in above program and display the student records stored into
it.
import pickle
stu = {}
fin = open('Stu.dat', 'rb')
try:
print("File Stu.dat storesthese records")
while True:
stu = pickle.load(fin)
print(stu)
except EOFError:
fin.close()
OUPUT:
7. WAP to open file Stu.dat and search for the records with roll number as 12 or 14. If found,
display the record.
import pickle
stu={}
found= False
fin = open('stu.dat', 'rb')
searchkeys=[12,14]
try:
print("searching in student.dat...")
while True:
stu=pickle.load(fin)
if stu['Rollno'] in searchkeys:
print(stu)
found=True
except EOFError:
if found== False:
print("no such record found in the file")
else:
print("search successful.")
fin.close()
OUTPUT:
8. Read the stu.dat created in earlier programs and display the records having marks>81.
import pickle
stu={}
found= False
with open('Stu.dat','rb') as fin:
stu = pickle.load(fin)
if stu['Marks']>81:
print(stu)
found = True
if found == False:
print("No such records found")
else:
print("Search Successful")
OUTPUT:
9. (a) Consider the binary file stu.dat storing student details, which were created in earlier
programs. WAP to update the records of the file stu.dat so that those who have scored
more than 81.0, get additional bonus marks of 2.
import pickle
stu = {}
found = False
fin = open('Stu.dat', 'rb+')
try:
while True:
rpos = fin.tell()
stu = pickle.load(fin)
if stu[ 'Marks']> 81:
stu[ 'Marks'] += 2
fin.seek(rpos)
fin.seek(rpos)
pickle.dump(stu, fin)
found = True
except EOFError:
if found == False:
print("Sorry, no matching record found.")
else:
print("Record(s) successfully updated.")
fin.close()
OUTPUT:
(b) Display the records of file stu.dat, which you modified in above program
import pickle
stu = {}
fin = open('Stu.dat', 'rb')
try:
print("File Stu.dat stores these records")
while True:
stu = pickle.load(fin)
print(stu)
except EOFError:
fin.close()
OUPUT:
10. WAP to create a CSV file to store student data(Roll no, Name , Marks). Obtain data from
user and user and write 5 records into the file.
import csv
fh = open("student.csv","w")
stuwriter = csv.writer(fh)
stuwriter.writerow(['Rollno','Name','Marks'])
for i in range(5):
print("Studen Record", (i+1))
rollno = int(input("Enter rollno:"))
name = input("Enter name:")
marks = float(input("Enter marks:"))
sturec = [rollno, name, marks]
stuwriter.writerows(sturec)
fh.close()
11. The data of winners of 4 rounds of a competitive programming competition is given as:
[‘Name’, ‘Points’, ‘Rank’]
[‘Shradha’, 4500, 23]
[‘Nishchay’, 4800, 31]
[‘Ali’, 4500, 25]
[‘Adi’, 5100, 14]
WAP to create a csv file ( compresult.csv) and write the above data into it.
import csv
fh = open("compresult.csv","w")
cwriter = csv.writer(fh)
compdata =[['Name', 'Points', 'Rank'],
['Shradha', 4500, 23],
['Nishchay', 4800, 31],
['Ali', 4500, 25],
['Adi', 5100, 14]]
cwriter.writerows(compdata)
fh.close()
12. You created the file compresult.csv in the previous program. WAP to read the records of
this csv file and display them.
import csv
with open("compresult.csv", "r") as fh:
creader = csv.reader(fh)
for rec in creader:
print(rec)
13. Modify the code of the previous program so that blank lines for every EOL are not
displayed.
import csv
with open("compresult.csv", "r", newline = '\r\n') as fh:
creader = csv.reader(fh)
for rec in creader:
print(rec)
14. (a) WAP to create csv file by supressing the EOL translation.
import csv
fh = open("Employee.csv", "w", newline = '')
ewriter = csv.writer(fh)
empdata = [
['Empno', 'Name', 'Designation', 'Salary'],
[1001, 'Trupti', 'Manager', 56000],
[1002, 'Raziya', 'Manager', 55900],
[1003, 'Simran', 'Analyst', 35000],
[1004, 'Silviya', 'Clerk', 25000],
[1005, 'Suji', 'PROfficer', 31000]]
ewriter.writerows(empdata)
print("File successfully created")
fh.close()
(b) WAP to read and display the contents of Employee.csv created in the previous program.
import csv
with open("Employee.csv","r") as fh:
ereader = csv.reader(fh)
print("File Employee.csv contains :")
for rec in ereader:
print(rec)
def isEmpty(stk):
if stk == []:
return True
else:
return False
def Push(stk, item):
stk.append(item)
top= len(stk) - 1
def Pop(stk):
if isEmpty(stk):
return "Underflow"
else:
item = stk.pop()
if len (stk) == 0:
top = None
else:
top = len(stk) - 1
return item
def Peek(stk):
if isEmpty(stk):
return "Underflow"
else:
top = len(stk) - 1
return stk[top]
def Display(stk):
if isEmpty(stk):
print("Stack empty")
else:
top = len(stk) - 1
print(stk[top], "<-top")
for a in range(top-1, -1, -1):
print(stk[a])
#_main_
Stack = []
top = None
while True:
print("Stack Operations")
print("1.Push")
print("2.Pop")
print("3.Peek")
print("4.display stack")
print("5.exit")
ch = int(input("Enter your choice (1-5):")) OUTPUT:
if ch == 1:
item = int(input("Enter item:"))
Push(Stack,item)
elif ch == 2:
item = Pop(Stack)
if item == "Underflow":
print("stack is empty")
else:
print("popped item is", item)
elif ch == 3:
item = Peek(Stack)
if item == "Underflow":
print("Stack is empty")
else:
print("topmost item is", item)
elif ch == 4:
Display(Stack)
elif ch == 5:
break
else:
print("Invalid choice!")
16. The code given below reads the following record from the table named student and
displays only those who have marks greater than >75.
17. Design a Python application that fetches all the records from Pet table of menagerie
database
import mysql.connector as a
mydb = a.connect(host="localhost",
user="root",
password="dps123",
database = "menagerie")
cur = mydb.cursor()
run = "select * from PET "
cur . execute(run)
data = cur.fetchall()
for i in data :
print(i)
mydb.close()
18. Design a Python application that fetches only those records from Event table of menagerie
database where type is Kennel.
import mysql.connector as a
mydb = a.connect(host="localhost",
user="root",
password="dps123",
database = "menagerie")
cur = mydb.cursor()
run = "select * from Event where type = 'Kennel' "
cur . execute(run)
data = cur.fetchall()
for i in data :
print(i)
mydb.close
19. Design a Python application to obtain a search criteria from user and then fetch records
based on that from empl table.
import mysql.connector as a
mydb = a.connect(host="localhost",user="root",password="portal express", database =
"portal_express")
mydb.close()