CBSE COMPUTER SCIENCE
Ir al canal en Telegram
QUESTION BANK, REFERENCE BOOK, LAB MANUAL , WORKSHEET ETC., PYTHON TEXT BOOK AND REFERENCE BOOKS, 01. ASK QUESTIONS AT https://t.me/joinchat/FJ1noGs-64I0OWI1
Mostrar más549
Suscriptores
Sin datos24 horas
Sin datos7 días
Sin datos30 días
Archivo de publicaciones
https://www.qb365.in/materials/stateboard/12th-computer-science-python-and-csv-files-book-back-questions-3927.html
Online Test : https://www.qb365.in/materials/online-test/148380/python-and-csv-files-practice-test-1.html
https://www.tutorialaicsip.com/cs-xii-qna/file-handling-in-python-class-12/
https://www.techbeamers.com/python-file-handling-quiz-part-2-experienced/
https://www.cbsetuts.com/important-questions-class-12-computer-science-python/
https://www.w3resource.com/python-exercises/file/
#DELETING THE RECORDS
import mysql.connector as mcr
cn = mcr.connect(host='127.0.0.1',user='root',password="admin",database="company")
cr = cn.cursor()
print("#"*40)
print(" EMPLOYEE DELETION FORM")
print("#"*40)
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO DELETE :"))
query="select * from employee where empno={}".format(eno)
cr.execute(query)
result = cr.fetchall()
if cr.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO","%20s"%"NAME", "%15s"%"DEPARTMENT","%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
choice=input("\n## ARE YOUR SURE TO DELETE ? (Y) :")
if choice.lower()=='y':
query="delete from employee where empno={}".format(eno)
cr.execute(query)
cn.commit()
print("=== RECORD DELETED SUCCESSFULLY! ===")
ans=input("DELETE MORE ? (Y) :")
#UPDATING THE RECORDS
import mysql.connector as mcr
cn = mcr.connect(host='127.0.0.1',user='root',password="admin",database="company")
cr = cn.cursor()
print("#"*40)
print(" EMPLOYEE UPDATION FORM")
print("#"*40)
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO UPDATE :"))
query="select * from employee where empno={}".format(eno)
cr.execute(query)
result = cr.fetchall()
if cr.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO","%20s"%"NAME", "%15s"%"DEPARTMENT","%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
choice=input("\n## ARE YOUR SURE TO UPDATE ? (Y) :")
if choice.lower()=='y':
print("== YOU CAN UPDATE ONLY DEPT AND SALARY ==")
print("== FOR EMPNO AND NAME CONTACT ADMIN ==")
d=input("ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT WANT TO CHANGE )")
if d=="":
d=row[2]
try:
s = int(input("ENTER NEW SALARY,(LEAVE BLANK IF NOT WANT TO CHANGE ) "))
except:
s=row[3]
query="update employee set dept='{}',salary={} where empno={}".format(d,s,eno)
cr.execute(query)
cn.commit()
print("## RECORD UPDATED ## ")
ans=input("UPDATE MORE (Y) :")
#SEARCHING AND DISPLAYING THE RECORDS
import mysql.connector as mcr
cn = mcr.connect(host='127.0.0.1',user='root',password="admin",database="company")
cr = cn.cursor()
print("#"*40)
print(" EMPLOYEE SEARCHING FORM")
print("#"*40)
ans='Y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO SEARCH :"))
query="select * from employee where empno={}".format(eno)
cr.execute(query)
result = cr.fetchall()
if cr.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO", "%20s"%"NAME","%15s"%"DEPARTMENT","%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
ans=input("SEARCH MORE (Y/N) :")
#STORING AND RETRIEVING THE RECORDS
import mysql.connector as mcr
cn = mcr.connect(host='127.0.0.1',user='root',password="admin")
cr = cn.cursor()
cr.execute("create database if not exists company")
cr.execute("use company")
cr.execute("create table if not exists employee(empno int, name varchar(20), dept varchar(20),salary int)")
cn.commit()
choice=None
while choice!=0:
print("1. ADD RECORD ")
print("2. DISPLAY RECORD ")
print("0. EXIT")
choice = int(input("Enter Choice :"))
if choice == 1:
e = int(input("Enter Employee Number :"))
n = input("Enter Name :")
d = input("Enter Department :")
s = int(input("Enter Salary :"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
cr.execute(query)
cn.commit()
print("## Data Saved ##")
elif choice == 2:
query="select * from employee"
cr.execute(query)
result = cr.fetchall()
print("%10s"%"EMPNO","%20s"%"NAME","%15s"%"DEPARTMENT","%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
elif choice==0:
cn.close()
print("## Bye!! ##")
else:
print("## INVALID CHOICE ##")
#To take 10 sample phishing mail and
#count the most commonly occurring word
phishingemail=[
"jackpotwin@lottery.com",
"claimtheprize@mymoney.com",
"youarethewinner@lottery.com",
"luckywinner@mymoney.com",
"spinthewheel@flipkart.com",
"dealwinner@snapdeal.com"
"luckywinner@snapdeal.com"
"luckyjackpot@americanlottery.com"
"claimtheprize@lootolottery.com"
"youarelucky@mymoney.com"
]
myd={}
for e in phishingemail:
x=e.split('@')
for w in x:
if w not in myd:
myd[w]=1
else:
myd[w]+=1
key_max = max(myd,key=myd.get)
print("Most Common Occuring word is :",key_max)
def isEmpty(Que): # checks whether the Queue is empty or not
if Que==[]:
return True
else:
return False
def Enqueue(Que,item): # Allow additions to the queue
Que.append(item)
top=len(Que)-1
def Dequeue(Que):
if isEmpty(Que): # verifies whether the queue is empty or not
print("Underflow")
else: # Allow deletions from the queue
item=Que.pop(0)
if len(Que)==0:
top=None
else:
top=len(Que)
print("Popped item is "+str(item))
def Display(Que):
if isEmpty(Que):
print("Queue is empty")
else:
top=len(Que)-1
print("Elements in the queue are: ")
for i in range(top,-1,-1):
print (str(Que[i]))
# executable code
if name == "main":
Que=[]
top=None
c='Y'
while (c=='Y'):
Opt=int(input('Enter 1. ENQUEUE 2. DEQUE 3. DISPLAY : '))
if (Opt==1):
Element=input('Enter a value to be inserted : ')
Enqueue(Que,Element)
elif Opt==2:
Dequeue(Que)
elif Opt==3:
Display(Que)
else:
print('Invalid input!')
c=input('Do you want to continue the queue operations [Y/N] : ')
print('QUEUE OPERATION IS OVER...')
def isEmpty(stk): # checks whether the stack is empty or not
if stk==[]:
return True
else:
return False
def Push(stk,item): # Allow additions to the stack
stk.append(item)
top=len(stk)-1
def Pop(stk):
if isEmpty(stk): # verifies whether the stack is empty or not
print("Underflow")
else: # Allow deletions from the stack
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)
print("Popped item is "+str(item))
def Display(stk):
if isEmpty(stk):
print("Stack is empty")
else:
top=len(stk)-1
print("Elements in the stack are: ")
for i in range(top,-1,-1):
print (str(stk[i]))
# executable code
if name == "main":
stk=[]
top=None
c='Y'
while (c=='Y'):
Opt=int(input('Enter 1. PUSH 2. POP 3. DISPLAY : '))
if (Opt==1):
Element=input('Enter a value to be inserted : ')
Push(stk,Element)
elif Opt==2:
Pop(stk)
elif Opt==3:
Display(stk)
else:
print('Invalid input!')
c=input('Do you want to continue the stack operations [Y/N] : ')
print('STACK OPERATION IS OVER...')
# Gnenerates a random number between 1 and 6 including 1 and 6
import random
x=input("Press Y to roll the DICE and N to exit : ")
x = "Y"
while x == "Y":
no = random.randint(1,6)
if no == 1:
print("[------]")
print("[ ]")
print("[ 1 ]")
print("[ ]")
print("[------]")
if no == 2:
print("[------]")
print("[ 1 ]")
print("[ ]")
print("[ 1 ]")
print("[------]")
if no == 3:
print("[------]")
print("[ ]")
print("[1 1 1]")
print("[ ]")
print("[------]")
if no == 4:
print("[------]")
print("[1 1]")
print("[ ]")
print("[1 1]")
print("[------]")
if no == 5:
print("[------]")
print("[1 1]")
print("[ 1 ]")
print("[1 1]")
print("[------]")
if no == 6:
print("[------]")
print("[1 1 1]")
print("[ ]")
print("[1 1 1]")
print("[------]")
x=input("press Y to roll again and N to exit:")
print("\n")
#To create CSV File for storing empno, name and salary
import csv
with open('myfile.csv',mode='a') as csvfile:
mywriter = csv.writer(csvfile,delimiter=',')
ans='y'
while ans.lower()=='y':
eno=int(input("Enter Employee Number "))
name=input("Enter Employee Name ")
salary=int(input("Enter Employee Salary :"))
mywriter.writerow([eno,name,salary])
print("## Data Saved... ##")
ans=input("Add More ?")
ans='y'
with open('myfile.csv',mode='r') as csvfile:
while ans.lower()=='y':
myreader = csv.reader(csvfile,delimiter=',')
found=False
e = int(input("Enter Employee Number to search :"))
for row in myreader:
if len(row)!=0:
if int(row[0])==e:
print("============================")
print("NAME :",row[1])
print("SALARY :",row[2])
found=True
break
if not found:
print("==========================")
print(" EMPNO NOT FOUND")
print("==========================")
csvfile.seek(0)
ans = input("Search More ? (Y)")
#Search for Rollno and display record if found else as not Exist
import pickle
student=[]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
marks = int(input("Enter Marks :"))
student.append([roll,name,marks])
ans=input("Add More ?(Y)")
pickle.dump(student,f)
f.close()
f=open('student.dat','rb+')
student=[]
while True:
try:
student = pickle.load(f)
except EOFError:
break
ans='y'
while ans.lower()=='y':
found=False
r = int(input("Enter Roll number to update :"))
for s in student:
if s[0]==r:
print("## Name is :",s[1], " ##")
print("## Current Marks is :",s[2]," ##")
m = int(input("Enter new marks :"))
s[2]=m
print("## After Updating the Mark is “,s[2], ” ##")
found=True
break
if not found:
print("####Sorry! Roll number not found ####")
ans=input("Update more ?(Y) :")
f.close()
#Program to create a binary file to store Rollno and name
#Search for Rollno and display record if found
#otherwise "Roll no. not found"
import pickle
student=[]
#Binary file opened as Append and Write Mode
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
student.append([roll,name])
ans=input("Add More ?(Y)")
pickle.dump(student,f)
f.close()
#Binary file opened as Read Mode
f=open('student.dat','rb')
student=[]
while True:
try:
student = pickle.load(f)
except EOFError:
break
ans='y'
while ans.lower()=='y':
found=False
r = int(input("Enter Roll number to search :"))
for s in student:
if s[0]==r:
print("## Name is :",s[1], " ##")
found=True
break
if not found:
print("####Sorry! Roll number not found ####")
ans=input("Search more ?(Y) :")
f.close()
#Program to create a file to store Rollno and name
#Program to read line from file and write it to another line
#Except for those line which contains letter “a”
f1 = open("file1.txt")
f2 = open("file1copy.txt","w")
for line in f1:
if 'a' not in line:
f2.write(line)
print("## File Copied Successfully! ##")
f1.close()
f2.close()
#Program to read content of file
#and display total number of vowels, consonants, lowercase and uppercase characters
f = open("File1.txt")
v=0
c=0
u=0
l=0
o=0
data = f.read()
vowels=['a','e','i','o','u']
for ch in data:
if ch.isalpha():
if ch.lower() in vowels:
v+=1
else:
c+=1
if ch.isupper():
u+=1
elif ch.islower():
l+=1
elif ch!=' ' and ch!='\n':
o+=1
print("Total Vowels in file :",v)
print("Total Consonants in file n :",c)
print("Total Capital letters in file :",u)
print("Total Small letters in file :",l)
print("Total Other than letters :",o)
f.close()
#Program to read content of file line by line
#and display each word separated by '#'
f = open("file1.txt")
for line in f:
words = line.split()
for w in words:
print(w+'#',end='')
print()
f.close()
#Program to find the occurrence of any word in a string
def countWord(str1,word):
s = str1.split()
count=0
for w in s:
if w==word:
count+=1
return count
str1 = input("Enter any sentence :")
word = input("Enter word to search in sentence :")
count = countWord(str1,word)
if count==0:
print("## Sorry! ",word," not present ")
else:
print("## ",word," occurs ",count," times ## ")
