70 Important Question CS
70 Important Question CS
70 Important Question CS
Q3) Q1 What possible output(s) are expected to be displayed on screen at the time of execution of the
program from the following code? Also specify the minimum values that can be assigned to each of the
variables BEGIN and LAST.
import random
VALUES = [10, 20, 30, 40, 50, 60, 70, 80]
BEGIN = random.randint (1, 3)
LAST = random.randint(2, 4)
for I in range (BEGIN, LAST+1):
print (VALUES[I], end = "-")
(i) 30-40-50- (ii) 10-20-30-40- (iii) 30-40-50-60- (iv) 30-40-50-60-70-
OUTPUT – (i) 30-40-50- Minimum value of BEGIN: 1 Minimum value of LAST: 2
-----------------------------------------------------------------------------------------------------------------------------------
Q4) What possible outputs(s) are expected to be displayed on screen at the time of execution of the program
from the following code? Also specify the maximum values that can be assigned to each of the variables
FROM and TO.
import random AR=[20,30,40,50,60,70]
FROM=random.randint(1,3)
TO=random.randint(2,4)
for K in range(FROM,TO):
print (AR[K],end=”#“)
(i)10#40#70# (ii)30#40#50# iii)50#60#70# (iv)40#50#70#
AnsMaximum value of FROM = 3
Maximum value of TO = 4
(ii) 30#40#50#
Q5) Q4 Consider the following code and find out the possible output(s) from the options given below. Also
write the least and highest value that can be generated.
import random as r
print(1 + r.r ndint(1 ,1 ) , end = ‘ ‘)
print(1 + r.r ndint(1 ,1 ) , end = ‘ ‘)
print(1 + r.r ndint(1 ,1 ) , end = ‘ ‘)
print(10 + r.randint(10,15))
i) 25 25 25 21 iii) 23 22 25 20 ii) 23 27 22 20 iv) 21 25 20 24
Ans
Possible outputs : i), iii) and iv)
Least value : 10
Highest value : 15
-----------------------------------------------------------------------------------------------------------------------------------
Q6) Assertion (A):- If the arguments in a function call statement match the number and order of arguments
as defined in the function definition, such arguments are called positional arguments.
Reasoning (R):- During a function call, the argument list first contains default argument(s) followed by
positional argument(s).
Ans: (c) A is True but R is False
-----------------------------------------------------------------------------------------------------------------------------------
Q7) Rao has written a code to input a number and check whether it is prime or not. His code is having
errors. Rewrite the correct code and underline the corrections made.
def prime():
n=int(input("Enter number to check :: ")
for i in range (2, n//2):
if n%i=0:
print("Number is not prime \n") break
else:
print("Number is prime \n’)
Ans:
def prime():
n=int(input("Enter number to check :: ")) #bracket missing
for i in range (2, n//2):
if n%i==0: # = missing
print("Number is not prime \n")
break #wrong indent
else:
print("Number is prime \n”) # quote mismatch
Q8) (a)Given is a Python string declaration:
myexam="@@CBSE Examination 2022@@"
Write the output of: print(myexam[::-2])
Ans: @20 otnmx SC@
-----------------------------------------------------------------------------------------------------------------------------------
Q8)Write the output of the code given below: my_dict = {"name": "Aman", "age": 26} my_dict['age'] = 27
my_dict['address'] = "Delhi" print(my_dict.items())
Ans: dict_items([('name', 'Aman'), ('age', 27), ('address', 'Delhi')])
-----------------------------------------------------------------------------------------------------------------------------------
def Diff(N1,N2):
if N1>N2:
return N1-N2
else:
return N2-N1
NUM= [10,23,14,54,32]
for CNT in range (4,0,-1):
A=NUM[CNT]
B=NUM[CNT-1]
print(Diff(A,B),'#', end=' ')
Ans: 22 # 40 # 9 # 13 #
-----------------------------------------------------------------------------------------------------------------------------------
Q14) A _________ statement skips the rest of the loop and jumps over to the statement following the loop.
Ans) break
-----------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------
Q20) write a method in python to read lines from a text file MYNOTES.TXT and display those lines which
start with alphabets 'K'
Ans) def display ():
file=open(MYNOTES.TXT’ , ‘r’)
lines=file.readlines()
while line:
if line[0]==’K’ :
print(line)
line=file.readline()
file.close()
-----------------------------------------------------------------------------------------------------------------------------------
Q21) write a program that copies a text file "source.txt" onto "target.txt" barring the lines starting with @
sign.
Ans) def filter (oldfile, newfile):
fin =open (oldfile, “r”)
fout= open (newfile, “w”)
while True:
text =fin.readline ()
if len(text)==0:
break
if text[0]== “@”:
continue
fout.write(text)
fin.close()
fout.close()
filter(“source.txt” , “target.txt”)
-----------------------------------------------------------------------------------------------------------------------------------
Q22) What is pickling and unpickling of data?
Ans) Pickling is the process of transforming data or an object in memory (RAM) to a stream of bytes called
byte streams. These byte streams in a binary file can then be stored in a disk or in a database or sent through
a network. Unpickling is the inverse of pickling process where a byte stream is converted back to Python
object.
-----------------------------------------------------------------------------------------------------------------------------------
Q23) Amritya Seth is a programmer, who has recently been given a task to write a python code to perform
the following binary file operations with the help of two user defined functions/modules: a. AddStudents() to
create a binary file called STUDENT.DAT containing student information – roll number, name and marks
(out of 100) of each student. b. GetStudents() to display the name and percentage of those students who have
a percentage greater than 75. In case there is no student having percentage > 75 the function displays an
appropriate message. The function should also display the average percent.
Ans)
i.import pickle
def AddStudents():
F= open("STUDENT.DAT",'wb')
while True:
Rno = int(input("Rno :"))
Name = input("Name : ")
Percent = float(input("Percent :"))
L = [Rno, Name, Percent]
c. pickle.dump(L,F)
Choice = input("enter more (y/n): ")
if Choice in "nN":
break
F.close()
def GetStudents():
Total=0
Countrec=0
Countabove75=0
with open("STUDENT.DAT","rb") as F:
while True:
try:
R = pickle.load(F)
Countrec+=1
Total+=R[2]
if R[2] > 75:
print(R[1], " has percent =",R[2])
Countabove75+=1
except:
break
if Countabove75==0:
print("There is no student who has percentage more than 75")
F.close()
-----------------------------------------------------------------------------------------------------------------------------------
Q24) What is the advantage of using a csv file for permanent storage?
Write a Program in Python that defines and calls the following user defined functions:
a. ADD() – To accept and add data of an employee to a CSV file ‘record.csv’. Each record consists of a
list with field elements as empid, name and mobile to store employee id, employee name and employee
salary respectively.
b. COUNTR() – To count the number of records present in the CSV file named ‘record.csv’.
Ans:
Advantage of a csv file:
• It is human readable – can be opened in Excel and Notepad applications
• It is just like text file
Program:
import csv
def ADD():
fout=open("record.csv","a",newline="\n")
wr=csv.writer(fout)
empid=int(input("Enter Employee id :: "))
name=input("Enter name :: ")
mobile=int(input("Enter mobile number :: "))
lst=[empid,name,mobile]
wr.writerow(lst)
fout.close()
def COUNTR():
fin=open("record.csv","r",newline="\n")
data=csv.reader(fin)
d=list(data)
print(len(d))
fin.close()
ADD()
COUNTR()
-----------------------------------------------------------------------------------------------------------------------------------
Q25) Give any one point of difference between a binary file and a csv file.
Write a Program in Python that defines and calls the following user defined functions:
a. add() – To accept and add data of an employee to a CSV file ‘furdata.csv’. Each record consists of
a list with field elements as fid, fname and fprice to store furniture id, furniture name and furniture price
respectively.
b. search()- To display the records of the furniture whose price is more than 10000.
Ans)
• Binary file:
• Extension is .dat
• Not human readable
• Stores data in the form of 0s and 1s
CSV file
• Extension is .csv
• Human readable
• Stores data like a text file
Program:
import csv
def add():
fout=open("furdata.csv","a",newline='\n')
wr=csv.writer(fout)
fid=int(input("Enter Furniture Id :: "))
fname=input("Enter Furniture name :: ")
fprice=int(input("Enter price :: "))
FD=[fid,fname,fprice]
wr.writerow(FD)
fout.close()
def search():
fin=open("furdata.csv","r",newline='\n') data=csv.reader(fin)
found=False
print("The Details are") for i in data:
if int(i[2])>10000:
found=True
print(i[0],i[1],i[2])
if found==False:
print("Record not found")
fin.close()
add()
print("Now displaying")
search()
-----------------------------------------------------------------------------------------------------------------------------------
Q26)Write stack program to enter detail of person who live in delhi. And pop() function for delete?
def Push_record(List):
for i in List:
if i[2]=="Delhi":
Record.append(i)
print(Record)
def Pop_record():
while True:
if len(Record)==0:
print('Empty Stack')
break
else:
print(Record.pop())
-----------------------------------------------------------------------------------------------------------------------------------
Q27) Add element in the stack and pop element from the stack using function()?
Ans)
N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
def PushElement(S,N):
S.append(N)
def PopElement(S):
if S!=[ ]:
return S.pop()
else:
return None
ST=[]
for k in N:
if k%7==0:
PushElement(ST,k)
while True:
if ST!=[ ]:
print(PopElement(ST),end=" ")
else:
break
Unit 1: Unit 2: Computer Networks
Chapter4: Unit 2: Computer Networks
Q29)
-----------------------------------------------------------------------------------------------------------------------------------
Q32
(i) Define network device Gateway with respect to computer networks.
(ii) How is ARPANET different from NSFNET?
Ans) (i) Gateway serves as the entry and exit point of a network, as all data coming in or going out of a
network must first pass through the gateway in order to use routing paths. It's a device that connects
dissimilar networks.
(ii) ARPANET (Advanced Research Project Agency Network): It is a project sponsored by U. S. Department
of Defense to connect the academic and research institutions located at different places for scientific
collaborations
-----------------------------------------------------------------------------------------------------------------------------------
Q33)
-----------------------------------------------------------------------------------------------------------------------------------
Q34) What are Protocols? Name the protocol used to transfer a file from one device to the other.
Ans Protocols are set of rules that are followed while transmitting data through a computer network.
Protocols determines how to data can be moved securely from a source device to a destination device. The
protocol used for transferring a file from one device to another is the File Transfer Protocol (FTP)
-----------------------------------------------------------------------------------------------------------------------------------
Q38)Explain why Circuit Switching is not cost effective compared to Packet Switching?
Ans The Circuit Switching is not cost effective like Packet Switching because, in Circuit Switching, every
time there is a need to set up a connection between the sender and the receiver before communicating the
message.
-----------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------
Unit 3: DBMS
Chapter4:DBMS
Q41)Fill in the blank:
_____ is a non-key attribute, whose values are derived from the primary key of some other
table.
(A) Primary Key (B) Candidate Key (C) Foreign Key (D) Alternate Key
ANS)(B)
-----------------------------------------------------------------------------------------------------------------------------------
Q42 )An Attribute in a relations a foreign key if it is the _____ key in any other relation.
(A) Candidate Key (B) Foreign Key (C) Primary Key (D) Unique Key
Ans)c
-----------------------------------------------------------------------------------------------------------------------------------
Q43) An attribute in a relation is a foreign key if it is the ________ key in any other relation.
(A) Candidate Key (B)Foreign Key (C) Primary Key (D)Unique Key
Ans)c
-----------------------------------------------------------------------------------------------------------------------------------
Q44) _________ is an attribute, whose values are Unique and not null.
(A) Primary Key (B)Foreign Key (C)Candidate Key (D)Alternate Key
Ans)a
Q45 Select the correct statement, with reference to RDBMS:
a) NULL can be a value in a Primary Key column
b) ' ' (Empty string) can be a value in a Primary Key column
c) A table with a Primary Key column cannot have an alternate key.
d) A table with a Primary Key column must have an alternate key.
Ans)d
-----------------------------------------------------------------------------------------------------------------------------------
Q46) What are the differences between DELETE and DROP commands of SQL?
DELETE is DML command while DROP is a DDL command. Delete is used to delete rows from a table
while DROP is used to remove the entire table from the database.
-----------------------------------------------------------------------------------------------------------------------------------
Q49) A table "Animals" in a database has 3 columns and 10 records. What is the degree and cardinality of
this table?
ans)
Degree 3 and Cardinality=10
-----------------------------------------------------------------------------------------------------------------------------------
a. DESCRIBE
b. UNIQUE
c. DISTINCT
d. NULL
Q51)
Fill in the blank:
is a non-key attribute, whose values are derived from the primary key of some other table.
a. Primary Key
b. Foreign Key
c. Candidate Key
d. Alternate Key
Q52)
Which of the following commands will delete the table from MYSQL database?
a. DELETE TABLE
b. DROP TABLE
c. REMOVE TABLE
d. ALTER TABLE
Ans: (b) DROP TABLE
-----------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------
Q58) Categorize the following commands as DDL or DML: INSERT, UPDATE, ALTER, DROP
Ans:
DDL- ALTER, DROP DML – INSERT, UPDATE
-----------------------------------------------------------------------------------------------------------------------------------
Q59)
-----------------------------------------------------------------------------------------------------------------------------------
Q60) Write a method COUNTLINES() in Python to read lines from text file ‘TESTFILE.TXT’ and display
the lines which are not starting with any vowel.
Example:
If the file content is as follows:
An apple a day keeps the doctor away. We all pray for everyone’s safety.
A marked difference will come in our country.
The COUNTLINES() function should display the output as: The number of lines not starting with any vowel
-1
Ans:
def COUNTLINES() :
file = open ('TESTFILE.TXT', 'r') lines = file.readlines()
count=0
for w in lines :
if (w[0]).lower() not in 'aeoiu' count = count + 1
print ("The number of lines not starting with any vowel: ", count)
file.close()
-----------------------------------------------------------------------------------------------------------------------------------
Q61)
Ans)
(i) SELECT TNAME, CITY, SALARY FROM TRAINER ORDER BY HIREDATE;
(ii) SELE T TNAME, TY FROM TRA NER WHERE H REDATE BETWEEN ‘ 1-12- 1’AND ‘ 1-12-31’;
(iii) SELECT TNAME,HIREDATE,CNAME,STARTDATE FROM TRAINER, COURSE WHERE
TRAINER.TID=COURSE.TID AND FEES<=10000;
(iv) SELECT CITY, COUNT(*) FROM TRAINER GROUP BY CITY;
-----------------------------------------------------------------------------------------------------------------------------------
Q62)Satyam. a database analyst has created thefollowing table:
Q63)
Ans)
-----------------------------------------------------------------------------------------------------------------------------------
Q66). Write the Python code to display the present databases in MySQL
Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,password=”root”)
cursor=mycon.cursor()
cursor.execute(“show databases”)
for i in cursor:
print(i)
mycom.close()
-----------------------------------------------------------------------------------------------------------------------------------
Q67) Write the Python code to insert data into student table of database kvs in MYSQL .
Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,password=”root”,database=”kvs”)
cursor=mycon.cursor()
no=int(input(“Enter roll no “))
n=input(“Enter name “)
g=input(“Enter gender ”)
dob=input(“Enter DOB “)
m=float(input(“Enter mark ”))
query= “insert into student values( {}, ‘{}’ , ‘{}’ , ’{}’ , {} )”.format( no,n,g,dob,m)
cursor.execute(query)
mycon.commit( )
----------------------------------------------------------------------------------------------------------------------------------
Q68) (i) What is the difference between degree and cardinality with respect to RDBMS. Give one example
to support your answer.
(ii) Mr. Shuvam wants to write a program in Python to Display the following record in the table named EMP
in MYSQL database EMPLOYEE with attributes: •EMPNO (Employee Number ) - integer • ENAME
(Employee Name) - string size(30) • SAL (Salary) - float (10,2) • DEPTNO(Department Number) - integer
Note: The following to establish connectivity between Python and MySQL: • Username - root • Password –
admin • Host – localhost The values of fields rno, name, DOB and fee has to be accepted from the user. Help
Shuvam to write the program in Python.
Ans)
(i) DEGREE: The number of attributes in a relation is called the Degree of the relation. For example,
relation GUARDIAN with four attributes is a relation of degree 4.
CARDINALITY: The number of tuples in a relation is called the Cardinality of the relation. For example,
the cardinality of relation GUARDIAN is 5 as there are 5 tuples in the table.
import mysql.connector
mycon=mysql.connector.connect(host="localhost", user="root", passwd="admin",database="EMPLOYEE")
mycursor=mycon.cursor()
print("\nBEFORE DELETION CONTENT OF EMP TABLE FOLLOWS: ")
mycursor.execute("SELECT * FROM EMP")
for k in mycursor:
print(k)
eno=int(input("Enter the empno which record you want to delete: "))
qr="DELETE FROM EMP WHERE empno={}".format(eno)
mycursor.execute(qr)
mycon.commit() # To save above DML tansactions to the databases otherwise will not save permanently
print("\nAFTER DELETION CONTENT OF EMP TABLE FOLLOWS: ")
mycursor.execute("SELECT * FROM EMP")
for k in mycursor:
print(k)
mycon.close()
--------------------------------------------------------------------------------------------------------------------------------
Q69) (i) What is the difference between Primary and Foreign key?
(ii) Mr. Pranay wants to write a program in Python to update the particular record by accepting its
Department Number value in the table named DEPT in MYSQL database EMPLOYEE with attributes:
•DEPTNO (Department Number) – integer • DNAME (Department Name) – string size(15) •LOC(Location
of the Department) – string size(15) Note: The following to establish connectivity between Python and
MySQL: • Username - root • Password – admin • Host – localhost The values of fields rno, name, DOB and
fee has to be accepted from the user. Help Kabir to write the program in Python.
Ans)
(i) Primary Key: One or more than one attribute chosen by the database designer to uniquely identify the
tuples in a relation is called the primary key of that relation.
Foreign key: It is used to represent the relationship between two relations. A foreign key is an attribute
whose value is derived from the primary key of another relation.
(ii)
import mysql.connector
mycon=mysql.connector.connect(host="localhost", user="root",passwd="admin", database="EMPLOYEE")
mycursor=mycon.cursor()
dno=int(input("Enter the DEPT. NO which record you want to update: "))
qr="SELECT * FROM DEPT WHERE deptno={}".format(dno)
mycursor.execute(qr)
rec=mycursor.fetchall()
print("\n Old Record is follows: ")
for k in rec:
print(k)
print("\nENTER DETAILS TO UPDATE RECORD:\n")
print("Entered DEPTNO No:",dno)
dname=input("Enter Department Name:")
loc=input("Enter Location of the Department:")
qr="UPDATE dept SET dname='{}', loc='{}' WHERE deptno={}".format(dname, loc,dno)
print(qr)
mycursor.execute(qr)
mycon.commit()
print("\nNEW RECORD AFTER UPDATE OF TABLE: ")
mycursor.execute("SELECT * FROM DEPT")
for k in mycursor:
print(k)
mycon.close()
--------------------------------------------------------------------------------------------------------------------------------
Q70) Question from PB-1(33)
Ans)
def ChecknDisplay():
import mysql.connector as mycon
mydb=mycon.connect(host="localhost",user="root", passwd="school123",database="COMPANY")
mycur=mydb.cursor()
eid=input("Enter EmpID : ")
nm=input("Enter EmpName : ")
s=input("Enter Salary: ")
dept=input("Enter Department : ")
query="INSERT INTO EMPLOYEES VALUES ({},'{}',{},’{}’)". format(eid,nm,s,dept)
mycur.execute(query)
mydb.commit()
mycur.execute("select * from EMPLOYEES where salary>50000")
for rec in mycur:
print(rec)
-----------------------------------------------------------------------------------------------------------------------------------