Write A Program To Show Whether Entered Numbers Are Prime or Not in The Given Range
Write A Program To Show Whether Entered Numbers Are Prime or Not in The Given Range
string=input('Enter a string:')
length=len(string)
mid=length//2
rev=-1
for a in range(mid):
if string[a]==string[rev]:
print(string,'is a palindrome.')
break
else:
print(string,'is not a palindrome.')
3. Find the largest/smallest number in a list/tuple
# creating empty list
list1 = []
print("Fibonacci sequence:")
for i in range(nterms):
print(fibonacci(i),end=' ')
print(end = "\t")
9. Read a text file line by line and display each word
separated by a #
filein = open("Mydoc.txt",'r')
line =" "
while line:
line = filein.readline()
#print(line)
for w in line:
if w == ' ':
print('#',end = '')
else:
print(w,end = '')
filein.close()
'''
#-------------OR------------------
filein = open("Mydoc.txt",'r')
for line in filein:
word= line .split()
for w in word:
print(w + '#',end ='')
print()
filein.close()
'''
10. Read a text file and display the number of vowels/
consonants/ uppercase/ lowercase characters in the file.
file=open("sample.txt","r")
myfile=file.read() print(myfile)
vowels=0
consonants=0
upper=0 lower=0
for i in myfile:
if str.isupper(i):
upper+=1
if str.islower(i):
lower+=1
i=str.lower(i) if i in
"aeiou":
vowels+=1
if i in "bcdfghjklmnpqrstvwxyz":
consonants+=1
print("No. of vowels:",vowels) print("No. of
consonants:",consonants) print("No. of
uppercase letters:",upper) print("No. os
lowercase letters:",lower)
11. Write a Python code to find the size of the file in bytes,
the number of lines, number of words and no. of character.
file=open("sample.txt","r") str
=file.read() size=len(str)
file=open("sample.txt","r")
words=0
character=0
lines=0
for line in file:
wordlist=line.split() lines =
lines + 1
words=words+len(wordlist)
character=character+len(line)
print("The size of the file is:",size,"bytes") print("No. of lines in
the file are:",lines) print("The total no. of words are:",words)
print("The total no. of characters are:",character)
12. Write a program that accepts a filename of a text file
and reports the file's longest line.
def Readrecord():
with open ('StudentRecord1.dat','rb') as Myfile:
print("\n-------DISPALY STUDENTS DETAILS--------")
print("\nRoll No.",' ','Name','\t',end='')
print()
while True:
try:
rec=pickle.load(Myfile)
print(' ',rec['SROLL'],'\t ' ,rec['SNAME'])
except EOFError:
break
def Input():
n=int(input("How many records you want to create :"))
for ctr in range(n):
sroll=int(input("Enter Roll No: "))
sname=input("Enter Name: ")
Writerecord(sroll,sname)
def SearchRecord(roll):
with open ('StudentRecord1.dat','rb') as Myfile:
while True:
try:
rec=pickle.load(Myfile)
if rec['SROLL']==roll:
print("Roll NO:",rec['SROLL'])
print("Name:",rec['SNAME'])
except EOFError:
print("Record not find..............")
print("Try Again..............")
break
def main():
while True:
print('\nYour Choices are: ')
print('1.Insert Records')
print('2.Dispaly Records')
print('3.Search Records (By Roll No)')
print('0.Exit (Enter 0 to exit)')
ch=int(input('Enter Your Choice: '))
if ch==1:
Input()
elif ch==2:
Readrecord()
elif ch==3:
r=int(input("Enter a Rollno to be Search: "))
SearchRecord(r)
else:
break
main()
14. Create a binary file with roll number, name and marks.
Input a roll number and update the marks.
def Writerecord(sroll,sname,sperc,sremark):
with open ('StudentRecord.dat','ab') as Myfile:
srecord={"SROLL":sroll,"SNAME":sname,"SPERC":sper
c,
"SREMARKS":sremark}
pickle.dump(srecord,Myfile)
def Readrecord():
with open ('StudentRecord.dat','rb') as Myfile:
print("\n-------DISPALY STUDENTS DETAILS--------
")
print("\nRoll No.",' ','Name','\t',end='')
print('Percetage',' ','Remarks')
while True:
try:
rec=pickle.load(Myfile)
print(' ',rec['SROLL'],'\t '
,rec['SNAME'],'\t ',end='')
print(rec['SPERC'],'\t ',rec['SREMARKS']
)
except EOFError:
break
def Input():
n=int(input("How many records you want to create :"))
for ctr in range(n):
sroll=int(input("Enter Roll No: "))
sname=input("Enter Name: ")
sperc=float(input("Enter Percentage: "))
sremark=input("Enter Remark: ")
Writerecord(sroll,sname,sperc,sremark)
def Modify(roll):
with open ('StudentRecord.dat','rb') as Myfile:
newRecord=[]
while True:
try:
rec=pickle.load(Myfile)
newRecord.append(rec)
except EOFError:
break
found=1
for i in range(len(newRecord)):
if newRecord[i]['SROLL']==roll:
name=input("Enter Name: ")
perc=float(input("Enter Percentage: "))
remark=input("Enter Remark: ")
newRecord[i]['SNAME']=name
newRecord[i]['SPERC']=perc
newRecord[i]['SREMARKS']=remark
found =1
else:
found=0
if found==0:
print("Record not found")
with open ('StudentRecord.dat','wb') as Myfile:
for j in newRecord:
pickle.dump(j,Myfile)
def main():
while True:
print('\nYour Choices are: ')
print('1.Insert Records')
print('2.Dispaly Records')
print('3.Update Records')
print('0.Exit (Enter 0 to exit)')
ch=int(input('Enter Your Choice: '))
if ch==1:
Input()
elif ch==2:
Readrecord()
elif ch==3:
r =int(input("Enter a Rollno to be update:
"))
Modify(r)
else:
break
main()
15. Remove all the lines that contain the character `a' in a
file and write it to another file.
f1 = open("Mydoc.txt")
f2 = open("copyMydoc.txt","w")
for line in f1:
if 'a' not in line:
f2.write(line)
print('## File Copied Successfully! ##')
f1.close()
f2.close()
f2 = open("copyMydoc.txt","r")
print(f2.read())
16. Write a program to perform read and write
operation onto a student.csv file having fields as
roll number, name, stream and percentage.
import csv
with open('Student_Details.csv','w',newline='')
as csvf:
writecsv=csv.writer(csvf,delimiter=',')
choice='y'
while choice.lower()=='y':
rl=int(input("Enter Roll No.: "))
n=input("Enter Name: ")
p=float(input("Enter Percentage: "))
r=input("Enter Remarks: ")
writecsv.writerow([rl,n,p,r])
print(" Data saved in Student Details
file..")
choice=input("Want add more
record(y/n).....")
with open('Student_Details.csv','r',newline='')
as fileobject:
readcsv=csv.reader(fileobject)
for i in readcsv:
print(i)
17. Program to search the record of a particular
student from CSV file on the basis of inputted name
import csv
#input Roll number you want to search
number = input('Enter number to find: ')
found=0
#read csv, and split on "," the line
with open('Student_Details.csv') as f:
csv_file = csv.reader(f, delimiter=",")
#loop through csv list
for row in csv_file:
#if current rows index value (here 0) is
equal to input, print that row
if number ==row[0]:
print (row)
found=1
else:
found=0
if found==1:
pass
else:
print("Record Not found")
OUTPUT:
20. Write A Python Program To Implement 2 User Defined Functions One Is To
Create Binary File And Another Is To Read Binary File (Make Use Of Pickle
Module).
INPUT:
OUTPUT:
This common words used in phishing are kind of alarming messages and
privacy protection threat notification. These can also be in the form of amusing
lotteries and sale offers. Also they can be in the form of a fake login and ask for
your credential for updates or something else. We should aware of these
phishing emails and don’t share our credentials.