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.
def LShift (Arr, n):
L = len(Arr)
for x in range (0,n):
y = Arr[0]
for i in range(0,L-1):
Arr[1] = Arr[i+1]
Arr[L-1] = y
print(Arr)
Sample Input Data of the list Arr= [ 10,20,30,40,12,11], n=2
Output Arr = [30,40,12,11,10,20]
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.
def oct2others (n) :
print("Passed octal number : ", n)
numString = str(n)
decNum = int(numString, 8)
print("Number in Decimal: ", decNum)
print("Number in Binary:", bin(decNum))
print("Number in Hexadecimal : ", hex(decNum))
num = int(input ("Enter an octal number :"))
oct2others (num)
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 “[Link]”.
count = int(input("How many students are there in the class?"))
fileout = open ("[Link]", "w")
for i in range(count):
print("Enter details for student", (i+1), "below:")
rollno = int(input("Rollno:”))
name = input("Name :")
marks = float(input("Marks:"))
rec = str(rollno) + "," + name + "," + str(marks) +'\n'
[Link](rec)
[Link]()
OUTPUT:
4. WAP to add two or more students details to the file created in above program.
fileout = open("[Link]", "a")
for i in range(2):
print("Enter details for a student", (i+1), "below:")
rollno = int(input("Rollno:"))
name = input("Name :")
marks = float(input("Marks:"))
rec = str(rollno) + "," + name + "," + str(marks) +'\n'
[Link](rec)
[Link]()
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('[Link]', '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
[Link](stu,stufile)
ans = input("Want to enter more record y/n....?")
[Link]()
6. WAP to open the file created in above program and display the student records stored into
it.
import pickle
stu = {}
fin = open('[Link]', 'rb')
try:
print("File [Link] storesthese records")
while True:
stu = [Link](fin)
print(stu)
except EOFError:
[Link]()
OUPUT:
7. WAP to open file [Link] and search for the records with roll number as 12 or 14. If found,
display the record.
import pickle
stu={}
found= False
fin = open('[Link]', 'rb')
searchkeys=[12,14]
try:
print("searching in [Link]...")
while True:
stu=[Link](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.")
[Link]()
OUTPUT:
8. Read the [Link] created in earlier programs and display the records having marks>81.
import pickle
stu={}
found= False
with open('[Link]','rb') as fin:
stu = [Link](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 [Link] storing student details, which were created in earlier
programs. WAP to update the records of the file [Link] so that those who have scored
more than 81.0, get additional bonus marks of 2.
import pickle
stu = {}
found = False
fin = open('[Link]', 'rb+')
try:
while True:
rpos = [Link]()
stu = [Link](fin)
if stu[ 'Marks']> 81:
stu[ 'Marks'] += 2
[Link](rpos)
[Link](rpos)
[Link](stu, fin)
found = True
except EOFError:
if found == False:
print("Sorry, no matching record found.")
else:
print("Record(s) successfully updated.")
[Link]()
OUTPUT:
(b) Display the records of file [Link], which you modified in above program
import pickle
stu = {}
fin = open('[Link]', 'rb')
try:
print("File [Link] stores these records")
while True:
stu = [Link](fin)
print(stu)
except EOFError:
[Link]()
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("[Link]","w")
stuwriter = [Link](fh)
[Link](['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]
[Link](sturec)
[Link]()
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 ( [Link]) and write the above data into it.
import csv
fh = open("[Link]","w")
cwriter = [Link](fh)
compdata =[['Name', 'Points', 'Rank'],
['Shradha', 4500, 23],
['Nishchay', 4800, 31],
['Ali', 4500, 25],
['Adi', 5100, 14]]
[Link](compdata)
[Link]()
12. You created the file [Link] in the previous program. WAP to read the records of
this csv file and display them.
import csv
with open("[Link]", "r") as fh:
creader = [Link](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("[Link]", "r", newline = '\r\n') as fh:
creader = [Link](fh)
for rec in creader:
print(rec)
14. (a) WAP to create csv file by supressing the EOL translation.
import csv
fh = open("[Link]", "w", newline = '')
ewriter = [Link](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]]
[Link](empdata)
print("File successfully created")
[Link]()
(b) WAP to read and display the contents of [Link] created in the previous program.
import csv
with open("[Link]","r") as fh:
ereader = [Link](fh)
print("File [Link] contains :")
for rec in ereader:
print(rec)
15. Python program to implement stack operation
def isEmpty(stk):
if stk == []:
return True
else:
return False
def Push(stk, item):
[Link](item)
top= len(stk) - 1
def Pop(stk):
if isEmpty(stk):
return "Underflow"
else:
item = [Link]()
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("[Link]")
print("[Link]")
print("[Link]")
print("[Link] stack")
print("[Link]")
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.
Roll No – Integer Name – string
Class – Integer Marks – Integer
import [Link] as mysql
def sql_data():
con1= [Link](host = "localhost",
user= "root",
password = "tiger",
database="school")
mycursor = [Link]()
print("Students with marks greater than 75 are :")
[Link]("select * from student where marks >75")
data = [Link]()
for i in data:
print(i)
print()
17. Design a Python application that fetches all the records from Pet table of menagerie
database
import [Link] as a
mydb = [Link](host="localhost",
user="root",
password="dps123",
database = "menagerie")
cur = [Link]()
run = "select * from PET "
cur . execute(run)
data = [Link]()
for i in data :
print(i)
[Link]()
18. Design a Python application that fetches only those records from Event table of menagerie
database where type is Kennel.
import [Link] as a
mydb = [Link](host="localhost",
user="root",
password="dps123",
database = "menagerie")
cur = [Link]()
run = "select * from Event where type = 'Kennel' "
cur . execute(run)
data = [Link]()
for i in data :
print(i)
[Link]
19. Design a Python application to obtain a search criteria from user and then fetch records
based on that from empl table.
import [Link] as a
mydb = [Link](host="localhost",user="root",password="portal express", database =
"portal_express")
name = input("Enter the employee name :- ")
cur = [Link]()
run = "select * from Empl where name = '{}' ".format(name,)
cur . execute(run)
data = [Link]()
for i in data :
print(i)
[Link]()