You are on page 1of 24

1

# Program to get roll numbers , names and marks of the students of a class
from user and store these details in a file called “Marks.txt”

count=int(input("How many students are there in the class:"))


fileout=open("Marks.txt","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'
fileout.write(rec)
fileout.close()
Output:
How many students are there in the class:3
Enter details for student 1 below:
Rollno:1
Name:Arnav
Marks:92
Enter details for student 2 below:
Rollno:2
Name:Madhav
Marks:94
Enter details for student 3 below:
Rollno:3
Name:Shaurya
Marks:95
2
# Program to read a text file line by line and display each word separated by a
‘#’.
myfile=open("poem.txt","r")
line=" "
while line:
line=myfile.readline()
for word in line.split():
print(word,end="#")
print()
myfile.close()
Output:
WHY?#
we#work,#we#try#to#be#better#
we#work#with#full#zest#
But,#why#is#that#we#just#don't#know#any#letter#

we#still#give#our#best#
we#have#to#steal#
But#why#is#that#we#still#don't#get#a#meal#
we#don't#get#luxury#
we#don't#get#childhood#
But#we#still#work,#
Not#for#us,#but#for#all#the#others#
why#is#it#some#kids#wear#shoes,#BUT#we#make#them?#
by#Mythili,#class#5#
3
# Program to read a text file and display the number of vowels/ consonants/
uppercase/ lowercase characters in the file.
fin=open("poem.txt","r")
x=" "
vcount=ccount=lcount=upcount=0
while x:
x=fin.read(1)
if x in ["a","A","e","E","i","I","o","O","u","U"]:
vcount+=1
else:
ccount+=1
if x.isupper()==True:
upcount+=1
elif x.islower()==True:
lcount+=1
print("vowels in the file:",vcount)
print("consonants in the file:",ccount)
print("uppercase letters in the file:",upcount)
print("lowercase letters in the file:",lcount)
fin.close()
Output:
vowels in the file: 86
consonants in the file: 284
uppercase letters in the file: 11
lowercase letters in the file: 252
4
# Program to get student roll no., name and marks from user and write onto a
binary file.
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["Name"]=name
stu["Marks"]=marks
pickle.dump(stu,stufile)
ans=input("Want to enter more records?(y/n).....")
stufile.close()
Output:
Enter roll number:1
Enter name:Aanya
Enter marks:89
Want to enter more records?(y/n).....y
Enter roll number:2
Enter name:Mukul
Enter marks:95
Want to enter more records?(y/n).....y
Enter roll number:3
Enter name:Vidhi
Enter marks:82
Want to enter more records?(y/n).....n
5
# Program to append student record to a binary file by getting data from user.
import pickle
stu={}
stufile=open("Stu.dat","ab")
ans="y"
while ans=="y":
rno=int(input("Enter roll number:"))
name=input("Enter name:")
marks=float(input("Enter marks:"))
stu["Rollno"]=rno
stu["Name"]=name
stu["Marks"]=marks
pickle.dump(stu,stufile)
ans=input("Want to append more records?(y/n).....")
stufile.close()
Output:
Enter roll number:4
Enter name:Anjali
Enter marks:92
Want to append more records?(y/n).....y
Enter roll number:5
Enter name:Madhav
Enter marks:88
Want to append more records?(y/n).....y
Enter roll number:6
Enter name:Shaurya
Enter marks:94
Want to append more records?(y/n).....n
6
# Program to create a binary file with name and roll number. Search for a given
roll number and display the name, if not found display appropriate message.
import pickle
stu={ }
found=False
fileout=open("details.dat","wb")
t="y"
while t=="y":
print("Enter details of students:")
rollno=int(input("Enter roll number:"))
name=input("Enter name:")
r={"Rollno":rollno,"Name":name}
pickle.dump(r,fileout)
t=input("Do you want to enter more details?(y/n):")
fileout.close()
fileout=open("details.dat","rb")
searchkeys=int(input("Enter roll number to be searched:"))
try:
print("Searching in file details.dat.....")
while True:
stu=pickle.load(fileout)
if stu["Rollno"]==searchkeys:
print("The name of student with rollno",searchkeys,"is",stu["Name"])
found=True
except EOFError:
if found==False:
print("No such records found in file.")
else:
print("Search successfull.")
fileout.close()
Output:
Enter details of students:
Enter roll number:1
Enter name:Aanya
Do you want to enter more details?(y/n):y
Enter details of students:
Enter roll number:2
Enter name:Shaurya
Do you want to enter more details?(y/n):y
Enter details of students:
Enter roll number:3
Enter name:Tarun
Do you want to enter more details?(y/n):n
Enter roll number to be searched:2
Searching in file details.dat.....
The name of student with rollno 2 is Shaurya
Search successfull.

7
# Program to create a binary file Stu.dat storing student details and update the
records of the file so that those who have scored more than 81 marks, get
additional bonus of 2 marks

import pickle
stu={}
stufile=open("Stu.dat","wb")
ans="y"
while ans=="y":
rno=int(input("Enter rollno:"))
name=input("Enter name:")
marks=float(input("Enter marks:"))
stu["Rollno"]=rno
stu["Name"]=name
stu["Marks"]=marks
pickle.dump(stu,stufile)
ans=input("Want to enter more records?(y/n):")
stufile.close()
found=False
inf={}
fin=open("Stu.dat","rb+")
try:
while True:
rpos=fin.tell()
inf=pickle.load(fin)
if inf["Marks"]>81:
inf["Marks"]+=2
fin.seek(rpos)
pickle.dump(inf,fin)
found=True
except EOFError:
if found==False:
print("No such records found in file.")
else:
print("Updation successful.")
fin.close()
Output:
Enter rollno:1
Enter name:Aanya
Enter marks:90
Want to enter more records?(y/n):y
Enter rollno:2
Enter name:Madhav
Enter marks:87
Want to enter more records?(y/n):y
Enter rollno:3
Enter name:Shubhra
Enter marks:80
Want to enter more records?(y/n):n
Updation successful.

8
# Program to create a binary file with roll number, name and marks. Input a roll
number and update the marks.

import pickle
stu={}
found=False
fin=open("s.dat","rb+")
try:
while True:
rpos=fin.tell()
stu=pickle.load(fin)
if stu["Rollno"]==1:
stu["Marks"]=80
fin.seek(rpos)
pickle.dump(stu,fin)
found=True
except EOFError:
if found==False:
print("No such records found in the file.")
else:
print("Updation successful.")
fin.close()
Output:
Updation successful.

9
# Program to remove all the lines that contain the character `a' in a file and
write it to another file.

with open("poem.txt","r") as test_file1:


data=test_file1.readline()
print(data)
while data:
if data.find("a")==-1:
with open("p.txt","a") as test_file2:
test_file2.write(data+"\n")
data=test_file1.readline()
print(data)
Output:
WHY?
we work, we try to be better
we work with full zest

we still give our best


we don't get luxury
we don't get childhood
But we still work,

10
#

11
# Write a random number generator that generates random numbers

import random
def rolladice():
counter=0
mylist=[]
while (counter)<6:
randomNumber=random.randint(1,6)
mylist.append(randomNumber)
counter=counter+1
if (counter)>=6:
pass
else:
return mylist
n=1
while (n==1):
n=int(input("Enter 1 to roll a dice and get a random number:"))
print(rolladice())

Output:
Enter 1 to roll a dice and get a random number:1
[3]
Enter 1 to roll a dice and get a random number:2
[1]
12
# Program to implement a stack using a list data-structure.
s=[]
c="y"
while c=="y":
print("1.push")
print("2.pop")
print("3.display")
choice=int(input("Enter your choice:"))
if choice==1:
a=input("Enter any number:")
s.append(a)
elif choice==2:
if s==[]:
print("Queue Empty")
else:
print("Deleted element is:",s.pop())
elif choice==3:
l=len(s)
for i in range(0,l):
print(s[i])
else:
print("Wrong input")
c=input("Do you want to continue or not?")

Output:
1.push
2.pop
3.display
Enter your choice:1
Enter any number:1
Do you want to continue or not?y
1.push
2.pop
2.display
Enter your choice:1
Enter any number:2
Do you want to continue or not?y
1.push
2.pop
2.display
Enter your choice:1
Enter any number:3
Do you want to continue or not?y
1.push
2.pop
2.display
Enter your choice:2
Deleted element is: 3
Do you want to continue or not?y
1.push
2.pop
2.display
Enter your choice:3
1
2
Do you want to continue or not?n
13
# Program to create CSV file to store student rollno ,name, marks

import csv
fh=open("Student.csv","w")
stuwriter=csv.writer(fh)
stuwriter.writerow(["Rollno","Name","Marks"])
for i in range(5):
print("Student record:",(i+1))
rollno=int(input('Enter rollno:'))
name=input("Enter name:")
marks=float(input("Enter marks:"))
sturec=[rollno,name,marks]
stuwriter.writerow(sturec)
fh.close()

Output:
Student record: 1
Enter rollno:11
Enter name:Nishtha
Enter marks:79
Student record: 2
Enter rollno:12
Enter name:Rudy
Enter marks:89
Student record: 3
Enter rollno:13
Enter name:Rustom
Enter marks:75
Student record: 4
Enter rollno:14
Enter name:Gurjot
Enter marks:89
Student record: 5
Enter rollno:15
Enter name:Sadaf
Enter marks:85
14
# Program to read the records of CSV file and display

import csv
with open("Student.csv","r") as fh:
stureader=csv.reader(fh)
for i in stureader:
print(i)
fh.close()

Output:
['Rollno', 'Name', 'Marks']
[]
['11', 'Nishtha', '79.0']
[]
['12', 'Rudy', '89.0']
[]
['13', 'Rustom', '75.0']
[]
['14', 'Gurjot', '89.0']
[]
['15', 'Sadaf', '85.0']
[]
15
# Program to modify CSV file so that blank lines for EOL character are not
displayed
import csv
with open("Student.csv","r",newline="\r\n") as fh:
stureader=csv.reader(fh)
for i in stureader:
print(i)
fh.close()

Output:
['Rollno', 'Name', 'Marks']
['11', 'Nishtha', '79.0']
['12', 'Rudy', '89.0']
['13', 'Rustom', '75.0']
['14', 'Gurjot', '89.0']
['15', 'Sadaf', '85.0']
16
# Take a sample of any text file and find most commonly occurring word(s)

file=open("poem.txt","r")
content=file.read()
max=0
max_occ_word=" "
occ_dict={}
words=content.split()
for word in words:
count=content.count(word)
occ_dict.update({word:count})
if count>max:
max=count
max_occ_word=word
print("Most commonly occuring word:",max_occ_word)
print("Frequency",max)

Output:
Most commonly occuring word: WHY?
Frequency 1
Most commonly occuring word: we
Frequency 12
17
# Program to insert record into a MySQL database

import mysql.connector
mycon=mysql.connector.connect(host="localhost",user="root",passwd="1234",datab
ase="abc")
if mycon.is_connected():
print("Successfully connected to MySQL database")
cursor=mycon.cursor()
Ecode =(input("enter ecode: "))
Ename = (input("enter name: "))
Gender = (input("enter gender: "))
Grade = (input("enter grade: "))
Gross = (input("enter gross: "))
DOJ = (input("enter doj (yyyy-mm-dd): "))
cursor.execute("insert into employee values('" + Ecode + "','" + Ename + "','" +
Gender + "','" + Grade + "','" + Gross + "','" + DOJ+"')")
cursor.execute("commit")
print("Successfully inserted record into mySQL table")
mycon.close()

Output:
Successfully connected to MySQL database
enter ecode: 1007
enter name: Ramesh
enter gender: M
enter grade: A2
enter gross: 3450.0
enter doj (yyyy-mm-dd): 2019-04-23
Successfully inserted record into mySQL table
18
# Program to update record in a MySQL database
import mysql.connector
mycon=mysql.connector.connect(host="localhost",user="root",passwd="1234",datab
ase="abc")
if mycon.is_connected():
print("Successfully connected to MySQL database")
cursor=mycon.cursor()
Ecode = input("Enter ecode of record to be updated: ")
Ename = (input("enter ename: "))
Gender = (input("enter gender: "))
Grade = (input("enter grade: "))
Gross = (input("enter gross: "))
DOJ = (input("enter doj (yyyy-mm-dd): "))
cursor.execute("update employee set ename='"+ Ename +"', gender='"+ Gender
+"',gross='"+ Gross +"',grade='" + Grade +"',doj='" + DOJ +"' where ecode='"+
Ecode+"'")
cursor.execute("commit")
print("Successfully updated record")
mycon.close()

Output:
Successfully connected to MySQL database
Enter ecode of record to be updated: 1007
enter ename: Ramesh
enter gender: M
enter grade: B1
enter gross: 6789.0
enter doj (yyyy-mm-dd): 2019-04-23
Successfully updated record
19
# Program to delete a record from a MySQL database
import mysql.connector
mycon=mysql.connector.connect(host="localhost",user="root",passwd="1234",datab
ase="abc")
if mycon.is_connected():
print("Successfully connected to MySQL database")
cursor=mycon.cursor()
Ecode = input("Enter the ecode of the record to be deleted: ")
cursor.execute("delete from employee where ecode=" + Ecode)
cursor.execute("commit")
print("Successfully deleted record")
mycon.close()

Output:
Successfully connected to MySQL database
Enter the ecode of the record to be deleted: 1007
Successfully deleted record
20
# Program to display all records from a MySQL database
import mysql.connector
mycon=mysql.connector.connect(host="localhost",user="root",passwd="1234",datab
ase="abc")
if mycon.is_connected():
print("Successfully connected to MySQL database")
cursor=mycon.cursor()
cursor.execute("select * from employee")
data=cursor.fetchall()
count=cursor.rowcount
for row in data:
print(row)
mycon.close()

Output:
Successfully connected to MySQL database
(1001, 'Ravi', 'M', 'E4', Decimal('4670'), datetime.date(2020, 3, 12))
(1002, 'Ram', 'M', None, Decimal('5670'), datetime.date(2020, 4, 13))
(1003, 'Radha', 'F', 'E1', Decimal('5000'), datetime.date(2019, 3, 12))
(1004, 'Seema', 'F', 'E1', Decimal('6790'), datetime.date(2019, 1, 23))
(1005, 'Hemant', 'M', 'E2', Decimal('8000'), datetime.date(2018, 4, 10))
(1006, 'Rohan', 'M', 'E5', Decimal('4560'), datetime.date(2016, 5, 12))

You might also like