Questions
Q1) Write a python program to input 3 numbers and display the largest , smallest number.
[ ]: def q1():
a = int(input("1st number: ")) # 12
b = int(input("2nt number: ")) # 59
c = int(input("3rd number: ")) # 4
print(max(a,b,c),min(a,b,c))
q1()
59 4
Q2) Write a python program to input a number and check if the number is prime or not.
[ ]: def q2():
class InvalidInput(Exception):
pass
n = int(input("Enter:"))
flag = True
try:
i=2
while i*i <= n:
if n % i == 0:
flag = False
i += 1
if n < 2:
raise InvalidInput
elif flag:
print(n, "is prime")
else:
print(n, "is composite")
except InvalidInput:
if (n == 1 or n == 0):
print("Neither prime nor composite")
else:
print("-ve no. not allowed")
q2()
1000000007 is prime
Q3) Write a python program to read a text file and display each word separated by ‘#’.
[ ]: def q3():
f = open("file.txt", 'r')
l = f.readlines()
for i in l:
w = i.split()
for j in w:
print(j,"#",end =" ")
print(" ")
f.close()
q3()
froddo # is # a # donkey # donkey # monaky #
Q4) Write a python program to read a file and display the nuber of vowels, consonants, uppercase,
lowercase.
[ ]: def q4():
f = open("file.txt", 'r')
l = f.read()
vowel = ['a','e','i','o','u','A','E','I','O','U']
totalVowels = 0
totalSpaces = 0
totalUpper = 0
totalLower = 0
for i in l:
if i in vowel:
totalVowels += 1
elif i.isspace():
totalSpaces += 1
if i.isupper():
totalUpper += 1
elif i.islower():
totalLower += 1
totalCharCount = len(l)
print("Vowels:", totalVowels,
"Consonants:", totalCharCount-totalVowels-totalSpaces,
"Uppercase:", totalUpper,
"Lowercase:", totalLower,
f.close()
q4()
Vowels: 10 Consonants: 17 Uppercase: 0 Lowercase: 27
Q5) write a python program to remove the character ‘a’ in a line and write it to another file.
[ ]: def q5():
f = open("file.txt", 'r')
l = f.read()
nl = l.replace('a', ' ')
fx = open('new.txt', 'w')
fx.write(nl)
print(nl)
f.close()
fx.close()
q5()
froddo is donkey donkey mon ky
Q6) Write a python program to create a binary file with employee no., salary and employ ID and
display the data on the screen.
[ ]: def q7():
import pickle
def write():
f = open("emp.dat", 'ab')
dataDumpTof = list()
empName = str(input("Name: "))
empId = int(input("ID: "))
empSalary = int(input("Salary in rs: "))
dataDumpTof.append({"Name": empName, "ID": empId, "Salary": empSalary})
pickle.dump(dataDumpTof, f)
f.close()
def read():
f = open("emp.dat", 'rb')
l = pickle.load(f)
print(l)
for i in l:
print('\t',"Name: ", i['Name'],'\n'
'\t',"ID: ", i['ID'],'\n'
'\t',"Salary: ", i['Salary']
f.close()
write()
read()
q7()
[{'Name': 'Rohit', 'ID': 38, 'Salary': 100000000000000}]
Name: Rohit
ID: 38
Salary: 100000000000000
Q7) TAke a sample text file and find the most commonly occuring word and frequency of all words.
[ ]: from collections import Counter
inputFile = "file.txt"
nW = []
f = open('file.txt', 'r')
for i in f:
w = i.split()
for j in w:
nW.append(j)
wF = Counter(nW) # word frequency -> Counter({"word": frequency})
mF = 0 # max frequency
for k in wF:
if(wF[k] > mF):
mF = wF[k]
m=k
print("{",m,"} is the most repeated word in the text file",'\n'
'\t',"Frequency of all words", wF)
f.close()
{ donkey } is the most repeated word in the text file
Frequency of all words Counter({'donkey': 2, 'froddo': 1, 'is': 1, 'a':
1, 'monaky': 1})
Q8) Create a binary file with roll no. , name and marks. Input a roll no. to change marks.
[ ]: def q8():
import pickle
f = open("student.dat","ab+")
dataDumptoF = {}
def entry():
dataDumptoF["Name"] = str(input("Enter Student name: "))
dataDumptoF["RollNo"] = int(input("Enter roll no: "))
dataDumptoF["Marks"] = float(input("Enter Student Marks: "))
pickle.dump(dataDumptoF, f)
def searchChange():
j = f.tell()
f.seek(0)
l = pickle.load(f)
print(l)
rollNo = int(input("enter the roll no to search: "))
if (l["RollNo"] == rollNo):
l["Marks"] = float(input("Enter marks to be updated: "))
f.seek(j)
pickle.dump(l,f)
print("Student marks updated successfully")
print(l)
else:
print("Roll no. doesn't exist")
entry()
searchChange()
f.close()
q8()
{'Name': 'Rohit', 'RollNo': 38, 'Marks': 98.0}
Student marks updated successfully
{'Name': 'Rohit', 'RollNo': 38, 'Marks': 100.0}
Q9) Write a python program for a random number genrator that generates a random number
between 1-6.
[ ]: import random
for i in range(0,6):
print(random.randint(1,6))
Q10) Create a binary file with name and roll no. and for a given roll no. display the name if not
found display appropriate message.
[ ]: def q9():
import pickle
f = open("number.dat","ab+")
dataDumptoF = {}
def entry():
dataDumptoF["Name"] = str(input("Enter Student name: "))
dataDumptoF["RollNo"] = int(input("Enter roll no: "))
pickle.dump(dataDumptoF, f)
def search():
f.seek(0)
l = pickle.load(f)
print(l)
rollNo = int(input("enter the roll no to search: "))
if (l["RollNo"] == rollNo):
print(l["Name"])
else:
print("Roll no. doesn't exist")
entry()
search()
f.close()
q9()
{'Name': 'Rohit', 'RollNo': 38}
Rohit
Q11) Create a csv file with employ ID, name and mobile no. update the record by searching with
employ ID and display the record.
[ ]: def q11():
import csv
def searchEmpByID(empList, targetID):
for index, emp in enumerate(empList):
if int(emp[1]) == targetID:
return index
return -1
def editEmpRecord(empList, index):
name = input("Enter new name: ")
id = int(input("Enter new ID: "))
mNum = int(input("Enter new mobile no.: "))
empList[index] = [name, id, mNum]
def printEmpRecords(empList):
for i, emp in enumerate(empList, start=1):
print("Record", i,'\n'
'\tName:', emp[0],'\n'
'\tID:', emp[1],'\n'
'\tMobile no.:', emp[2]
# Main program
with open('emp.csv', 'a') as f:
l = csv.writer(f)
numE = int(input("Number of emp: "))
rowsList = []
for _ in range(numE):
name = input("Name: ")
id = int(input("ID: "))
mNum = int(input("Mobile no.: "))
rowsList.append([name, id, mNum])
con = input("Continue? (yY/nN): ")or 'Y'
if con.lower() == 'n':
break
l.writerows(rowsList)
with open('emp.csv', 'r') as fr:
r = csv.reader(fr)
empData = list(r)
printEmpRecords(empData)
sID = int(input("Enter the ID to edit the record: "))
indexToEdit = searchEmpByID(empData, sID)
if indexToEdit != -1:
print("Editing record for ID", sID)
editEmpRecord(empData, indexToEdit)
print("Updated records:")
printEmpRecords(empData)
else:
print("Employee with ID", {sID}, "not found.")
q11()
Record 1
Name: Rohit
ID: 38
Mobile no.: 99
Record 2
Name: Sohit
ID: 12
Mobile no.: 0
Record 3
Name: Roh
ID: 1
Mobile no.: 11
Editing record for ID 1
Updated records:
Record 1
Name: Rohit
ID: 38
Mobile no.: 99
Record 2
Name: Sohit
ID: 12
Mobile no.: 0
Record 3
Name: Mohit
ID: 11
Mobile no.: 11
Q12) Create a csv file by entering user id and password search and display the password for a given
used id.
[ ]: def q12():
import csv
def searchUserByID(userList, targetID):
for index, user in enumerate(userList):
if int(user[0]) == targetID:
return index
return -1
def printUserRecords(userList):
for i, user in enumerate(userList, start=1):
print("Record", i,'\n'
'\tUser ID:', user[0],'\n'
'\tPassword:', user[1],'\n'
# Main program
with open('users.csv', 'a') as f:
l = csv.writer(f)
numUsers = int(input("Number of users: "))
userRecords = []
for _ in range(numUsers):
userID = int(input("User ID: "))
password = input("Password: ")
userRecords.append([userID, password])
l.writerows(userRecords)
with open('users.csv', 'r') as fr:
r = csv.reader(fr)
userData = list(r)
printUserRecords(userData)
sID = int(input("Enter the User ID to search for: "))
indexToEdit = searchUserByID(userData, sID)
if indexToEdit != -1:
print("User with User ID", sID, "found.",'\n'
"User ID:", userData[indexToEdit][0],'\n'
"Password:", userData[indexToEdit][1]
else:
print("User with User ID", sID, "not found.")
q12()
Record 1
User ID: 38
Password: lulzsec
Record 2
User ID: 2
Password: popl
User with User ID 38 found.
User ID: 38
Password: lulzsec
User with User ID 38 found.
User ID: 38
Password: lulzsec
Q13) Write a python program to create and search student record in csv file.
[ ]: def q12():
import csv
def searchStByID(stList, targetRN):
for index, st in enumerate(stList):
if int(st[2]) == targetRN:
return index
return -1
def printStRecords(stList):
for i, st in enumerate(stList, start=1):
print("Record ", i)
print('\tName: ', st[0],'\n'
10
'\tClass: ', st[1],'\n'
'\tRoll Number:', st[2]
# Main program
with open('students.csv', 'a') as f:
l = csv.writer(f)
numSt = int(input("Number of Students: "))
stRecords = []
for _ in range(numSt):
name = (input("Name: "))
cl = int(input("Class: "))
rollNo = int(input("Roll No.: "))
stRecords.append([name, cl, rollNo])
l.writerows(stRecords)
with open('students.csv', 'r') as fr:
r = csv.reader(fr)
stData = list(r)
printStRecords(stData)
rollNo = int(input("Enter the Roll Number to search for: "))
indexToEdit = searchStByID(stData, rollNo)
if indexToEdit != -1:
print("Student with Roll Number ", rollNo, "found.")
print("Name: ", stData[indexToEdit][0],'\n'
"Class: ", stData[indexToEdit][1],'\n'
"Roll Number: ", stData[indexToEdit][2]
)
else:
print("Student with Roll Number ", {rollNo}, "not found.")
q12()
Record 1
Name: Rohit
Class: 12
Roll Number: 38
Record 2
Name: kohit
Class: 12
Roll Number: 0
Student with Roll Number 38 found.
Name: Rohit
11
Class: 12
Roll Number: 38
Student with Roll Number 38 found.
Name: Rohit
Class: 12
Roll Number: 38
Q14) Write a python program to implement a stack using push and pop operation on stack.
[ ]: def q14():
stack = list()
def isEmpty(stack):
if len(stack) == 0:
return True
else:
return False
def push(stack, e):
stack.append(e)
def pop(stack):
if isEmpty(stack):
print("Empty Stack")
return None
else:
stack.pop()
def display(stack):
l = len(stack)
for i in range(l-1, -1, -1):
print(stack[i])
push(stack, "Rohit")
display(stack)
q14()
Rohit
Q15) Write a python program using function push(arr) where arr is a list of numbers. From this
list push all the numbers that are divisible by 5 into a stack implemted using a list. Dsiplay the
stack if it has atleast one element otherwise display appropriate message.
[ ]: stack = list()
def isEmpty(stack):
if len(stack) == 0:
return True
else:
12
return False
def push(stack, e):
stack.append(e)
def pop(stack):
if isEmpty(stack):
print("Empty Stack")
return None
else:
stack.pop()
def display(stack):
l = len(stack)
print("Stack:")
for i in range(l-1, -1, -1):
print('\t',stack[i])
arr = input("Enter list of number separated by space: ")
arrList = arr.split()
for i in range(len(arrList)):
arrList[i] = int(arrList[i])
print("Input list:", arrList)
for i in arrList:
if i % 5 == 0:
push(stack, i)
display(stack)
Input list: [2, 4, 15, 10, 16, 20, 5, 17]
Stack:
20
10
15
13