0% found this document useful (0 votes)
109 views54 pages

Xii Comp

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

Xii Comp

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

QUESTION BANK

DAV INSTITUTIONS, WEST BENGAL ZONE


SESSION: 2024-2025
CLASS -XII
TOPIC: REVISION TOUR
A. MCQ Type Select the most appropriate from the following:
1 Given the following dictionaries
dict_student = {"rno" : "53", "name" : 'Rajveer Singh'}
dict_marks = {"Accts" : 87, "English" : 65}
Which statement will append the contents of dict_marks in dict_student?
a. dict_student + dict_marks
b. dict_student.add(dict_marks)
c. dict_student.merge(dict_marks)
d. dict_student.update(dict_marks)
2 Match the columns: if
>>l=list(‘computer’)
Column A Column B
1 L[1:4] a. [‘t’,’e’,’r’]
2 L[3:] b. [‘o’,’m’,’p’]
3 L[-3:] c. [‘c’,’o’,’m’,’p’,’u’,’t’]
4 L[:-2] d. [‘p’,’u’,’t’,’e’,’r’]

a) 1-b,2-d,3-a,4-c b) 1-c,2-b,3-a,4-d c) 1-b,2-d,3-c,4-a d) 1-d,2-a,3-c,4-b

3 Which of the following statements are not correct:


i) An element in a dictionary is a combination of key-value pair
ii) A tuple is a mutable data type
iii) We can repeat a key in dictionary
iv) clear( ) function is used to deleted the dictionary.

a) i,ii,iii b) ii,iii,iv c) ii,iii,i d) i,ii,iii,iv


4 Which of the following statements are correct:
i) Lists can be used as keys in a dictionary
ii) A tuple cannot store list as an element
iii) We can use extend() function with tuple.
iv) We cannot delete a dictionary once created.

a) i,ii,iii b) ii,iii,iv c) ii,iii,I d) None of these


5 Match the output with the statement given in column A with Column B.
Column A Column B
>>>tuple([10,20,30]) a. >>> (10,20,30)
>>>(“Tea”,)* 3 b. >>> 2
>>>tuple(“Item”) c. >>> (‘Tea’, ‘Tea’, ‘Tea’)
>>>print(len(tuple([1,2]))) d. >>> (‘I’, ‘t’, ‘e’, ‘m’)
a) 1-b,2-c,3-d,4-a b) 1-a,2-c,3-d,4-b c) 1-c,2-d,3-a,4-a d) 1-d,2-a,3-b,4-c

6 Find the output of the following code snippet:-


x = 50
def func():
global x
print('x is', x)
x=2
print('Changed global x to', x)
func()
print('Value of x is', x)

a) x is 50
Changed global x to 2
Value of x is 50
b) x is 50
Changed global x to 2
Value of x is 2
c) x is 50
Changed global x to 50
Value of x is 50
d) None of the mentioned

B ASSERTION & REASON TYPE QUESTION. Choose the correct option.


A. Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
B. Both Assertion and Reason are true and Reason is not the correct explanation of Assertion.
C. Assertion is true but Reason is false.
D. Both Assertion and Reason are false.
7 Assertion. Assigning a new value to an int variable creates a new variable internally.
Reason. The int type is immutable data type of Python.
8 Assertion. """A Sample Python String""" is a valid Python String.
Reason. Triple Quotation marks are not valid in Python.
9 Assertion. If and For are legal statements in Python.
Reason. Python is case sensitive and its basic selection and looping statements are in lower
case.
10 Assertion. The break statement can be used with all selection and iteration statements.
Reason. Using break with an if statement is of no use unless the if statement is part of a
looping construct.
11 Assertion. The break statement can be used with all selection and iteration statements.
Reason. Using break with an if statement will give no error.
12 Assertion. Dictionaries are mutable, hence its keys can be easily changed.
Reason. Mutability means a value can be changed to create new storage for the changed value
13 Assertion: The get() method in Python dictionaries returns None if the specified key is not
found.
Reason: Python dictionaries raise a KeyError if the specified key is not found during retrieval.
14 Assertion: The update() method in Python dictionaries replaces the existing values with new
values for the specified keys.
Reason: The update() method modifies the dictionary in place by adding items from another
dictionary.
15 Assertion: The popitem() method in Python dictionaries returns and removes the last inserted
key-value pair.
Reason: Python dictionaries maintain the insertion order of elements.
16 Assertion: Dictionaries in Python can have duplicate keys.
Reason: Python dictionaries allow for dynamic resizing, enabling the storage of duplicate
keys.
17 Predict the output of the following code fragments:
T = True
x=100
while T :
print (x)
x = x - 10
if x < 50 :
T = False
C APPLICATION BASED QUESTIONS

18 Fill in the missing lines of code in the following code. The code reads in a limit amount and a
list of prices and prints the largest price that is less than the limit. You can assume that all
prices and the limit are positive numbers. When a price 0 is entered the program terminates
and prints the largest price that is less than the limit.

#Read the limit


limit = float(input("Enter the limit"))
max_price = 0
# Read the next price
next_price = float(input("Enter a price or 0 to stop:"))
while next_price > 0 :
<write your code here>
#Read the next price
<write your code here>
if max_price > 0:
<write your code here>
else :
<write your code here>
19 Write a program that asks the user the day number in a year in the range 2 to 365 and asks the
first day of the year — Sunday or Monday or Tuesday etc. Then the program should display
the day on the day-number that has been input.

20 Write a program that reads a date as an integer in the format MMDDYYYY. The program will
call a function that prints print out the date in the format <Month Name> <day>, <year>.

Enter date : 12252019


December 25, 2019
21 Write a program that should prompt the user to type some sentence(s) followed by "enter". It
should then print the original sentence(s) and the following statistics relating to the
sentence(s):

Number of words
Number of characters (including white-space and punctuation)
Percentage of characters that are alpha numeric
Hints: Assume any consecutive sequence of non-blank characters in a word.
22 Write a program that rotates the elements of a list so that the element at the first index moves
to the second index, the element in the second index moves to the third index, etc., and the
element in the last index moves to the first index.

Enter the list: [8, 10, 13, 25, 7, 11]


Original List: [8, 10, 13, 25, 7, 11]
Rotated List: [11, 8, 10, 13, 25, 7]
23 Create a dictionary whose keys are month names and whose values are the number of days in
the corresponding months.
(a) Ask the user to enter a month name and use the dictionary to tell them how many days are
in the month.
(b) Print out all of the keys in alphabetical order.
(c) Print out all of the months with 31 days.
(d) Print out the (key-value) pairs sorted by the number of days in each month.
24 Write a function called addDict(dict1, dict2) which computes the union of two dictionaries. It
should return a new dictionary, with all the items in both its arguments (assumed to be
dictionaries). If the same key appears in both arguments, feel free to pick a value from either.

D Short answer type question


25 Rewrite the following code is Python after removing all syntax errors(s).
Underline each correction done in the code.
for Name in [Ramesh, Suraj, Priya]
if Name [0] = ‘S’:
Print (Name)

Answer:
for Name in [“_Ramesh_”, “_Suraj_” , “_Priya_”]
if Name [0] =_=‘S’ :
print (Name)
26 What do you understand by mutability ? What does "in place" task mean ?
27 Start with the list [8, 9, 10]. Do the following using list functions:
1. Set the second entry (index 1) to 17
2. Add 4, 5 and 6 to the end of the list
3. Remove the first entry from the list
4. Sort the list
5. Double the list
6. Insert 25 at index 3
28 What are the two ways to remove something from a list? How are they different ?

29 In the Python shell, do the following :Define a variable named states that is an empty list.

1. Add 'Delhi' to the list.


2. Now add 'Punjab' to the end of the list.
3. Define a variable states2 that is initialized with 'Rajasthan', 'Gujarat', and 'Kerala'.
4. Add 'Odisha' to the beginning of the list states2.
5. Add 'Tripura' so that it is the third state in the list states2.
6. Add 'Haryana' to the list states2 so that it appears before 'Gujarat'. Do this as if you DO
NOT KNOW where 'Gujarat' is in the list. Hint. See what states2.index("Rajasthan")
does. What can you conclude about what listname.index(item) does ?
7. Remove the 5th state from the list states2 and print that state's name.
30 If a is (1, 2, 3)
1. what is the difference (if any) between a * 3 and (a, a, a) ?
2. Is a * 3 equivalent to a + a + a ?
3. what is the meaning of a[1:1] ?
4. what is the difference between a[1:2] and a[1:1] ?
31 Why is a dictionary termed as an unordered collection of objects?
32 What type of objects can be used as keys in dictionaries?

33 Though tuples are immutable type, yet they cannot always be used as keys in a dictionary. What
is the condition to use tuples as a key in a dictionary?
34 Dictionary is a mutable type, which means you can modify its contents? What all is modifiable
in a dictionary? Can you modify the keys of a dictionary?
35 Write a function, lenWords(STRING), that takes a string as an argument and returns a tuple
containing length of each word of a string. For example, if the string is "Come let us have some
fun", the tuple will have (4, 3, 2, 4, 4, 3)
36 Write a function countNow(PLACES) in Python, that takes the dictionary, PLACES as an
argument and displays the names (in uppercase)of the places whose names are longer than 5
characters. For example, Consider the following dictionary
PLACES={1:"Delhi",2:"London",3:"Paris",4:"New York",5:"Doha"} The output should be:
LONDON NEW YORK
37 What do you understand by local and global scope of variables? How can you access a global
variable inside the function, if function has a variable with same name

****
TOPIC: FUNCTIONS IN PYTHON
1 Function name must be followed by
2 keyword is used to define a function
3 Function will perform its action only when it is
4 Write statement to call the function.
def Add():
X=10+20
print(X)
#statement to call the above function
5 Write statement to call the function.
def Add(X,Y):
Z=X+Y
print(Z)
#statement to call the above function
6 Write statement to call the function.

def Add(X,Y):
Z=X+Y
return Z
#statement to call the above function
print(“Total =”,C)
7 Which Line Number Code will never execute?
def Check(num): #Line1
if num%2==0: #Line2
print("Hello") #Line 3
return True #Line4
print("Bye") #Line5
else: #Line6
return False #Line7
C = Check(20)
print(C)
8 What will be the output of following code?
def Cube(n):
print(n*n*n)

Cube(n) # n is 10 here
print(Cube(n))
9 What are the different types of actual arguments in function? Give example of any
one of them.
10 What will be the output of following code:
def Alter(x, y = 10, z=20):
sum=x+y+z
print(sum)
Alter(10,20,30)
Alter(20,30)
Alter(100)
11 Call the given function using KEYWORD ARGUMENT with values 100 and 200
def Swap(num1,num2):
num1,num2=num2,num1
print(num1,num2)

Swap( , )
12 Which line number of code(s) will not work and why?
def Interest(P,R,T=7):I
= (P*R*T)/100
print(I)

Interest(20000,.08,15) #Line1
Interest(T=10,20000,.075) #Line2
Interest(50000,.07) #Line3
Interest(P=10000,R=.06,Time=8) #Line4
Interest(80000,T=10) #Line5
13 What will be the output of following code?
def Calculate(A,B,C):
return A*2,B*2,C*2
val = Calculate(10,12,14)
print(type(val))
print(val)
14 What are Local Variable and Global Variables? Illustrate with example
15 What will be the output of following code?
def check():
num=50
print(num)
num=100
print(num)
check()
print(num)
16 What will be the output of following code?
def check():
global num
num=1000
print(num)
num=100
print(num)
check()
print(num)

17 Function can alter only Mutable data types?(True/False)


18 A Function can call another function or itself?(True/False)
19 What will be the output of following code?
def display(s):
l = len(s)
m=""
for I in range(0,l):
if s[i].isupper():
m=m+s[i].lower()
elif s[i].isalpha():
m=m+s[i].upper()
elif s[i].isdigit():
m=m+"$"
else:
m=m+"*"
print(m)
display("[email protected]")
20 What will be the output of following code?
def Alter(M,N=50):
M=M+N
N=M-N
print(M,"@",N)
return M
A=200
B=100
A = Alter(A,B)
print(A,"#",B) B =
Alter(B) print(A,‟@‟,B)
21 What will be the output of following code?
def Total(Number=10):
Sum=0
for C in range(1,Number+1):
if C%2==0:
continue
Sum+=C
return Sum
print(Total(4))
print(Total(7))
print(Total())
22 What will be the output of following code?
X=100
def Change(P=10,Q=25):
global X
ifP%6==0:
X+=100
else:
X+=50
Sum=P+Q+X
print(P, '#', Q, '$', Sum)
Change()
Change(18,50)
Change(30,100)
23 What will be the output of following code?
def drawline(char='$',time=5):
print(char*time)
drawline()
drawline('@',10)
drawline(65)
drawline(chr(65))
24 What will be the output of following code?
def Updater(A,B=5):
A=A//B
B=A%B
print(A,'$',B)
return A+B
A=100
B=30
A = Updater(A,B)
print(A,'#',B)
B=Updater(B)
print(A,'#',B)
A=Updater(A)
print(A,'$',B)
25 What will be the output of following code?
def Fun1(mylist):
for i in range(len(mylist)):
if mylist[i]%2==0:
mylist[i]/=2
else:
mylist[i]*=2

list1=[21,20,6,7,9,18,100,50,13]
Fun1(list1)
print(list1)
26 Write a Python function that takes a number as a parameter and checks whether the number is prime or not.
Note : A prime number (or a prime) is a natural number greater than 1 and that has no positive divisors other than 1 and
itself.
27 Write a python function showlarge() that accepts a string as parameter and prints the words whose length is
more than 4 characters.
Eg: if the given string is “My life is for serving my Country” The output should be
serving
Country
28 Write a function OCCURRENCE() to count occurrence of a character in any given string. here function take
string and character as parameters.
29 Write definition of a method/function AddOddEven(VALUES) to display sum of odd and even values
separately from the list of VALUES.
For example : If the VALUES contain [15, 26, 37, 10, 22, 13] The function should display Even Sum: 58 Odd
Sum: 65
30 Write a Python function that takes a list and returns a new list with distinct elements from the first list.
Sample List : [1,2,3,3,3,3,4,5]
Unique List : [1, 2, 3, 4, 5]
TOPIC: EXCEPTION HANDLING
Q1. The error occurs when rules of programming language are misused is called as:
a. Semantics Error b. 2. Logical Error
c. Syntax error d. Runtime Error
Q2. What is the purpose of the try block in Python error handling?
a) To define the block of code where an exception may occur
b) To catch and handle exceptions that occur within the block
c) To ensure that the code executes without any errors
d) To terminate the program if an exception occurs
Q3. Which keyword is used to catch exceptions in Python?
a) try b) catch c) except d) handle
Q4. Which of the following is NOT a standard Python exception?
a) KeyError b) SyntaxError c) IndexError d) TypeError
Q5. How can you handle multiple exceptions in a single except block?
a) Separate the exceptions using commas
b) Use nested except blocks
c) Use the except keyword only once
d) It is not possible to handle multiple exceptions in a single except block
Q6. What does the finally block in Python error handling ensure?
a) It ensures the program will terminate if an exception occurs.
b) It ensures the code within it will always execute, regardless of whether an exception occurs
or not.
c) It ensures that the program will skip executing the code if an exception occurs.
d) It ensures that only the code within the finally block will execute if an exception occurs.
Q7. Which of the following is true about the else block in Python error handling?
a) It is executed if an exception occurs.
b) It handles exceptions occurring in the try block.
c) It is executed if no exception occurs in the try block.
d) It is executed instead of the finally block.
Q8. What is the purpose of the assert statement in Python?
a) To handle exceptions b) To terminate the program
c) To check if a condition is true d) To raise an exception
Q9. Which of the following statements is true about the except clause in Python?
a) It is mandatory in a try-except block. b) It catches all exceptions by default.
c) It must be placed before the try block. d) It can specify the type of exceptions to catch.
Q10. Choose the correct output of the following.
try:
x = 10 / 0
except ZeroDivisionError:
print("Division by zero")
finally:
print("Finally block")
a) Division by zero b) Finally block
Finally block
c) Division by zero d) ZeroDivisionError
Q11. What does the following Python code do?
try:
# Some code that may raise an exception
except:
pass
a) It raises an exception. b) It catches all exceptions and ignores them.
c) It terminates the program. d) It handles exceptions gracefully.
Q12. Choose the correct statement.
Statement-1: An exception is a Python object that represents an error.
Statement-2: Even if a statement or expression is syntactically correct, there might arise an error
during its execution.
a. Both Statement I and Statement II are true
b. Both Statement I and Statement II are false
c. Statement I is true but Statement II is false
d. Statement I is false but Statement II is true
Q13. Choose the correct statement.
Statement-1: Exception needs to be handled by the programmer so that the program does not
terminate abnormally.
Statement-2: Exception does not disrupt the normal execution of the program.
a. Both Statement I and Statement II are true
b. Both Statement I and Statement II are false
c. Statement I is true but Statement II is false
d. Statement I is false but Statement II is true
Q14. Choose the correct statement.
Statement-1: throws keyword is used to throw an exception from a block.
Statement-2: Built-in exceptions are defined in the Python compiler/interpreter.
a. Both Statement I and Statement II are true
b. Both Statement I and Statement II are false
c. Statement I is true but Statement II is false
d. Statement I is false but Statement II is true
Q15. Match the following with correct explanation of different types of errors in python
1. occur after the code has been compiled and the program is running. The
a) Syntax error error of this type will cause your program to behave unexpectedly or even
crash.
2. indicate that there is something wrong with the syntax of the program or
b) Logical errors rules for programming language are misused.

3. occur due to our mistakes in programming logic. Program compiles and


c) Runtime errors executes but doesn't give the desired output

4. is raised specifically when you try to use a variable or a function name


d) NameError that is not valid.

Choose the correct option: -


a. a-1, b-2, c-4, d-3 b. a-2, b-3, c-1, d-4
c. a-3, b-1, c-2, d-4 d. a-4, b-1, c-3, d-2
TOPIC:- STACK
Assertion and Reasoning Questions
A. Both Assertion (A) and Reason (R) are true and Reason (R) is the correct explanation of Assertion
(A)
B. Both Assertion (A) and Reason (R) are true and Reason (R) is not the correct explanation of
Assertion (A)
C. Assertion (A) is true and Reason (R) is false
D. Assertion (A) is false and Reason (R) is true
1. Assertion (A): Stacks are also known as Last-In –First-Out (LIFO) data structures.
Reasoning (R): The item that is added last to the stack is the first item to be removed
from the stack.
2. Assertion (A): A Stack can only be accessed from one end.
Reasoning (R): This property of stack is known as its linear nature.
3. Assertion (A): The push operation in a stack adds an item to the top of the stack.
Reasoning (R): The pop operation in a stack removes an item from the bottom of the
stack.
4. Assertion (A): The peek operation in a stack returns the value of the topmost item in the
stack without removing it.
Reasoning (R): This operation is also known as pop operation.
5. Assertion (A): Stacks are used in the implementation of recursion.
Reasoning (R): When a function calls itself, it create a new stack frame.
6. What is the name of the error that occurs when you try to pop an item from an empty
stack?
A StackOverflowError
b) IndexError
c) ArrayIndexOutofBoundsException
d) NullPointerException
7. Assume a stack STK implemented as a list. Predict the output of the following code.

def push_char(ch):
STK.append(ch)
def display_STK():
strdata=""
if len(STK)==0:
print("Empty Stack")
else:
for i in STK:
strdata+=i
print(strdata[::-1])
def pop_char():
if STK!=[]:
item=STK.pop()
else:
pass
STK=[ ]
push_char('D')
push_char('A')
push_char('V')
push_char('M')
pop_char()
push_char('O')
push_char('D')
pop_char()
pop_char()
push_char('E')
push_char('L')
pop_char()
display_STK()

A. VAD
B. ODEL
C. LEDO
D. EVAD
8. Which of the following condition is necessary for fixed size stack for checking a stack st
is full in Python?
A. Top ==len(st)
B. Top ==len(st)-1
C. Top < len(st)
D. Top ==st
9. Which of the following is not an inherent application of stack?
A. Implementation of recursion
B. Evaluation of postfix expression
C. Job scheduling
D. Reversing a string

10. Choose the correct output for the following sequence of stack operations. push (5), push
(8), pop, push (2), push (5), pop, push (1)
A. 2551
B. 85251
C. 85521
D. 521
11. Consider a string strnew and write the following user defined functions in python to
perform the specified operations on the fixed size stack ‘vow’ (maximum element
accommodate by stack is 5)
i) Push_add(strnew): It takes the string as an argument and pushes only vowels
to the stack vow. If stack is full then it will print the message “Stack is Full,
no more element will be added to the stack” while trying to add element on
to the stack.
ii) Pop_item( ):- It remove the element and displays them. Also, the function
should display “Stack is Empty” when there are no elements in the stack.
12. Write a menu driven program to perform all the stack operation. Each operation will be
implemented with help of user defined function. The structure of the stack are as
follows:-
[ [ “Name of the student1”, totalmark1”], [ “Name of the student2”, totalmark2”]]
Different operation of stack are as follows:-
1) Push( ):- Add an element on to the stack.
2) Pop( ):- Remove an element from the stack.
3) Peek( ) :- Display current top element of the Stack.
4) Display( ) : Display all elements in top to bottom arrangement.
13. A list named datalist contains the following information:
Name of Employee
City
Phone number of Employee
in following manner
[[Name of Employee, City, Phone number of Employee]]

Write the following methods to perform given operations on the stack “status”:
Push_element (datalist) To Push an object containing Name of the Employee, city,
Phone no of the employee of those employee whose city is either “kolkata” or “new
delhi” into the stack.
Pop_element () To Pop an object from the stack and to release the memory.
14. Consider a dictionary which consists of key as “Admno” and value as Name, Class,
Markpercent, of 45 students in the following way-
data={“Admno”:[“Name”,”Class”,”Markpercent”]}
Write the following user defined function to perform push and pop operation on the
stack “Topers” respectively.
i) Push_top(data) accepts data dictionary as an argument and add only name of the
students on to the stack whose mark is more than 90% .
ii) Pop_element( ) to remove and display all the element from the stack and the
function should display “Stack is empty” if there is no element on to the stack.
Read the text carefully and answer the questions:
Millions of computer science students have taken a course on algorithms and data
structures, typically the second course after the initial one introducing programming.
One of the basic data structures in such a course is the stack. The stack has a special
place in the emergence of computing as a science, as argued by Michael Mahoney, the
pioneer of the history of the theory of computing. The stack can be used in many
computer applications, few are given below:
In recursive function When function is called.
Expression conversion such as - Infix to Postfix, Infix to Prefix, Postfix to Infix, Prefix
to Infix.
In stack, insertion operation is known as Push whereas deletion operation is known as
Pop.
Code 1
def push (Country, N):
Country.insert(len(Country),N) # Statement 1
# Function Calling
Country=[ ]
C=['Indian', 'USA', 'UK', 'Canada', 'Sri Lanka']
for i in range (0, len(C), 2): # Statement 2
push (Country, C[i])
print (Country)
# Output
#['Indian', 'UK', 'Sri Lanka']

def pop (Country):


if Country==[ ]: # Statement 3
return "Underflow"
else:
return Country.pop() #Statement4

for i in range (len (Country) + 1):


print (pop(Country)) #Statement 5
Output
Sri Lanka
UK
Indian
Underflow
15. Identify the suitable code for the blank of Statement 1.
A. .append(len(Country),N)
B. .append()
C. .extend()
D. .insert()
16. Fill the Statement 2, to insert the alternate element from Country list.
A. 3
B. 2
C. -1
D. 0
17. Fill the Statement 3, to check the stack is empty.
A. len(Country)==0
B. Country.is Empty()==0
C. Country=[]
D. Country.is Empty()

18. Fill the Statement 4, to delete an element from the stack.


A. pop(1)
B. del country[1]
C. pop()
D. Country.delete(1)
19. Fill the Statement 5, to call the pop function.
A. pop(Country)
B. pop(C)
C. call pop(Country)
D. def pop(Country)
20 Given a Dictionary Studata containing marks of students for three test-series in the form
Stu_ID:(TS1, TS2, TS3) as key-value pairs.
Write a Python program with the following user-defined functions to perform the
specified operations on a stack named StuStk
(i) Push_elements(StuStk, Studata) : It allows pushing IDs of those students, from the
dictionary Studata into the stack StuStk, who have scored more than or equal to 80
marks in the TS3 Test without using append( ) and extend () function of list.
(ii) Pop_elements(StuStk): It removes all elements present inside the stack in LIFO order
and prints them. Also, the function displays 'Stack Empty' when there are no elements in
the stack. Without using pop( ) function of list.
Call both functions to execute queries.
For example:
If the dictionary Stu_dict contains the following data:
Studata ={5:(87,68,89), 10:(57,54,61), 12:(71,67,90), 14:(66,81,80), 18:(80,48,91)}
After executing Push_elements(), StuStk should contain
[5,12,14,18]
After executing Pop_elements(), The output should be:
18
14
12
5
Stack Empty
TOPIC : DATA FILE HANDLING
MCQ
1. Which of the following functions changes the position of file pointer and returns its new position? 1
a. flush() b. tell() c. seek() d. offset()
2. Which pickle module method is used to write a Python object to a binary file? 1
a. save() b. serialize() c. store() d. dump()
3. Which of the following file opening mode in Python, generates an error if the file does not exist? 1
a. a b. r c. w d. w+
4. The correct syntax of seek() is: 1
a. file_object.seek(offset [, reference_point])
b. seek(offset [, reference_point])
c. seek(offset, file_object)
d. seek.file_object(offset)
5. Assertion (A): A binary file in python is used to store collection objects like lists and dictionaries 1
that can be later retrieved in their original form using pickle module.
Reasoning (A): Binary files are just like normal text files and can be read using a text editor like
Notepad.
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True
6. Which of the following is not a correct statement for binary files? 1
a) Easy for carrying data into buffer
b) Much faster than other file systems
c) Characters translation is not required
d) Every line ends with new line character “\n”
7. To read three characters from a file object f, we use________ 1
a) f.read(3) b) f.read() c) f.readline() d) f.readlines()
8. In which file, no delimiters are used for line and no translation occur? 1
a) text file b) binary file c) csv file d) general file
9. Consider the code given below: 1
fh=open("poem.txt","r")
fh.read(25)
Now the file-pointer needs to be placed at 20th byte.
Which statement will change the position of the file pointer?
a. fh.seek(20,2) b. fh.seek(20,0) c. fh.seek(20,1) d. fh.seek(-5)
10. Assertion (A): If a file is opened in binary mode its contents are viewed as a 1
sequence of bytes.
Reason (R): A text file also can be opened in binary mode.
a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True
Programming
11. Read the code given below. 2
Fh=open(“Main.txt”, “w”)
Fh.write(“Bye”)
Fh.close()
If the file contains “Good” before execution, what will be the contents of the file after execution of
this code? State the reason for the output also.
12. Write a function in Python to count the number of lines stored in a text file ‘Story.txt’ which start 2
with letter ‘A’ or ‘a’. (Consider the file contains data in multiple lines)
13. Write a function in Python, which reads a file “data.txt” and copies its contents to another file 3
“info.txt”. While copying, replace all full stops with commas.
14. Write a function display() in Python which reads the integer elements from the previously created 3
binary file ‘Number.dat’. Display only those numbers which are either divisible by 7 or ends with
digit 7.
15. A binary file ‘record.dat’ with Admission number, students name and fees. Assume that there are 3
10 records in the file.
Write a function update(adno) to accept admission number to update the fees of a student.
The function should also copy all the records in another binary file ‘temp.dat’.
The above file has the following structure:
["Adno","Name","Fees"]
16. Consider a binary file “EMP.DAT” contains a dictionary having multiple elements. Each element 3
is in the form EID:[ENAME,DEPT] as key:value pair where
EID – Employee Number
ENAME – Employee Name
DEPT– Department
Write a user-defined function search(dept), that accepts department as parameter and displays all
those records from the binary file EMP.DAT.
import pickle
def search(dept)
with open('EMP.DAT','rb') as file:
while True:
try:
emprec=pickle.load(file)
for r in emprec:
dep=emprec[r][2]
if dep==dept:
print(r, emprec[r])
except EOFError:
break
17. Write a function in Python to read a text file, Alpha.txt and displays those lines which begin with 3
the word ‘You’.
18. Write a function, vowelCount() in Python that counts and displays the number of vowels in the 3
text file named Poem.txt.
19. Consider a file, SPORT.DAT, containing records of the following structure: [SportName, 3
TeamName, No_Players] Write a function, copyData(), that reads contents from the file
SPORT.DAT and copies the records with Sport name as “Basket Ball” to the file named
BASKET.DAT. The function should return the total number of records copied to the file
BASKET.DAT.
20. Create a function maxsalary() in Python to read all the records from an already existing file 4
record.csv which stores the records of various employees working in a department. Data is stored
under various fields as shown below:
E_code E_name Scale Salary
A01 Bijesh Mehra S4 65400
B02 Vikram Goel S3 60000
C09 Suraj Mehta S2 45300
…… …… …… ……
Function should display the row where the salary is maximum.
Note: Assume that all employees have distinct salary.
21. Consider a binary file 'INVENTORY.DAT' that stores information about products using tuple with 4
the structure (ProductID, ProductName, Quantity, Price).
Write a Python function expensiveProducts() to read the contents of 'INVENTORY.DAT' and
display details of products with a price higher than Rs. 1000.
Additionally, calculate and display the total count of such expensive products.
For example: If the file stores the following data in binary format
(1, 'ABC', 100, 5000)
(2, 'DEF', 250, 1000)
(3, 'GHI', 300, 2000)
then the function should display
Product ID: 1 Product ID: 3 Total expensive products: 2
22. Pravesh is a Python programmer working in a school. For the Annual Sports Event, he has created 4
a csv file named Result.csv, to store the results of students in different sports events.
The structure of Result.csv is : [St_Id, St_Name, Game_Name, Result]
Where St_Id is Student ID (integer) ST_name is Student Name (string) Game_Name is name of
game in which student is participating(string) Result is result of the game whose value can be
either 'Won', 'Lost' or 'Tie'
For efficiently maintaining data of the event, Vedansh wants to write the following user defined
functions:
Accept() – to accept a record from the user and add it to the file Result.csv. The column headings
should also be added on top of the csv file.
wonCount() – to count the number of students who have won any event. As a Python expert, help
him complete the task.
Case Based Questions.
23. Birendra, a student of class 12th, is learning CSV File Module in Python. During examination, he
has been assigned an incomplete python code (shown below) to create a CSV File 'Student.csv'
(content shown below). Help him in completing the code which creates the desired CSV File.
CSV File
1,AKSHAY,XII,A
2,ABHISHEK,XII,A
3,ARVIND,XII,A
4,RAVI,XII,A
5,ASHISH,XII,A
Incomplete Code
import_____ #Statement-1
fh = open(_____, _____, newline='') #Statement-2
stuwriter = csv._____ #Statement-3
data = []
header = ['ROLL_NO', 'NAME', 'CLASS', 'SECTION']
data.append(header)
for i in range(5):
roll_no = int(input("Enter Roll Number : "))
name = input("Enter Name : ")
Class = input("Enter Class : ")
section = input("Enter Section : ")
rec = [_____] #Statement-4
data.append(rec)
stuwriter. _____ (data) #Statement-5
fh.close()

Answer the questions from the below mentioned questions.


i. Identify the suitable code for blank space in line marked as Statement-1. 1
a) csv file b) CSV c) csv d) Csv
ii. Identify the missing code for blank space in line marked as Statement-2? 1
a) "School.csv","w" b) "Student.csv","w"
c) "Student.csv","r" d) "School.csv","r"
iii. Choose the function name (with argument) that should be used in the blank space of line marked as 1
Statement-3
a) reader(fh) b) reader(MyFile)
c) writer(fh) d) writer(MyFile)
iv. Identify the suitable code for blank space in line marked as Statement-4. 1
a) 'ROLL_NO', 'NAME', 'CLASS', 'SECTION' b) ROLL_NO, NAME, CLASS, SECTION
c) 'roll_no','name','Class','section' d) roll_no,name,Class,section c) co.connect()
v. Choose the function name that should be used in the blank space of line marked as Statement-5 to 1
create the desired CSV File?
a) dump() b) load()
c) writerows() d) writerow()
24. Birupakshya 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.
He has succeeded in writing partial code and has missed out certain statements, so he has left certain
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.
Answer the questions from the below mentioned questions.
import pickle
def AddStudents():
____________ #1 statement to open the binary file to write data
while True:
Rno = int(input("Rno :"))
Name = input("Name : ")
Percent = float(input("Percent :"))
L = [Rno, Name, Percent] ____________ #2 statement to write the list L into the file
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: ____________ #3 statement to read from the file
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")
average=Total/Countrec
print("average percent of class = ",average)
AddStudents()
GetStudents()
i. Which of the following commands is used to open the file “STUDENT.DAT” for writing only in 1
binary format? (marked as #1 in the Python code)
a. F= open("STUDENT.DAT",'wb') b. F= open("STUDENT.DAT",'w')
c. F= open("STUDENT.DAT",'wb+') d. F= open("STUDENT.DAT",'w+')
ii. Which of the following commands is used to write the list L into the binary file, STUDENT.DAT? 1
(marked as #2 in the Python code)
a. pickle.write(L,f) b. pickle.write(f, L)
c. pickle.dump(L,F) d. f=pickle.dump(L)
iii. Which of the following commands is used to read each record from the binary file 1
STUDENT.DAT? (marked as #3 in the Python code)
a. R = pickle.load(F) b. pickle.read(r,f)
c. r= pickle.read(f) d. pickle.load(r,f)
iv. Which of the following statement(s) are correct regarding the file access modes? 1
a. ‘r+’ opens a file for both reading and writing. File object points to its beginning.
b. ‘w+’ opens a file for both writing and reading. Adds at the end of the existing file if it exists and
creates a new one if it does not exist.
c. ‘wb’ opens a file for reading and writing in binary format. Overwrites the file if it exists and
creates a new one if it does not exist.
d. ‘a’ opens a file for appending. The file pointer is at the start of the file if the file exists.
v. Which of the following statements correctly explain the function of seek() method? 1
a. tells the current position within the file.
b. determines if you can move the file position or not.
c. indicates that the next read or write occurs from that position in a file.
d. moves the current file position to a given specified position
******************
TOPIC: DATABASE MANAGEMENT SYSTEM
1. Based on which unique key, the records of a table are identified?
a)Candidate key b) Foreign key
c) Alternate key d) Primary key
2. Which of the following is not a type of relationship in a RDBMS?
a)One-to-One b)Tuples-to-Tuples
c)One-to-Many d) Many-to-many
3. Repetition of data is called data _______________
a) Dependance b)Redundancy
c)Inconsistency d)Isolation
4. Number of attributes in a relation is called____________.
a)size b)degree c)cardinality d)weight
5. The term __________ is used to refer to a row.
a)Attribute b)Tuple c)Field d)Instance
Assertion (A) and Reasoning (R) based questions.
Mark the correct choice as
a) Both ( A ) and ( R ) are the correct and R is the correct explanation for ( A ).
b) Both ( A ) and ( R ) are true and ( R ) is not the correct explanation for ( A ).
c) (A) is true but ( R) is false
d) (A) is false but ( R) is true
e) Both (A) and ( R) are false
6. Assertion (A): RDBMS stands for Relational Database Management System.
Reasoning (R): RDBMS does not allow relating or associating two tables in a database.
7. Assertion (A): A database is the largest component for holding and storing data and may
contain several tables.
Reasoning (R): Each table comprises multiple rows and records.
8. Assertion (A): The number of attributes or columns in a relation is called the degree of the
relation.
Reasoning (R): The number of tuples or records in a relation is called the cardinality of the
relation.

9. Assertion (A): Primary key is a set of one or more attributes that recognize tuples in a
Tables
Reasoning (R): Every table must have one primary kay
10. Assertion (A): A foreign key is an attribute whose value is derived from the primary key of
another relation.
Reasoning (R): A foreign key is used to represent the relationship between tables or
relations.
11. A school has a rule that each student must participate in a sports activity. So each one
should give only one performance for sports activity. Suppose there are five students in a
class, each having a unique roll number.
The class representative has prepared a list of sports performance as shown below. Answer
the following.
Table: Sports Preferences
Roll_No Preference
9 Cricket
13 Football
17 Badminton
21 Hockey
24 NULL
NULL Kabaddi

a) Roll no 24 may not be interested in sports. Can a NULL value be assigned to that
student’s preference field?
b) Roll no 17 has given two preferences sports. Which property of relational DBMS is
violated here? Can we use any constraint or key in the relational DBMS to check against
such violation, if any?
c) Kabaddi was not chosen by any student. Is it possible to have this tuple in the Sports
Preferences relation?
12. The school canteen wants to maintain records of items available in the school canteen and
generate bills when students purchase any item from the canteen. The school wants to create
a canteen database to keep track of items in the canteen and the items purchased by
students.
Design a database by answer the following questions:
a) To store each item name along with its price, what relation should be used? Decide
appropriate attribute names along with their data type. Each item and its price should
be stored only once. What restriction should be used while defining the relation?
b) In order to generate bill, we should know the quantity of an item purchased. Should
this information be in a new relation or a part of the previous relation? If a new
relation is required, decide appropriate name and data type for attributes. Also,
identify appropriate primary key and foreign key so that the following two
restrictions are satisfied:
i) The same bill cannot be generated for different orders.
ii) Bill can be generated only for available items in the canteen.
c) The school wants to find out how many calories students intake when they order an
item. In which relation should the attribute ‘calories’ be stored?
13. Give the terms for each of the following:
a) Collection of logically related records.
b) DBMS creates a file that contains description about the data stored in the database.
c) Attribute that can uniquely identify the tuples in a relation.
d) Special value that is stored when actual data value is unknown for an attribute.
e) a field (or collection of fields) in one table, that refers to the PRIMARY KEY in
another table.
f) Software that is used to create, manipulate and maintain a relational database.
14. In another class having 2 sections, the two respective class representatives have prepared 2
separate Sports Preferences tables, as shown below:

SECTION-1 SECTION-2
Table: Sports Preferences Table: Sports Preferences
Roll_No Preference
9 Cricket Preference Roll_No
13 Football Badminton 17
17 Badminton Cricket 9
21 Hockey Cricket 24
24 Cricket Football 13
Hockey 21
➢ Sports Preferences of SECTION-1 (arranged on roll number columns)
➢ Sports Preferences of SECTION-2 (arranged on Sports name column, and column
order is also different)
Are the states of both the relations equivalent? Justify.
15. Define the term referential integrity? How is it enforced in databases?
16. Explain the term ‘Relationship with reference to RDMS. Name the different types of
relationship that can be formed in RDMS.
17. Why foreign keys are allowed to have NULL values? Explain with an example.
18. List three significant differences between a file processing system and a DBMS.
19. Define the term database engine.
20. Differentiate between metadata and data dictionary.
TOPIC: MYSQL AND INTERFACE OF PYTHON WITH MYSQL
Q. Question
1. What does DML stands for?
a) Different Model Level
b) Data Model Language
c) Data Mode Lane
d) Data Manipulation Language

2. An attribute in a relation is a foreign key if it is the _________ key in any other relation.
a) Candidate
b) Primary
c) Super
d) Sub
3. Consider following SQL statement. What type of statement is this?
SELECT *FROM employee;

a) DML
b) DDL
c) DCL
d) Integrity Constraint
4. The data types CHAR(n) and VARCHAR(n) are used to create _________, and __________
types of string/text fields in a database.

a) Fixed, equal
b) Equal, variable
c) Fixed, variable
d) Variable, equal
5. Which of the following commands is used to remove a database?
a) Drop
b) Delete
c) Erase
d) Scratch
6. Which of the following is not an EQUI JOIN?
a) INNER JOIN
b) NATURAL JOIN
c) OUTER JOIN
d) LAP JOIN

7. What type of field values are provided by DISTINCT CLAUSE?


a) Same
b) Different
c) Common
d) None of these

Assertion (A) and Reasoning (R) based questions.


Mark the correct choice as-
a) Both ( A ) and ( R ) are the correct and R is the correct explanation for ( A ).
b) Both ( A ) and ( R ) are true and ( R ) is not the correct explanation for ( A ).
c) (A) is true but ( R) is false
d) (A) is false but ( R) is true
e) Both (A) and (R) are false

1/5
8. Assertion(A): The Cartesian product of two sets(A and B) is defined as the set all possible
ordered pairs denoted by (A+B).
Reason(R): The Cartesian product is also known as the cross product of two sets. The Cartesian
product of two tables can be evaluated such that each row of the first table will be paired with all
the rows in the second table.
9. Assertion(A): Databases commands are not case sensitive.
Reason(R):. While creating databases in MySQL, we use commands to perform some
fundamentals task. The MySQL makes no difference whether you type the commands in
lowercase or uppercase while creating databases.
10. Assertion(A): In SQL, the GROUP BY clause is used to combine all such records of a table
which have the identical values in a special field(s).
Reason(R): The GROUP BY clause always returns one row for each group. We often use the
GROUP BY clause with aggregate functions such as SUM(), AVG(), MAX(), MIN() etc.
11. Assertion(A): The INNER JOIN is one of the types of SQL JOIN that can be performed between
two or more tables.
Reason(R): In SQL, The INNER JOIN clause returns all the matching records of two or more
tables where the key field of the records are same.
12. Assertion(A): The fetchall() and fetchmany() methods are used to store the records into the
MySQL database.
Reason(R): Both the methods are used for the same purpose. The user applies these functions as
per the need. However, they return the records as lists and return None (if there is no record to
fetch).
13. Assertion(A): The MySQL query using interface is executed by execute() method.
Reason(R):While interfacing with Python IDLE, the screen() method is used to receive bulk
records from the database.
14. A table ‘Student’ is created in the database “performance’. The details of the table are given
below:
StuID Name Class Total Grade
CB/01 Kaushal 12 A 488 A
CB/02 Debashish 12 C 491 A+
CB/03 Mohit 12 B 476 B
CB/04 Sujay 12 A 480 A
CB/05 Kunal 12 D 485 A
Thereafter, The table is to be interfaced with Python IDLE to perform certain tasks. The
incomplete code is given below:
import mysql.connector as mycon
mydb=mycon.connect(host='localhost',database='........',#1user='root',passwd='twelve')
mycursor=mydb.cursor()
mycursor.execute("SELECT *FROM Student") #2
record=mycursor.<........> #3
for i in record:
print(i)
With reference to the above code, answer the following questions:
a) What will you fill in #1 to complete the statement?
b) What will you fill in #3 to fetch all the records from the table?
c) What necessary change will you perform in #2 to display all such names from the table
‘Student’ who have secured Grade A?
d) What statement will you write in #2 to add one more record in the table ‘Student’ as per

2/5
the specifications given below?
StuID Name Class Total Grade
CB/06 Monali 12 C 493 A+
15. A table ‘Employee’ is already created in a database and few records are also entered in the table.
The details of the table are shown below:
Table: Employee
EmpCode Name Dept Salary (Rs.) PhNum
E001 Goutam Modak Elect 42000 01123563783
E002 Ashim Das IT 48000 01127484637
E003 Shivam Singh IT 38000 01126534536
E004 Vikram Jana Mech 41000 01124374543
E005 Somnath Bhalla Elect 35000 01127443546

Perform the given tasks as directed:


a) Modify name of the employee with EmpCode ‘E003’ to Shivam Gupta.
b) Increase the salary of all the employees who get less than Rs. 40000 by Rs. 2000.
c) To display Name, and Salary of those employees, whose salary is between 35000 and
45000.
d) To list the names of those employees only whose name starts with ‘S’.

16. A table ‘Teacher’ is created in MySQL workbench with various fields such as TID, Name,
Qualification, Experience, etc. with appropriate data types. Thereafter, few records are entered in
the table as shown below:
Table: Teacher
TID Name Qualification Experience DOJ Salary
T01 Shubham Das PGT 5 2015-06-10 32000
T02 Alok Sharma TGT 9 2010-10-24 28000
T03 Manisha Verma PRT 12 2008-04-15 24000
T04 Nishant Choudhury TGT 11 2009-02-11 28000
T05 Abhishek Sen TGT 8 2012-09-24 29000
T06 Sushant Singh PGT 4 2016-05-04 32000

Refer the above table and write SQL commands for the following queries:
a) To show all information of the PGT teachers.
b) To list the names of all teachers with their date of join (DOJ) in ascending order.
c) To display teacher’s name, experience, salary, of PRT teachers only.
d) To display the highest and the lowest salary of the teachers from the given table.

17. Consider the following tables Product and Client. Write the outputs for SQL queries.
Table: Product
P_ID Prod_Name Manufacturer Price
TP01 Talcom Powder LAK 40
FW05 Face Wash ABC 45
BS01 Bath Soap ABC 55
SH06 Shampoo XYZ 120
FW12 Face Wash XYZ 95

Table: Client
3/5
C_ID ClientName City P_ID
01 Cosmetic Shop Delhi FW05
06 Total Health Mumbai BS01
12 Live Life Delhi SH06
15 Pretty Woman Delhi FW12
16 Dreams Banglore TP01

a) SELECT DISTINCT City FROM Client;


b) SELECT Manufacturer, MAX(Price), Min(Price), Count(*) FROM Product GROUP BY
Manufacturer;
c) SELECT ClientName, Manufacturer FROM Client, Product WHERE Client.ID = Product.ID;
d) SELECT Prod_Name, Price*4 FROM Product;
e) SELECT * FROM Client WHERE City=”Delhi”;
f) SELECT *FROM Product WHERE Price BETWEEN 50 to 100;
g) SELECT ClientName, City Prod_Name, Price FROM Client, Product WHERE Client.P_ID =
Product.P_ID;
h) UPDATE Product SET Price=Price+10 WHERE Manufacturer=’ABC’;

18. The school has asked their estate manager Mr. Sandip to maintain the data of all the labs in a
table LAB. Rahul has entered data of 5 labs.
Table:LAB
LAB_NO LAB_NAME INCHARGE CAPACITY FLOOR
L001 Chemistry Daisy 20 I
L002 Biology Venky 20 II
L003 Math Preeti 15 I
L004 Language Daisy 36 III
L005 Computer Mary Kom 37 II
Based on the data given above answer the following questions:

i) Identify the columns which can be considered as Candidate keys


ii) Write the degree and cardinality of the table
iii) Write the statements to:
a) Delete the record for the LAB_NO -‘L004’ from the table LAB.
b) Increase the capacity of all the labs by 10 students which are on ‘I’ floor.

iv)Write the statements to:


a) Add a constraint PRIMARY KEY to the column LAB_NO in the table.
b) Delete the table LAB.

19. The code given below reads the following record from the table named Student and display only
those records who have marks greater than 75:
Roll_no-integer, Name- String, Class- integer, Marks-integer

Note the following to establish connectivity between Python and MySQL:


➢ Username is root
➢ Password is tiger
➢ The table exists in a MySQL database named School

Write the following missing statements to complete the code:


Statement 1- To form the cursor object
4/5
Statement 2- To execute the query that extracts records of those students whose marks are
greater than 75.
Statement 3- to read the complete result of the query (records whose marks are greater than 75)
into the object named data, from the table student in the database.

import mysql.connector as mysql


def sql_data():
con1=mysql.connect(host='localhost', user='root', password='tiger',
database='school')
mycursor=__________________ #Statement 1
print("Students with marks greater than 75 are")
___________________ #Statement 2
data=_______________ #Statement 3
for i in dada:
print(i)
print()

20. Answer the following questions-


a) What are the main components of a table created in a database?
b) How will you classify SQL commands?
c) Differentiate between the Primary key and the Candidate key.
d) Name the button available on MySQL Workbench to display the result of your query.
e) What are the parameters of mysql.connector.connect() function?
f) Define the term result set?
g) What is the purpose of cursor.rowcount?
h) What is meant by a database cursor?
i) Distinguish between NATURAL JOIN and EQUI JOIN.
j) Differentiate between WHERE clause and HAVING clause.

-------------- xxxxxxxx -----------------

5/5
TOPIC:-NETWORKING
1) Name the protocol responsible to send/receive files over Computer Network. 1
(a) PPP (b)HTTP (c) FTP (d) SMTP
2) __________ is a fundamental Protocol on Internet, which enables data transfer between a client 1
and a server.
3) Expand GSM and CDMA. 1
4) Name two E-mail Client software. 1
5) Name two Linux distributions? 1
6) Fill in the blank: 1
____________ protocol is used to provide access to the mail inbox that is stored in e-mail
server.
(a) VoIP (b) SMTP (c) POP3 (d)HTTP
7) What is Blog? 1
8) Expand SMTP and W3C. 1
9) What is Telnet? 1
10) Fill in the blank: 1
Data transfer in LAN is quite high, and usually varies from ________ Mbps (called Ethernet)
to ____________Mbps (called Gigabit Ethernet )
11) Each NIC has a MAC address . Expand NIC and MAC. 1
12) State whether true or false. 1
A router can be wired or wireless.
13) What is URI or URL? Give Two examples of it. 1
14) Fill in the blank: 1
192:68:0:178 is an Example of _________________ Address.
(a)IP (b)HTTP (c) MAC (d) SMTP
15) Expand IoT and WoT. 1
16) What is Trojan Horse? 1

17) Mention one server side scripting language. 1

18) What is DNS? 1

19) Write Full form of “bps” and “BPS” 1

20) Which of the following is fastest medium of data transfer. 1

21) (a) Twisted Pair Cable (b) Microwave transmission (c) Co-axial Cable (d) Fibre optic cable
22) “NSFNET came after ARPANET”. Expand both the terms and Evaluate the statement.(whether 2

true or false”).
23) Differentiate between Microwave and Infrared. 2

24) Expand the following: 2


a. CSS b. NNTP c. ASP d. SGML
25) How XML is different from HTML. 2
26) Differentiate between Bus and Star Topology. 2
27) Differentiate between “Message Switching” and “Packet Switching”. 2
28) Government is planning to establish three different training centres in Asansol. Its main office 5
is at Kolkata. As a networking expert suggest the solution of given networking problems.

Distance between Various Centres


Centre 1 to Centre 2 500m
Centre 2 to Centre 3 300m
Centre 3 to Centre 1 350m
Number of Computers in various Centres
Centre 1 100
Centre 2 75
Centre 3 65
(i) Suggest the Network Topology to connect all three centre at Asansol. 1
(ii) Which Centre is suitable to house the server? 1
(iii) Suggest the economical way to connect the centres at Asansol to main office at Kolkata. 1
(iv) Suggest the placement of switch in different buildings. 1
(v) Suggest the cable to connect computers within centre economically. 1

29. A renowned medical chain has established a new


5
branch in the city. It has four buildings as shown
in the diagram given below.

Distance between the buildings are as follows No of Computers


A to B 65m A 25
A to C 140 m B 110
C to D 150m C 15
D to B 70m D 50
A to D 145m
C to B 175m
(i) Suggest a cable layout connection between the building with topology.
(ii) Suggests most suitable place to house the server.
(iii)Suggest the placement of repeater device with justification.
(iv) Suggest a tool (hardware/software) to prevent unauthorized access to network.
(v) Suggest the placement of Hub/Switch in the network.
30. Knowledge Supplement Organization has set up its new centre at Mangalore for its office and
web based activities. It has four buildings as shown in the diagram below:

Center to center distance between various buildings Number of Computers


Alpha to Beta 50m Alph 25
a
Beta to Gamma 150m Beta 50
Gamma to Lambda 25m Gam 125
ma
Alpha to Lambda 170m Lam 10
bda
Beta to Lambda 125m
Alpha to Gamma 90m
i)Suggest a cable layout of connections between the buildings.
ii) Suggest the most suitable place(i.e building) to house the server of this organization with a
suitable reason.
iii) Suggest the placement of the following devices with justification:
Repeater, Hub/Switch
iv) The organization is planning to link its front office situated in the city in a hilly region
where cable connection is not feasible, suggest an economic way to connect it with
reasonably high speed?
DAV INSTITUTIONS, WEST BENGAL ZONE
MARKING SCHEME (HINTS TO SOLUTIONS)
CLASS: XII
SUB: COMPUTER SCIENCE (083)

TOPIC: REVISION TOUR

1 dict_student.update(dict_marks)
2 a) 1-b,2-d,3-a,4-c
3 b) ii,iii,iv
4 d) None of these
5 b) 1-a,2-c,3-d,4-b
6 b) x is 50
Changed global x to 2
Value of x is 2
7 Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
8 Assertion is true but Reason is false.
9 Assertion is false but Reason is true.
10 Both Assertion and Reason are false.
11 Both Assertion and Reason are false.
12 Assertion is false but Reason is true.
13 Both Assertion and Reason are true and Reason is not the correct explanation of Assertion.
14 Both Assertion and Reason are true and Reason is not the correct explanation of Assertion
15 Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
16 c) Assertion is true, but Reason is false.
17 100
90
80
70
60
50
18 #Read the limit
limit = float(input("Enter the limit"))
max_price = 0
# Read the next price
next_price = float(input("Enter a price or 0 to stop:"))
while next_price > 0 :
if next_price < limit and next_price > max_price:
max_price = next_price
#Read the next price
next_price = float(input("Enter a price or 0 to stop:"))
if max_price > 0:
print("Largest Price =", max_price)
else :
print("Prices exceed limit of", limit);
19 dayNames = ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY",
"SATURDAY", "SUNDAY"]
dayNum = int(input("Enter day number: "))
firstDay = input("First day of year: ")

if dayNum < 2 or dayNum > 365:


print("Invalid Input")
else:
startDayIdx = dayNames.index(str.upper(firstDay))
currDayIdx = dayNum % 7 + startDayIdx - 1
if currDayIdx >= 7:
currDayIdx = currDayIdx - 7
print("Day on day number", dayNum, ":", dayNames[currDayIdx])

20 months = ["January", "February", "March", "April", "May", "June",


"July", "August", "September", "October", "November", "December"]

dateStr = input("Enter date in MMDDYYYY format: ")


monthIndex = int(dateStr[:2]) - 1
month = months[monthIndex]
day = dateStr[2:4]
year = dateStr[4:]
newDateStr = month + ' ' + day + ', ' + year
print(newDateStr)
21 str = input("Enter a few sentences: ")
length = len(str)
spaceCount = 0
alnumCount = 0
for ch in str :
if ch.isspace() :
spaceCount += 1
elif ch.isalnum() :
alnumCount += 1
alnumPercent = alnumCount / length * 100
print("Original Sentences:")
print(str)
print("Number of words =", (spaceCount + 1))
print("Number of characters =", (length))
print("Alphanumeric Percentage =", alnumPercent)
22 l = eval(input("Enter the list: "))
print("Original List")
print(l)
l = l[-1:] + l[:-1]
print("Rotated List")
print(l)
23 days_in_months = { "january":31, "february":28, "march":31, "april":30,
"may":31, "june":30, "july":31, "august":31, "september":30,
"october":31, "november":30, "december":31}

m = input("Enter name of month: ")


if m not in days_in_months:
print("Please enter the correct month")
else:
print("There are", days_in_months[m], "days in", m)

print("Months in alphabetical order are:", sorted(days_in_months))

print("Months with 31 days:", end=" ")


for i in days_in_months:
if days_in_months[i] == 31:
print(i, end=" ")
day_month_lst = []
for i in days_in_months:
day_month_lst.append([days_in_months[i], i])
day_month_lst.sort()
month_day_lst =[]
for i in day_month_lst:
month_day_lst.append([i[1], i[0]])

sorted_days_in_months = dict(month_day_lst)
print()
print("Months sorted by days:", sorted_days_in_months)
24 def addDict(dict1, dict2):
union_dict = {}
for key, value in dict1.items():
union_dict[key] = value
for key, value in dict2.items():
union_dict[key] = value
return union_dict

dict1 = {'a': 1, 'b': 2}


dict2 = {'b': 3, 'c': 4}
result = addDict(dict1, dict2)
print("Union of dict1 and dict2:", result)
25 for Name in [“_Ramesh_”, “_Suraj_” , “_Priya_”]
if Name [0] =_=‘S’ :
print (Name)
26 Mutability means that the value of an object can be updated by directly changing the contents of
the memory location where the object is stored. There is no need to create another copy of the
object in a new memory location with the updated values. Examples of mutable objects in
python include lists, dictionaries.
In python, "in place" tasks refer to operations that modify an object directly without creating a
new object or allocating additional memory. For example, list methods like append(), extend(),
and pop() perform operations in place, modifying the original list, while string methods like
replace() do not modify the original string in place but instead create a new string with the
desired changes.
27 listA = [8, 9, 10]

1. listA[1] = 17
2. listA.extend([4, 5, 6])
3. listA.pop(0)
4. listA.sort()
5. listA = listA * 2
6. listA.insert(3, 25)

28 The two ways to remove something from a list are:

1. pop method — The syntax of pop method is List.pop(<index>).

2. del statement — The syntax of del statement is

del list[<index>] # to remove element at index


del list[<start>:<stop>] # to remove elements in list slice

29 1. states = []
2. states.append('Delhi')
3. states.append('Punjab')
4. states2 = ['Rajasthan', 'Gujarat', 'Kerala']
5. states2.insert(0,'Odisha')
6. states2.insert(2,'Tripura')
7. a = states2.index('Gujarat')
states2.insert(a - 1,'Haryana')
8. b = states2.pop(4)
print(b)

30 1. a * 3 ⇒ (1, 2, 3, 1, 2, 3, 1, 2, 3)
(a, a, a) ⇒ ((1, 2, 3), (1, 2, 3), (1, 2, 3))
So, a * 3 repeats the elements of the tuple whereas (a, a, a) creates nested tuple.
2. Yes, both a * 3 and a + a + a will result in (1, 2, 3, 1, 2, 3, 1, 2, 3).
3. This colon indicates (:) simple slicing operator. Tuple slicing is basically used to obtain a
range of items.
tuple[Start : Stop] ⇒ returns the portion of the tuple from index Start to index Stop
(excluding element at stop).
a[1:1] ⇒ This will return empty list as a slice from index 1 to index 0 is an invalid range.
4. Both are creating tuple slice with elements falling between indexes start and stop.
a[1:2] ⇒ (2,)
It will return elements from index 1 to index 2 (excluding element at 2).
a[1:1] ⇒ ()
a[1:1] specifies an invalid range as start and stop indexes are the same. Hence, it will
return an empty list.

31 A dictionary is termed as an unordered collection of objects because the elements in a dictionary


are not stored in any particular order. Unlike string, list and tuple, a dictionary is not a sequence.
For a dictionary, the printed order of elements is not the same as the order in which the elements
are stored.

32 Keys of a dictionary must be of immutable types such as

1. a Python string
2. a number
3. a tuple (containing only immutable entries)

33 For a tuple to be used as a key in a dictionary, all its elements must be immutable as well. If a
tuple contains mutable elements, such as lists, sets, or other dictionaries, it cannot be used as a
key in a dictionary.

34 Yes, we can modify the contents of a dictionary.


Values of key-value pairs are modifiable in dictionary. New key-value pairs can also be added to
an existing dictionary and existing key-value pairs can be removed.
However, the keys of the dictionary cannot be changed. Instead we can add a new key : value
pair with the desired key and delete the previous one.
For example:

d={1:1}
d[2] = 2
print(d)
d[1] = 3
print(d)
d[3] = 2
print(d)
del d[2]
print(d)
35

36

37 A global variable is a variable that is accessible globally. A local variable is one that is only
accessible to the current scope, such as temporary variables used in a single function
definition. A variable declared outside of the function or in global scope is known as global
variable. This means, global variable can be accessed inside or outside of the function where as
local variable can be used only inside of the function. We can access by declaring variable as
global

****
TOPIC: FUNCTIONS
MARKING SCHEME
3 ()
2 def
3 Called/Invokedoranyotherwordwithsimilarmeaning
4 Add()
5 Add(10,20)
6 C=Add(10,20)
7 Line 5
8 1000
1000
None
9 1. Positional
2. Keyword
3. Default
4. Variable length argument
Example : (Keyword argument)
def Interest(principal, rate, time):
return(principal*rate*time)/100
R=Interest(rate=.06, time=7, principal=100000)
10 60
70
130
11 Swap(num1=100,num2=200)
12 Line 2 : Keyword argument must not be followed by positional argument
Line 4 : There is no keyword argument with name “Time”
Line5: Missing value for positional argument “R”
13 <class 'tuple'>
(20, 24, 28)
14 Local variables are those variables which are declared inside any block like function,
loop or condition. They can be accessed only in that block. Even formal argument will
also be local variables and they can be accessed inside the function only. Local
variables are always indented. Life time of local variables is created when we enter in
that block and ends when execution of block is over.
Global variables are declared outside all block i.e. without any indent. They can be
accessed anywhere in the program and their life time is also throughout the program.
Example:
count=1 #Global variable count
def operate(num1, num2): # Local variable num1 and
num2 result = num1 + num2 #Local variable
result print(count)
operate(100,200)
count+=1
operate(200,300)
15 100
50
100
16 100
1000
1000
17 True
18 True
19 exam$$*CBSE*COM
20 300@200
300#100
150@100
300@150
21 4
16
25
22 10#25$185
18#50$318
30#100$480
23 $$$$$
@@@@@@
@@@@ 325
AAAAA
24 3$3
6#30
6$1
6#7
1$1
2$7
25 [42,10.0,3.0,14,18,9.0,50.0,25.0,26]
26 def test_prime(n):
if (n == 1):
return False
elif (n == 2):
return True
else:
for x in range(2, n):
if (n % x == 0):
return False
return True
print(test_prime(9))
30 def unique_list(l):
x = []
for a in l:
if a not in x:
x.append(a)
return x
print(unique_list([1, 2, 3, 3, 3, 3, 4, 5]))
TOPIC: EXCEPTION HANDLING
MCQ:
Q1. c. Syntax error
Q2. a) To define the block of code where an exception may occur
Q3. c) except
Q4. b) SyntaxError
Q5 a) Separate the exceptions using commas
Q6. b) It ensures the code within it will always execute, regardless of whether an exception occurs or
not.
Q7. c) It is executed if no exception occurs in the try block.
Q8. c) To check if a condition is true
Q9. d) It can specify the type of exceptions to catch.
Q10. a) Division by zero
Finally block
Q11. b) It catches all exceptions and ignores them.
Q12. a. Both Statement I and Statement II are true
Q13. c. Statement I is true but Statement II is false
Q14. d. Statement I is false but Statement II is true
15. b. a-2, b-3, c-1, d-4
Topic : File Handling
MCQ
1. c. seek() 1
2. d. dump() 1
3. b. r 1
4. a. file_object.seek(offset [, reference_point]) 1
5. c) A is True but R is False 1
6. d) Every line ends with new line character “\n” 1
7. a) f.read(3) 1
8. b) binary file 1
9. b) fh.seek(20,0) 1
10. (b) Both A and R are true and R is not the correct explanation for A 1
Programming
1. Bye
As when an existing file is opened in write mode, it truncates the existing data from the file.
2. def count_lines():
f=open"Story.txt","r")
line=f.readlines()
c=0
for wd in line:
if wd[0]=="A" or wd[0]=="a":
c=c+1
print("Total number of lines:",c)
f.close()
count_lines()
3. def create():
f=open("data.txt","r")
f1=open("info.txt","w")
str=f.read()
for i in str:
if i==".":
i=","
f1.write(i)
else:
f1.write(i)
f.close()
f1.close()
create()
4. import pickle
def display():
f=open('number.dat','rb')
try:
while True:
rec=pickle.load(f)
if(rec%7==0 and a%10==7):
print(rec)
except:
f.close()
display()
5. import pickle
def update(adno):
rec={}
fin=open("record.dat","rb")
fout=open("temp.dat","wb")
ack=False
while True
try:
rec=pickle.load(fin)
if rec["Adno"]==adno:
ack=True
rec["Fees"]=int(input("Enter the fees:"))
pickle.dump(rec,fout)
else:
pickle.dump(rec,fout)
except:
break
if ack==True:
print("Fees updated!"
else:
print("Record not found!")
fin.close()
fout.close()
6. import pickle
def search(dept)
with open('EMP.DAT','rb') as file:
while True:
try:
emprec=pickle.load(file)
for r in emprec:
dep=emprec[r][2]
if dep==dept:
print(r, emprec[r])
except EOFError:
break
7.
8.

9.

10.
11.

12.

Case Based Questions.


1.i. Identify the suitable code for blank space in line marked as Statement-1. 1
a) csv file b) CSV c) csv d) Csv
ii. Identify the missing code for blank space in line marked as Statement-2? 1
a) "School.csv","w" b) "Student.csv","w"
c) "Student.csv","r" d) "School.csv","r"
iii. Choose the function name (with argument) that should be used in the blank space of line 1
marked as Statement-3
a) reader(fh) b) reader(MyFile)
c) writer(fh) d) writer(MyFile)
iv. Identify the suitable code for blank space in line marked as Statement-4. 1
a) 'ROLL_NO', 'NAME', 'CLASS', 'SECTION' b) ROLL_NO, NAME, CLASS,
SECTION
c) 'roll_no','name','Class','section' d) roll_no,name,Class,section c) co.connect()
v. Choose the function name that should be used in the blank space of line marked as 1
Statement-5 to create the desired CSV File?
a) dump() b) load()
c) writerows() d) writerow()
2.i. a. F= open("STUDENT.DAT",'wb') 1

ii. c. pickle.dump(L,F) 1
iii. a. R = pickle.load(F) 1
iv. a. ‘r+’ opens a file for both reading and writing. File object points to its beginning. 1
v. d. moves the current file position to a given specified position 1
******************
TOPIC: DBMS
1. d) Primary key
2. b)Tuples-to-Tuples

3. b)Redundancy
4. b)degree

5. b)Tuple

Assertion (A) and Reasoning (R) based questions.

Mark the correct choice as

a) Both ( A ) and ( R ) are the correct and R is the correct explanation for ( A ).
b) Both ( A ) and ( R ) are true and ( R ) is not the correct explanation for ( A ).
c) (A) is true but ( R) is false
d) (A) is false but ( R) is true
e) Both (A) and ( R) are false
6. c) (A) is true but ( R) is false
7. a) Both ( A ) and ( R ) are the correct and R is the correct explanation for ( A ).
8. b) Both ( A ) and ( R ) are true and ( R ) is not the correct explanation for ( A ).
9. a) Both ( A ) and ( R ) are the correct and R is the correct explanation for ( A ).
10. a) Both ( A ) and ( R ) are the correct and R is the correct explanation for ( A ).
11. a) No NULL value cannot be assigned to it because according to the school rule every
Ans. student must participate in a sports activity.
b) No roll no 17 cannot give two preferences because it is violating the primary key
constraint. Every student has unique roll no. We can use primary key constraint to
check for such violations.

c) Not possible because roll no field cannot be NULL as no student can have NULL as
its roll number.
12. a) ITEM relation which holds data for the name of the food item and it's price.
Ans. ITEM( ItemId, ItemName, Price)
Here, ITEM is the table. ItemId column is the primary key of the relation, ItemName
is the name of the food item and price is its price per quantity.
To restrict duplicate values, ItemId is made the primary key of the relation.

b) A new relation is required to store the purchase of the item. It would be called
ORDERS and it has the following attributes -
1- OrderId - a unique id for every order. It is the primary key. This constraint satisfies
the condition (i).
2- Quantity - stores the quantity purchased by the student.
3- ItemId - foreign key that references the ITEM relation to make sure that item is
available in the canteen. This constraint satisfies the condition (ii).

c) ITEM relation. Since every item has it's own calorie value so it would be stored
with every item.

13. a) Database
Ans. b) Database catalog or data dictionary
c) Attribute that can uniquely identify the tuples in a relation is PRIMARY KEY.
d) Null.
e) A foreign key.
f) Relational Database Management System
14. Yes, the states of both the relations is equivalent because in database the row order
Ans. does not matter also there is no distinction of tables based on the order of attributes
(columns) they have, so both relations are equivalent.

15. Referential integrity is a term used in database design to describe the relationship
Ans. between two tables. It is important because it ensures that all data in a database remains
consistent and up to date. It helps to prevent incorrect records from being added,
deleted, or modified.

Referential integrity is usually enforced by creating a foreign key in one table that
matches the primary key of another table. If referential integrity is not enforced, then
you may encounter data redundancy and inconsistencies.

16. it is an association between tables. Those associations create using join statements to
Ans. retrieve data. It is a condition that exists between two database tables in which one
table contains a foreign key that references the primary key of the other tables.

There are 3 different types of relations in the database: one-to-one. one-to-many,


and. many-to-many.
17. Sometimes, we want to enter a record, which is not related. To handle this situation, it
Ans is allowed to enter a NULL value in the foreign key. For example, Suppose a
shopkeeper wants to sell a product, but the customer is not a regular customer, so his
customer id does not exist.
18. File system is a method of organizing the files with a hard disk or other medium of
Ans. storage. File system arranges the files and helps in retrieving the files, when required. It
is compatible with different file types, such as mp3, doc, txt, mp4, etc and these are
also grouped into directories. It also influences the method of writing and reading data
to the hard disk.
Examples are NTFS or the New Technology File System and EXT, the Extended File
System.

DBMS, meanwhile, is the acronym for Database Management System. It is also a


software used to store and regain user’s data, while also maintaining the required
security measures. This includes a group of programmers that can help to manipulate
the database. In bigger systems, DBMS helps the users as well as third party software
to store and recover the data.

Examples are MySQL, MS SQL Server, Oracle and so on.

19. A database engine (or storage engine) is the underlying software component that a
Ans. database management system (DBMS) uses to create, read, update and delete (CRUD)
data from a database.
20. The data dictionary contains data about the data in the database. Similarly.
Ans. Metadata component is the data about the data in the data warehouse.
-------- xxxxxxxx -----------------
Topic: MySQL and Interface of Python with MySQL
-----------------------------------------------------------------------------------------------------------------------------------
Q. Value points/ Key points
No.
1. d) Data Manipulation Language
2. b) Primary
3. a) DML
4. c)Fixed, variable
5. a) Drop
6. a) INNER JOIN
7. b)Different
8. (A) is false but ( R) is true
9. Both ( A ) and ( R ) are the correct and R is the correct explanation for ( A ).
10. (A) is false but ( R) is true
11. Both ( A ) and ( R ) are the correct and R is the correct explanation for ( A ).
12. (A) is false but ( R) is true
13. (A) is true but ( R) is false
14. a) Database=’Performance’
b) record=mycursor.fetchall()
c) mysursor.execute(“SELECT *FROM Student WHERE Grade=’A’ ”)
d) mycursor.execute(“INSERT INTO Student VALUES(‘CB/06’, ‘Monali’, ‘12C’, 493, ‘A+’)”)

15. a) UPDATE Employee SET Name=’Shivam Gupta’ WHERE EmpCode=’E003’;


b) UPDATE Employee SET Salary=Salaey+2000 WHERE Salary<40000;
c) SELECT Name, Salary FROM Employee WHERE Salary BETWEEN 35000 AND 45000;
d) SELECT *FROM Employee WHERE Name LIKE “S%”;

16. a) SELECT *FROM Teacher WHERE Qualification=’PGT’;


b) SELECT Name, DOJ FROM Teacher ORDER BY DOJ;
c) SELECT Name, Experience, Salary FROM Teacher WHERE Qualification=’PRT’;
d) SELECT MAX(Salary), MIN(Salary) FROM Teacher;

17. a)
City
Delhi
Mumbai
Banglore

b)
Manufacturer Max(Price) Min(Price) Count(*)
LAK 40 40 1
ABC 55 45 2
XYZ 120 95 2

c)
ClientName Prod_Name
Cosmetic Shop Face Wash
Total Health Bath Soap
Live Life Shampoo
Pretty woman Face Wash
Dreams Talcom Powder

Prod_Name Price*4
TalcomPowder 160
Face Wash 180
d) Bath Soap 220
Shampoo 480
Face Wash 380

e)
C_ID ClientName City P_ID
01 Cosmetic Shop Delhi FW05
12 Live Life Delhi SH06
15 Pretty Woman Delhi FW12
f)

P_ID Prod_Name Manufacturer Price


BS01 Bath Soap ABC 55
SH06 Shampoo XYZ 120
FW12 Face Wash XYZ 95
g)
ClientName City Prod_Name Price
Dreams Banglore Talcom Powder 40
Cosmetic Shop Delhi Face Wash 45
Total Health Mumbai Bath Soap 55
Live Life Delhi Shampoo 120
Pretty Woman Delhi Face Wash 95
h)
P_ID Prod_Name Manufacturer Price
FW05 Face Wash ABC 55
BS01 Bath Soap ABC 65
18. i) LAB_NO, LAB_NAME

ii) Degree:5
Cardinality:5

iii)
a) DELETE FROM LAB WHERE LAB_NO=’L004’;
b) UPDATE LAB SET CAPACITY=CAPACITY+10 WHERE FLOOR=’I’;

iv)
a) ALTER TABLE LAB ADD CONSTRAINT PKEY PRIMARY KEY (LABNO);
b) DROP TABLE LAB;

19. Statement 1- con1.cursor()


Statement 2- mycursor.execute(“SELECT *FROM Student WHERE marks>75”)
Statement 3- mycursor.fetchall()

20. a)
Entity
Attributes/Fields
Records
b)
DDL: Data Definition Language
DQL: Data Query Language
DML: Data Manipulation Language
DCL: Data Control Language

c)
Primary Key Candidate Key
1.The Primary Key is a column or a combination 1.A candidate Key can be any column or a
of columns that uniquely identify a record combination of columns that can qualify as
‘Unique Key’ in a database.
2. Only one ‘Candidate Key’ can be a ‘Primary 2.There are multiple ‘Candidate Keys’ in a
Key’. table.
Example:
Table: Student
Admno RollNo Name
1000 1 Akash
1001 2 Neha
1002 3 Himanshu
Roll Number and Admission number both are unique field so, they are candidate key.
Unique field RollNo we can take as a Primary key.

d)The button is ‘Execute’ which displays the result when clicked.

e) There are four parameters –


i) host=<host name>
ii) database=<database_name>
iii) user=<user_name>
iv) password=<password>

f) The term ‘result set’ defines a set of records which are retrieved from a database table while
performing queries. However, the result set may not be known to the user but can be verified.

g) It defines the property of cursor object which returns the number of records retrieved from a
database table.

h) Usually, a cursor in SQL and databases is control structure to traverse over the records in a
database. So it is used for the fetching of the results. We get the cursor object by calling the cursor()
method of connection.

i) The EQUI Join is a simple Join clause where the relation is established using equal (=) sign as the
relational operator to mention the condition.
The NATURAL Join is referred to as a type of EQUI Join and is structured in such a way that the
columns with the same name of the associated tables will appear once only.

j)
WHERE CLAUSE HAVING CLAUSE
1.WHERE clause allows you to filter data from 1.HAVING clause allows you to filter data
specific rows(individual rows) from a table from a group of rows in a query based on
based on certain conditions. conditions involving aggregate values.
2.WHERE clause cannot include aggregate 2. HAVING clause can include aggregate
functions functions.
Example: Example:
SELECT *FROM Student WHERE marks>75 SELECT avg(gross), sum(gross) FROM
employee GROUP BY grade HAVING
grade=’E4’;

---------------- xxxxxxxxxxxxx ----------------

You might also like