0% found this document useful (0 votes)
14 views18 pages

CS Question Bank 2024

Uploaded by

singhasrijan11
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views18 pages

CS Question Bank 2024

Uploaded by

singhasrijan11
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

CHAPTER 1 : REVISION OF THE BASICS

OF PYTHON

Objective Type Questions


STATE THE GIVEN STATEMENTS ARE TRUE OR Explanation: Execution always begins at the
FALSE. first
Q. 1. Identity of the object is its address in memory statement of the program. Statements are executed one
and does not get change once it is created. after the other from top to bottom.
Ans. True FILL IN THE BLANKS
Explanation: Every object has: Q. 1. Looping statement in python is implemented by using
An Identity, A type, and A value. …………… and statement.
Q. 2. Set is mutable. Ans. ‘for’, ‘while’
Ans. False Explanation: In some programs, certain set of
Explanation: Set is unordered collection of statements are executed again and again based upon
values of any type with no duplicate entry. It is conditional test. i.e., executed more than one time. This
immutable. type of execution is called looping or iteration.
Q. 3. In Python, comments start with ‘#’ symbol. Q. 2. Strings are in python.
Ans. True Ans. Immutable
Explanation: In Python, comments start with Explanation: Strings are immutable i.e. the contents of
‘#’ symbol. Anything written after # in a line is the string cannot be changed after it is created.
ignored by interpreter. There are three ways to Q. 3. To use modules in a program, programmer needs to
write a comment – as a separate line, beside the ……………. the module.
corresponding statement of code, or as a multi- Ans. import
line comment block. Explanation: A module is a file containing Python
Q. 4. From statement is used to get a specific function definitions (i.e. functions) and statements. Import
in the code instead of complete file. keyword is used to import built-in and user-defined
Ans. True modules and packages in python programming.
Explanation: For modules having large number Q. 4. are the value(s) provided in
of functions, it is recommended to use from function call/invoke statement.
instead of import. The from keyword is used to Ans. Arguments
import only a specified section from a module Explanation: SI (1000, 2, 10) 1000, 2, 10 are arguments.
not a complete module.
An argument can be constant, variable, or expression.
Syntax
Q. 5. The index value of tuple starts from ………..
>>> from modulename import functionname Ans. 0
[functionname…..]
Explanation: A tuple is a sequence of values, which can
Q. 5. Execution always begins at the last statement of be of any type and they are indexed by integer started
the program. from 0, 1, 2, 3 and so on.
Ans. False

Long Answer Type Questions


Q. 1. The following code takes n numbers and reverse
the set of numbers. Write the following missing
statements to complete the code.
Statement 1: to input the number.
Statement 2: to store the number in the
num. Statement 3: to display the reverse
numbers.
n = int(input(“Enter number of values”))
num = []
flag = 0
for i in range(n):
number =………………………………… Statement 1
num. Statement 2 j =
n – 1
for n
i /
2
i :
n num[i],
num[j]=num
r [j],
a num[i] j =
n j – 1
g else:
e break
( ………………………….
n Statement 3
)
: Ans. Statement 1.
input(“Enter the
number”)
i
f Statement 2.
append(number)
i Statement 3.
print(num)
< Output
Enter number of values 3
= Enter the number 1 Enter
the number 3 Enter the
number 5 [‘5’, ‘3’, ‘1’]

CHAPTER 2 : FUNCTIONS

Objective Type Questions


STATE THE GIVEN STATEMENTS ARE TRUE OR complexity of the program.
FALSE Ans. True
Q. 1. A function is used to do a specific task. Explanation: Advantages of dividing a program
Ans. True into modules:
Explanation: A function is a set of instructions ● Reduces complexity of the program.
or subprograms that are used to fulfil the user’s ● Eases code reusability.
need. A function is used to do a specific task and ● Helps create well defined boundaries within
divide the large program into smaller blocks. the program.
Q. 2. Function calling statement invokes the function. FILL IN THE BLANKS
Ans. True Q. 1. When mutable type arguments are passed to
Explanation: This is the final part of a function. a function, its ……………. is also passed to the
It invokes the function and returns the output function.
as instructed into the function body.
Q. 3. Positional Arguments allows the user to pass as
many arguments as required in the program.
Ans. False
Explanation: Positional Arguments:
Arguments passed to a function in correct
positional order, no. of arguments must match
with no. of parameters required.
Variable Length Arguments: It allows the user
to pass as many arguments as required in the
program. Variable-length arguments are
defined with the * symbol.
Q. 4. A variable that is declared in top-level
statements is called a global variable.
Ans. True
Explanation: To access the value of a global
variable, a user needs to write a global keyword
in front of the variable in a function.
Q. 5. Dividing a program into modules reduces
Ans. reference
Explanation: When mutable type arguments are passed
to a function, its reference is also passed to the function
and hence, their values can be altered by the function.
When immutable type arguments are passed to a
function, only its value is passed to the function and
hence, their values cannot be altered by the function.
Q. 2. The ………….. function returns the number of items in an
object.
Ans. len()
Explanation: If the object being passed is a string, then
the len() function returns the number of characters in
string.
Q. 3. A …………..variable is accessible only in the function
where it is declared.
Ans. local
Explanation: A local variable is accessible only in the
function where it is declared i.e., it is declared inside a
function and can be accessed only from that function.
Q. 4. functions do not return any value.
Ans. Void
Explanation: Void functions are those functions that do
not return any value or don’t have a return statement.
Q. 5. The functions that you can readily use without having to
write any special code are pre-defined functions called
functions.
Ans. built-in
Explanation: The Python built-in functions are defined
as the functions whose functionality is pre-defined in
Python. The python interpreter has several functions
that are always present for use. These functions are
known as Built-in Functions.
Examples of built-in functions:
● len( )
● type( )
● input( )
Long Answer Type Questions
Q. 1. The following code represent a function name as even Sum (Numbers) that add those values in the list of Numbers,
which are even. Write the following missing statements to complete the code. Statement 1: header of the function.
Statement 2: loop used to iterate the values of list. Statement 3: to check the numbers of list are even or not.
: Statement 1
sum=0
i in range(len(Numbers)):
Statement 2
If : Statement 3
sum=sum+Numbers[i]
print(sum)
Ans. Statement 1
def evenSum(Numbers)
Statement 2 for
Statement 3
Numbers[i] %2 == 0
CHAPTER 3 : FILE HANDLING

Objective Type Questions


STATE THE GIVEN STATEMENTS ARE TRUE OR Ans. True
FALSE
Explanation: Binary file consists of data stored as a
Q. 1. dump and load functions are used to write and
stream of bytes i.e. as it is stored in computer memory
read data from file.
(binary language). No translation occurs in binary file. In
Ans. True
binary file no end of line transaltion. Faster than text file.
Explanation: dump()use to write the object in FILL IN THE BLANKS
file, which is opened in binary access mode. Q. 1. module is used in serialization of data.
load()use to read the object from pickle file Ans. pickle
Q. 2. Reading from a CSV file is done using the reader Explanation: Pickle is the process of converting a Python
object. object into a byte stream to store it in a file/ database,
Ans. True maintain program state across sessions, or transport
data over the network.
Explanation: A CSV file can be defined as a
Q. 2. function returns the current position of the
simple file format that have the values file pointer.
sequenced by comma-separation and is then
Ans. tell()
stored as a plain text.
Explanation: In python programming, within file
Q. 3. Every file has a tail pointer which tells the handling concept tell() function is used to get the actual
current position in the file where writing or position of file object.
reading will take place. Q. 3. function changes the position of file pointer
Ans. False by placing the pointer at the specified position.
Explanation: File Pointer tells the current Ans. seek()
position in the file where the reading or writing Explanation: seek() function is used to change the
will take place. position of the File Handle to a given specific position.
Q. 4. method is used to write multiple strings to a
Q. 4. The relative paths are from the topmost level of
file.
the directory structure.
Ans. writelines()
Ans. False Explanation: writelines() method is used to write
Explanation: The absolute Paths are from the multiple strings to a file. We need to pass an iterable
topmost level of the directory structure. The object like lists, tuple, etc. containing strings to
relative paths are relative to the current writelines() method.
working directory denotes as a dot(.) while its
parent directory is denoted with two dots(..).
Q. 5. Binary file consists of data stored as a stream of
bytes.
Q. 5. To handle data files in python, we need to have file, first
a
thing we do is open it. This is done by using built in
object.
function open().
Ans. file
Using this function a file object is created which is then
Explanation: Object can be created by using used for accessing various methods and functions
open() function or file() function. To work on available for file manipulation.

Long Answer Type Questions


Q. 1. The following code of storing multiple integer if Choice in “nN” :
values in a binary file and then read and display break
it on screen. Write the following missing F.close ( )
statements to complete the code. def GetStudents ( ) :
Statement 1: to opening a binary file(data.dat) Total = 0
for writing in it. Count_rec = 0
Statement 2: put integer value in Count_above75 = 0
file. Statement 3: to close the file. with open (“STUDNET.DAT”, “rb”)
def binfile(): as F:
import pickle while True:
int(raw_input( #3
while True: )) statement
Statement 1 to read from
x = the file
try:
Stateme Name, Percent]
nt 2 ans = raw_input(‘want to #2 statement to
write
enter more
the list L into the file
data Y / N’)
if ans.upper()== ‘N’ : break Choice = input (“enter more
(y/n) : “)
Stateme
nt 3 Count_rec+=1
file = Total+=R [ 2]
open(‘data.dat’,’rb’) if R [2] > 75:
try : print (R [1], “has
while True : percent = “, R [2])
y = pickle.load(file) Count_above_75+=1
print y except:
except EOFError : break
pass if Count_above_75==0 :
file.close() print (“There is no student who
Ans. Statement 1. has percentage more than 75”)
file = open(‘data.dat’,’wb’) average=Total/Count_rec
Statement 2. print (“average percent of class
pickle.dump(x,file) = “,average)
Statement 3. AddStudents( )
file.close() GetStudents( )
(i) which command should be given (marked as
Q. 2. Anubhav has written the following code in
# 1 in the Python code) to open the data file.
Python to create a binary file STUDENTDAT to
add records and to count the number of (ii) Which commands is used to write the list L into the
students who have scored marks above 75. Help binary file, STUDENTDAT? (marked as #2 in the
him complete the code based on the given Python code)
requirements. (iii) Which command is used to read each record from
import pickle the binary file STUDENTDAT? (marked as #3 in the
Python code). What is the function of seek()
def AddStudents ( ) :
method?
#1 statement to open
the Ans. (i) F = open(“STUDENT.DAT”,’wb’)
binary file to write (ii) pickle.dump(L, F)
data while True: (iii) R = pickle.load(F).
Rno = int seek() moves the current file pointer to a given
(input(“Rno:”)) Name specified position.
= input (“Name : “) Q. 3. Radha Shah is a programmer, who has recently been
Percent = float (input given a task to write a python code to perform the
(“Percent : “)) L = [Rno, following CSV file operations with the help of two user
defined functions/modules:
(a) CSVOpen( ): to create a CSV file called BOOKS.CSV
in append mode containing information of books–
Title, Author and Price.
(b) CSVRead( ): to display the records from
the CSV file called BOOKS.CSV where the
field title starts with ‘R’.
She has succeeded in writing partial code and
has missed out certain statements, so she has
left certain queries in comment lines.
import csv
def CSVOpen ( ) :
with open
(‘books.csv’,
‘ ’, newline=’ ‘) as
csvf:
queries in comment lines. You as an expert of python
have to provide the missing statements and other related
queries based on the following code of Amritya.
import pickle
def AddStudents ( ):
#1 statement to open the
binary file to write data
while True:
Rno = int (input(“Rno:”))
cw= #Statement 1 (“Name:”)
#Statement 2 Percent = float
(input (“Percent:”))
Name = input
cw.writerow ([‘Rapunzel’, ‘Jack’, 300])
L = [Rno, Name, Percent]
cw.writerow ([‘Barbie’, ‘Doll’,
900]) #2 statement to write
cw.writerow ([‘Johnny’, ‘Jane’, csvf:
280]) def CSVRead ( ) : the list L into the file
try: Choice = input (“enter more
with open (‘books.csvm’, ‘r’) as (y/n):”) if Choice in “nN”:
break
cr= : #Statement 4 ts
for r in F.close( ) ( )
cr: if def :
#Statement 3 Get Tot
Stu al
den = 0
print (r) Count_above_75 =
except : Count_rec = 0 0
print (‘File Not Found’) You as an expert of Python have to provide the
CSVOpe with open (“STUDENT.DAT”, “rb”) as
F:
n( )
while True:
CSVRea try:
d( )
missing statements and other related queries
based
#3 statement to read
on the following code of Radha. print (R [1], “has percent
(i) Which statement will be used to create a =”, R[2])
csv writer object in Statement 1. Count_above_75+=1
(ii) Fill in the blank in Statement 2 to write except:
the name of the column headings in the break
CSV file, BOOKS.CSV. if Count_above_75==0:
(iii) Which statement will be used to read a print (“There is no student who
csv file in Statement 3 and Fill in the has
appropriate statement to check the field percentage more than 75”)
Title starting with ‘R’ for Statement 4. average=Total/Count_rec
Ans. (i) csv.writer(csvf) print (“average percent of class
(ii) cw.writerow([‘Title’, ‘Author’, =”, average)
AddStudents ( )
‘Price’]) cw. writerows(‘Title’,
GetStudents ( )
‘Author’, ‘Price’)
(i) Which command is used to open the file
(iii) cvs.reader(csvf) and r[0] “STUDENTDAT” for writing only in binary format?
[0]==’R’ FILE HANDLING (marked as #1 in the Python code)
Q. 4. Amritya Seth is a programmer, who has recently (ii) Which commands is used to write the list L into the
been given a task to write a python code to binary file, STUDENTDAT? (marked as #2 in the
perform the following binary file operations Python code)
with the help of two user defined (iii) Which command is used to read record from the
functions/modules: binary file STUDENTDAT? (marked as #3 in the
(a) AddStudents() to create a binary file Python code) what is r+ mode of file opening?
called STUDENTDAT containing student Ans. (i) F = open(“STUDENT.DAT”,’wb’).
information-roll number, name and (ii) pickle.dump(L,F)
marks (out of 100) of each student. (iii) R = pickle.load(F). It’ opens a file for both reading
(b) GetStudents() to display the name and and writing. The file pointer will be at the
percentage of those students who have a beginning of the file.
percentage greater than 75. In case
there is no students having percentage >
75 the function displays an appropriate
message. The function should also display
the average percent.
He has succeeded in writing partial code and
has missed out certain statements, so he has left
certain
from the file
Count_rec+=1
Total+=R [2]
if R [2] > 75:
CHAPTER 4 : DATA STRUCTURE
STATE THE GIVEN STATEMENTS ARE TRUE OR POP operation is applied on it, it comes to an
FALSE underflow condition and thus results in an
Q. 1. Lists are the container which store the error.
heterogeneous elements of any type. FILL IN THE BLANKS
Ans. True Q. 1. A is an organized group of data of
Explanation: list is a sequence data structure in different data types.
which each element may be of different types. Ans. Data Structure
We can apply different operations like reversal, Explanation: Data Structures are a way of organizing
slicing, counting of elements, etc. on list. data so that it can be accessed more efficiently depending
Q. 2. A stack is a linear data structure implemented in upon the situation. Python has implicit support for Data
LIFO (Last In First Out) manner. Structures which enable you to store and access data.
Ans. True These structures are called List, Dictionary, Tuple and
Explanation: A stack is a data structure whose Set.
elements are accessed according to the Last-In Q. 2. Removing data from stack is called .
Ans. POP
First- Out (LIFO) principle. This is because in a
Explanation: POP operation is used to remove the top
stack, insertion and deletion of elements can
most element of the stack, that is, the element at the TOP
only take place at one end, called top of the
of the stack. It is a delete operation. We can delete
stack
elements from a stack until it is empty.
Q. 3. Adding data into stack is called POP. Q. 3. refers to condition when one tries to
Ans. False POP an item from a stack that is empty.
Explanation: PUSH adds a new element at the Ans. Underflow
TOP of the stack. It is an insertion operation. We Explanation: Trying to delete an element from an
can add elements to a stack until it is full. POP empty stack results in an exception called ‘underflow’.
deletes an element at the TOP of the stack. Q. 4. Before every PUSH operation, the value of “Top” is
Q. 4. In a stack, insertion and deletion takes place at incremented by and then value is
one end i.e., the top of the stack. inserted at the top of stack.
Ans. True Ans. one
Explanation: In a stack, both deletion and Explanation: Whenever we add any element “data” in
insertion always takes place at one end called the list, then it will be called as ‘Push operation’ on stack.
the ‘top’ of the stack. Q. 5. When evaluating any expression using
Stack, only operands are Pushed onto it.
Q. 5. Popping from an empty stack results causes an Ans. Postfix
error. Explanation: While reading the expression from left to
Ans. True right, push the element in the stack if it is an operand.
Explanation: The underflow condition is the Pop the two operands from the stack, if the element is an
condition in which no new element can be operator and then evaluate it. Push back the result of the
removed from the stack, it means stack is evaluation. Repeat it till the end of the expression.
empty. So, if the stack is empty and then if the

Long Answer Type Questions


Q. 1. The following code represents the pop method Statement 1: to end the execution of a function
in stack to print a string in reverse order. Write and
the following missing statements to complete return to the calling environment.
the code. def pop Stack (stack): Statement 2: to assign variable top with the index
if isempty(stack): position of the element which was last entered in the
Statemen stack.
t 1 Statement 3: to print the item in the list at index position
else: [a].
Statemen Ans. Statement 1.
t 2 return
for a in range (top, –1, –1): Statement 2.
Statemen top = len(stack) –1
t 3 Statement 3.
return print(stack[a])
CHAPTER 5 : DATA COMMUNICATION &
NETWORK TOPOLOGIES

Objective Type Questions


STATE THE GIVEN STATEMENTS ARE TRUE OR FALSE
Q. 1. WWW is a set of protocols that allow you to access any document on the internet through the naming systems based
on URLs.
Ans. True
Explanation: The World Wide Web (WWW) or web in short, is an ocean of information, stored in the form of trillions
of interlinked web pages and web resources. The resources on the web can be shared or accessed through the
Internet.
Q. 2. Every web site has a unique address called the web address.
Ans. True
Explanation: A Uniform Resource Locator (URL) is used to specify, where an identified resource is available in the
network and the mechanism for retrieving it. A URL is also referred to as a web address.
Q. 3. URL is also known as Internet Protocol address.
Ans. False
Explanation: IP address, also known as Internet Protocol address, in a unique address that can be used to uniquely
identify each node in a network.
Q. 4. A DNS Server is a computer used to resolve host names to IP addresses.
Ans. True
Explanation: A DNS Server is a computer used to resolve hostnames to IP addresses. For example, a DNS server
translates Myexample.in to 212.15.25.105.
Q. 5. A computer that facilitates sharing of data, software and hardware resources on the network is known as the client.
Ans. False
Explanation: A computer that facilitates sharing of data, software and hardware resources on the network is known
as the server. Servers can be of two types:
(a) Dedicated and
(b) Non dedicated servers
FILL IN THE BLANKS
Q. 1. In switching physical connection is established between sender and receiver.
Ans. Circuit
Explanation: In circuit switching, a dedicated path exists from source to destination while in packet switching, there is no
fixed path.
Q. 2. is a network that connects a variety of nodes placed at a limited distance ranging.
Ans. LAN
Explanation: LAN is a network that connects a variety of nodes placed at a limited distance ranging from a single room, a floor,
an office or a campus having one or more buildings in the same premises.
Q. 3. topology is based on a central which acts as a hub.
Ans. Star
Explanation: In star topology, each communicating device is connected to a central node, which is a networking device like a
hub or a switch.
Q. 4. A is a collection of two or more computers linked together for the purpose of sharing information and resources.
Ans. Computer Network
Explanation: A network is any collection of independent computers that communicate with one another over a shared
network medium.
Q. 5. Each computer on the network is called a .
Ans. Node
Explanation: In a communication network, each device that is a part of a network and that can receive, create, store or send
data to different network routes is called node.

CHAPTER 6 : DATABASE
CONCEPTS
STATE THE GIVEN STATEMENTS ARE TRUE OR
Ans. Foreign Key
FALSE
Explanation: A foreign key is used to represent the
Q. 1. A relational database is a collection of tables.
relationship between two relations. A foreign key is an
Ans. True attribute whose value is derived from the primary key of
Q. 2. The degree of the relationship is number of another relation.
participating entities in a relationship. Q. 2. A RDBMS must comply with at least rules.
Ans. True Ans. 6
Explanation: The number of attributes in a Explanation: An RDBMS product has to satisfy at least
relation is called the Degree of the relation. For six of the 12 rules of Cod to be accepted as a full-fledged
example, a relation with five attributes is a RDBMS.
relation of degree 5. Q. 3. Tuple is used to refer to a ………..
Q. 3. Database Schema is the relation of a database. Ans. row
Ans. False Explanation: Each row of data in a relation (table) is
Explanation: Database Schema is the design of called a tuple. In a table with n columns, a tuple is a
a database. It is the skeleton of the database relationship between the n related values.
that represents the structure(table names and Q. 4. The minimal set of super key is known as
their fields/columns), the type of data each Ans. Candidate key
column can hold, constraints on the data to be Explanation: A candidate key is a minimal super key or a
stored (if any), and the relationships among the super key with no redundant attribute. It is called a
tables. minimal super key because we select a candidate key
Q. 4. Each tuple in a relation is distinct. from a set of super keys such that the selected candidate
Ans. True key is the minimum attribute required to uniquely
Explanation: A relation is defined as a set of identify the table.
tuples. By definition all the elements of a set are Q. 5. proposed the relational model.
distinct; hence, all the tuples in a relation must Ans. E.F. Codd
also be distinct. This means that no two tuples Explanation: In 1970 Edgar F. Codd, at the IBM San Jose
can have the same combination of values for all Research Laboratory, proposed a new data
their attributes. representation framework called the relational data
Q. 5. A collection of raw facts and figure is called model which established the fundamentals of the
information. relational database model.
Ans. False
Explanation: A collection of raw facts and
figure is called data.
FILL IN THE BLANKS
Q. 1. is a non-key attribute, whose values
are derived from the primary key of some other
table.
Explanation: A relational database consists of a collection of tables.
All data values are atomic. No repeating groups are allowed.
CHAPTER 7 : STRUCTURED QUERY
LANGUAGE (SQL)

Objective Type Questions


STATE THE GIVEN STATEMENTS ARE TRUE OR with duplicate values The SELECT statement
FALSE when
Q. 1. SQL statements end with a semicolon (;). combined with DISTINCT clause, returns records without
Ans. True repetition (distinct records).
Explanation: A semicolon is a statement Q. 4. The How clause is used to retrieve data that meet some
terminator. This is purely used to identify specified conditions.
where a particular statement ends. Ans. False
Q. 2. ALTER TABLE command is a DDL (Data Explanation: The WHERE clause is used to retrieve data
Definition Language) statement. that meets some specified conditions.
Ans. True Q. 5. By default, WHERE displays records in ascending order
Explanation: ALTER TABLE command is a DDL of the specified column’s values.
(Data Definition Language) statement which is Ans. True
used to modify the table structure. Explanation: ORDER BY clause is used to display data in
Q. 3. The SELECT statement when combined with an ordered form with respect to a specified column. By
DISTINCT clause, returns records without default, ORDER BY displays records in ascending order of
repetition. the specified column’s values.
Ans. True FILL IN THE BLANKS
Explanation: By default, SQL shows all the data Q. 1. The is the most popular query language
used by major relational database management systems.
Ans. Structured Query Language (SQL) Q. 4. SQL provides a/an operator that can be
Explanation: SQL is easy to learn as the used with the WHERE clause to search for a specified
statements comprise of descriptive English pattern in a column.
words and are not case sensitive. We can create Ans. LIKE
and interact with a database using SQL easily. Explanation: The LIKE operator makes use of the
Q. 2. We can use the statement to see following two wild card characters:
the Tables. ● % (per cent): used to represent zero, one, or multiple
Ans. SHOW TABLES characters.
Explanation: SHOW has many forms that ● _ (underscore): used to represent exactly a single
provide information about databases, tables, character.
columns, or status information about the server. Q. 5. is an operation which is used to combine rows
Q. 3. statement is use to remove a from two or more tables based on one or more common
database or a table permanently from the fields between them.
system. Ans. Join
Ans. DROP Explanation: SQL JOINS are used to retrieve data from
Explanation: The DROP command in SQL is multiple tables. A SQL JOIN is performed whenever two
used to drop entities such as databases, tables, or more tables are listed in a SQL statement.
columns, indexes, constraints, etc.

Long Answer Type Questions-I


Q. 1. Consider a database with two tables STUDENTS and SPORTS as given below:
Table: STUDENTS
ADMNO NAME CLASS SEC RN ADDRES PHON
O S E
1211 MEEN 12A D 4 A-26 32456
A 78
1212 VANI 10A D 1 B-25 54567
89
1213 MEEN 12B A 1 NULL NULL
A
1214 KARIS 10B B 3 AB-234 45678
H 90
Table: SPORTS
ADMN GAME COACHNAME GRAD
O E
1215 CRICKET MR. RAVI A
1213 VOLLETYBAL MR. AMANDEEP B
L
1211 VOLLETYBAL MR. GOVARDHAN A
L
1212 BASKETBALL MR. TEWARI B
Write statements to: IS NOT NULL;
(i) Write the statement to delete a column (b) SELECT NAME, COACHNAME FROM
phone from the table students.
STUDENTS, SPORTS WHERE CLASS
(ii) Name the columns in both the tables that
LIKE “12%” AND STUDENTS.ADMNO
can be made primary keys.
= SPORTS. ADMNO;
(iii) Write statements to:
(a) Display name and game of those OR
students whose address is available OR
in students’ table.
(iii) Convert Statements Case WRITE STATEMENTS TO
(b) Display Name of the students who
(a) count the number of students who play
are studying in class 12 and their
corresponding Coach names (Only volleyball
For part (iii) Only) (b) Display name of all students of class 12 along
(iv) (a) SELECT NAME, GAME FROM with their coach names
STUDENTS, SPORTS Ans. (i) ALTER TABLE STUDENTS DROP PHONE;
WHERE STUDENTS. (ii) For the table Students primary key will be RNO and
ADMNO=SPORTS. ADMNO AND ADDRESS for the table sports primary key wll be ADMNO.
Long Answer Type Questions-II
Q. 1. A departmental store MyStore is considering to (iii) (a) INSERT INTO store (ItemNo, ItemName, Scode)
maintain their inventory using SQL to store the VALUES(2010, ”Note Book”, 25);
data. As a database administer, Abhay has (b) DROP TABLE store;
decided that:
OR
● Name of the database: mystore
(iii) (a) Describe Store.
● Name of table: STORE
(b) SELECT Itemname FROM STORE WHERE
● The attributes of STORE are as
quantity < 100;
follows: ItemNo: numeric
ItemName: character of size 20
Scode: numeric
Quantity: numeric
Table: STORE
Item Item Name Sco Quantity
No de
2005 Sharpener Classic 23 60

2003 Ball Pen 0.25 22 50

2002 Get Pen Premium 21 150

2006 Get Pen Classic 21 250

2001 Eraser Small 22 220

2004 Eraser Big 22 110

2009 Ball Pen 0.2 21 180

(i) Identify the attribute best suitable to be


declared as a primary key.
(ii) Write the degree and cardinality of the
table
STORE.
(iii) Write commands to:
(a) Insert the following data into the attributes
Item No, Item Name and SCode respectively in
the given table STORE Item No = 2010, Item
Name = “Note Book” and Scode = 25
(b) remove the table STORE from the database
MyStore.
OR (Options part iii only)
(iii) Write the query to
(a) Display the structure of the table STORE, i.e.,
name of the attributes and their respective
data types that he has used in the table.
(b) to display the name of all the items which have
quantity less than 100
Ans. (i) ItemNo
(ii) Degree = 4 Cardinality = 7
CHAPTER 8 : INTERFACE OF PYTHON
WITH SQL DATABASE

Objective Type Questions


STATE THE GIVEN STATEMENTS ARE TRUE OR that
FALSE
Explanation: MySQLdb is a legacy software that’s still
Q. 1. mysql. connector library is used to connect used in commercial applications. It’s written in C and is
python with MySQL. faster than MySQL Connector/Python but is available
Ans. True only for Python 2.
Explanation: To create a connection between FILL IN THE BLANKS
the MySQL database and Python, the connect() Q. 1. method retrieves the next row of a query
method of mysql. connector module is used. We result set and returns a single sequence, or None if no
pass the database details like Host Name, user more rows are available.
name, and the password in the method call, and
Ans. fetchone()
then the method returns the connection object.
Explanation: fetchone() method is used when you want
Q. 2. Database cursor is a special control structure
to select only the first row from the table.
facilitates the row-by- records in the result Q. 2.
row processing of sets. function returns the number of
rows affected by DML statements.
Ans. True Ans. cursor.rowcount()
Explanation: A cursor is an object which helps Explanation: This read-only property returns the
to execute the query and fetch the records from number of rows returned for SELECT statements, or the
the database. number of rows affected by DML statements.
A cursor keeps track of result Q. 3. There are
the position in the methods used for fetching the
set, and allows you to perform multiple records from a database within python.
operations row by row against a result set, with Ans. three
or without returning to the original table. Explanation: The three methods used for fetching are as
Q. 3. cursor.execute(query,rows) is used to insert or follows:
update multiple rows using a single query. ● fetchall(): returns all the records from the query
Ans. False resultset as a tuple.
Explanation: Function cursor. executemany ● fetchone(): returns one record from the query
(query,rows) is used to insert or update resultset.
multiple rows using a single query. ● fetchmany(n): returns ‘n’ records from the query
Q. 4. resultset is the logical set of records that are resultset.
fetched from the database when SQL query Q. 4. To save your changes to the database, you must
executed.
Ans. True the transaction.
Explanation: A ResultSet object is a table of
Ans. commit
data representing a database result set, which is
Explanation: This method sends a COMMIT statement to
usually generated by executing a statement that the MySQL server, committing the current transaction.
queries the database. Since, by default Connector/ Python does not auto
Q. 5. MySQLdb is an interface for connecting to a commit, it is important to call this method after every
MySQL database servers from Python. transaction that modifies data for tables that use
Ans. True transactional storage engines.
Q. 5. is used to get the row-id of the last modified row.
Ans. lastrowid()

Long Answer Type Questions

Q. 1. Consider the table Teacher in which Tina wants to add two rows. For this, she wrote a
program in which some code is missing.
Write the following missing statements to complete the code:
(i) Which function will be filled in the blank at statement 2?
(ii) What should be come in the blank at the statement 1?
(iii) Which function will be filled in the blank at statement 3?
import mysql.connector mycon=mysql.connector.connect(host=”l
ocalhost”,User=”root”, passwd=”system”
,database=”test”)
cursor=con.cursor()
sql=”INSERT Teacher(T_Id,Fname,Lname, Hire_date, Salary,
Subject)
VALUSE (%s, %s, %s, %s, %s,%s)”,
#statement Line1
val =[(101, ‘Vibha’, ‘Bajpai’, ’12-
10-2021’, 27000, ‘Python’), (104,
‘Rekha’,‘Sharma’, ’01-01-2022’, 27000,
‘Math’)]
try:
cursor.executemany(sql,val)
mycon. () #Line statement2
except:
mycon.rollback() #statement3
Ans. (i) commit
(ii) INTO
(iii) mycon.close()
Explanation: To get and print the ID of the last inserted row, lastrowid is used. This is a special
keyword which is used to get the ID of the last inserted row.

You might also like