0% found this document useful (0 votes)
102 views51 pages

Cs Worksheet

The document contains a series of multiple choice, true/false, assertion/reason, error finding, and output prediction questions related to Python programming concepts. It covers topics such as data types, control structures, functions, and error handling. The questions are designed for Class XI students to assess their understanding of Python programming.

Uploaded by

proffesionalraaj
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)
102 views51 pages

Cs Worksheet

The document contains a series of multiple choice, true/false, assertion/reason, error finding, and output prediction questions related to Python programming concepts. It covers topics such as data types, control structures, functions, and error handling. The questions are designed for Class XI students to assess their understanding of Python programming.

Uploaded by

proffesionalraaj
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

Python Revision Tour of Class XI

MULTIPLE CHOICE BASED QUESTIONS

1 Which of the following expressions generate an Error? 1


a. int("23") b. int("23.5") c. float("23") d. float("23.5")

2 Which of the following can not be used as normal identifiers: 1


a. Pass b. pass c. int d. eval

3 What will be the output of the given below program: - 1


if 1+3==7:
print("Hello")
else :
print("Know Program")
a. Hello b. Know Program
c. Compiled successfully, no output d. Error

4 Which statement will check if a is equal to b ? 1

a. if a = b : b. if a == b : c. if a === b d. if a == b

5 The ____________ statement prematurely ends the execution of the current while / for loop. 1
a. break b. continue c. pass d. None of these

6 What will the following code snippet produce : 1


for i in range(1,5):
print(i,end=" ")
if i==3:
break
a. 123 b. 1234 c. 12 d. 12345

7 Which of the following methods removes all items from a list? 1


a. remove() b. delete() c. clear() d. pop()

8 Which of the following is a correct way to define a single-element tuple? 1


a. t = (10) b. t = 10, c. t = (10,) d. Both b and c

9 Which of the following is correct with respect to Python Code given below? 1

Coins={"Five":10,"Ten":100}
a. one dictionary named Coins is created.
b. "Five" and "Ten" are the keys of dictionary named Coins
c. 10 and 100 are the values of dictionary named Coins
d. All of these

10 Consider the code below and choose the correct output from the given options: 1
customer = {"city": "Prayagraj", "State": "Uttar Pradesh", "capital": "Lucknow"}
print([Link]())
a. dict_items([{'city', 'Prayagraj'), ('State', 'Uttar Pradesh'), ('capital', 'Lucknow'}])
b. dict_items([('city', 'Prayagraj'), ('State', 'Uttar Pradesh'), ('capital', 'Lucknow')])
c. dict_items((['city', 'Prayagraj'], ['State', 'Uttar Pradesh'], ['capital', 'Lucknow']))
d. None of the Above

11 S = "Python Programming" 1
The output of statement print(S[::-1][::2]) is______________.
12 Which of the following methods will convert "PYTHON" to "python"? 1
a. lower("PYTHON") b. "PYTHON".tolower()
c. "PYTHON".lower() d. "PYTHON".lowerto()

TRUE / FALSE BASED QUESTIONS

13 State whether the following given statement is True or False : 1


Statements which are start with # ,never executed by the interpreter.

14 State whether the following given statement is True or False : 1


The '=' operator is used for comparison in python.

15 State whether the following given statement is True or False : 1


The if...else is an extension of the simple if statement.

16 State whether the following given statement is True or False : 1


We use if-elif-else statement when the multipath decisions are involved.

17 State whether the following given statement is True or False : 1


Iterative construct is used to execute the statement multiple times.

18 State whether the following given statement is True or False : 1


There are three types of iterative statements in python.

19 State whether the following given statement is True or False : 1


The list method pop() removes the first element of the list.

20 State whether the following given statement is True or False : 1


(10,) and (10) are the same in Python.

21 State whether the following given statement is True or False : 1


Python Dictionary contains mappings comprising of Key Value Pairs.

22 State whether the following given statement is True or False : 1


Python dictionary is in fact Ordered Collection of Key Value pairs in latest python versions.

23 State whether the following given statement is True or False : 1


The replace ( ) function modifies the Original string.

24 State whether the following given statement is True or False : 1


The in operator can be used to check if a substring exists within a string.

ASSERTION (A) REASON (R) BASED QUESTIONS

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


a. Both A and R are true, and R is the correct explanation of A.
b. Both A and R are true, but R is not the correct explanation of A.
c. A is true, but R is false.
d. A is false, but R is true.

25 Assertion (A) : In python, implicit type conversion automatically converts a lower data type to a 1
higher data type during expression evaluation
Reason (R) : Python allows conversion from float to int automatically if both are used in an
expression.
26 Assertion (A) : Keywords can not be used as normal identifiers. 1
Reason (R) : Keywords are reserved for special purposes.

27 Assertion (A) : In an if-else statement, the if block checks the true part whereas else checks for 1
the false part.
Reasoning (R) : In a conditional construct, the else block is mandatory.

28 Assertion (A) : In an if-else statement, the if block checks the true part whereas else checks for 1
the false part.
Reasoning (R) : In a conditional construct, the else block is mandatory.

29 Assertion (A) : break Statement is used to terminate the loop. 1


Reason (R) : break is a jump statement which is used to move the control to the starting point
of the loop.

30 Assertion (A) : while loop is an entry controlled loop. 1


Reason (R) : In while loop, the condition is checked first before entering the body of the loop.

31 Assertion (A) : Lists in Python are mutable. 1


Reason (R) : You can change, add, or delete elements from a list.

32 Assertion (A) : Tuples are more memory efficient than lists. 1


Reason (R) : Tuples are immutable, while lists are mutable.

33 Assertion (A) : Dictionaries in Python are mutable. 1


Reasoning (R) : The values present in key value pairs cannot be changed.

34 Assertion (A) : Dictionaries are mutable but their keys are immutable. 1
Reason (R) : The values of a dictionary can change but keys of the dictionary cannot be
changed because through them data is hashed.

35 Assertion (A) : Strings in Python are immutable. 1


Reason (R) : In Python, once a string is created, the characters in it can not be changed
individually using indexing.

36 Assertion (A) : "Hello World".split() returns a list with one element:"Hello World" 1
Reason (R) : The split() method breaks a string into parts using the specified separator.

ERROR FINDING BASED QUESTIONS

37 Correct the given statement : 1


x y z = 10, 20, 30

38 Correct the given python statement(s) : 2


term1 = input("Enter term 1 marks")
term2 = input("Enter term 2 marks")
total = term1+term2
print("You are " + total + " years old")

39 Observe the following code carefully and rewrite it after removing all syntactical errors. 2
Underline all the corrections made.
def 1func():
a=input("Enter a number"))
if a>=33
print("Promoted to next class")
ELSE:
print("Repeat")
40 Amit, a Python programmer, is working on a project in which he wants to write a function to 2
count the number of even and odd values in the list. He has written the following code but his
code is having errors. Rewrite the correct code and underline the corrections made.
define EOCOUNT(L):
even_no = odd_no = 0
for i in range(0,len(L))
if L[i]%2=0:
even_no+=1
else:
odd_no+=1
print(even_no, odd_no)

41 Rewrite the following code in python after removing all syntax error(s). Underline each 2
correction done in the code.
250 = Num
while Num <= 1000:
if Num => 750:
print Num
Num = Num + 100
else
print Num*3
Num= Num+ 150

42 Rewrite the following code in python after removing all syntax error(s). Underline each 2
correction done in the code.
while x>0
if a%2=0
print(a%2)
elseif a%3=0 then
print(a%3)

43 Rewrite the following code in python after removing all syntax error(s). Underline each 3
correction done in the code.
fruits = ['apple', 'banana' 'cherry']
t = (1, 2, 3)
t[1] = 100
k = (5,)
Print(k[0])
print(t)
print(fruits)

44 Rewrite the following code in python after removing all syntax error(s). Underline each 3
correction done in the code.
colors =list ["red", "green", "blue",]
[Link]["green"]
my_tuple = (10, 20, 30
tuple1 = (1, 2)
tuple2 = (3, 4)
result = tuple1 + tuple2[]
print(my_tuple)
print(colors)

45 The following python code contains an error. Rewrite the correct code and underline the 2
corrections made by you.
details= {"city": ["Prayagraj", "Patna"], "State": "Uttar Pradesh", "Bihar"]}
46 The following python code contains error(s). Rewrite the correct code and underline the 2
corrections made by you.
info = {"country": "India", "State": "Kerala", "Language":"Malayalam"}
print(values().info)

47 The following python code is trying to print all vowel characters in a given string. Rewrite the 2
correct code and underline the corrections made by you.
sub1="computer science"
sub2=""
for i in range(sub1):
if i ='aeiou':
sub2=sub2+str(i)

print(sub2)

48 The following python code contains error(s).Underline the error in code: 2

s1 = 'Python world"
s1[8] = 'W'
print(upper(s1))
print(isupper(s1))

FINDING OUTPUT(s) BASED QUESTIONS

49 Evaluate the following expression: 2


a) 15 % 11 + 2 ** 3 ** 2 * 2
b) Not True and False or True

50 What will be the output of the following ………………. 1


float("7.5" + "7")

51 Predict the output of the following code: 3


m="[email protected]"
for i in range(0,len(str)):
if(str[i].isupper()):
m=m+str[i].lower()
elif str[i].islower():
m=m+str[i].upper()
else:
if i%2==0:
m=m+str[i-1]
else:
m=m+"#"
print(m)

52 Predict the output of the following code: 3


F1="WoNdERFUL"
F2="StuDenTS"
F3=""
for I in range(0,len(F2)+1):
if F1[I]>='A' and F1[I]<='F':
F3=F3+F1[I]
elif F1[I]>='N' and F1[I]<='Z':
F3=F3+F2[I]
else:
F3=F3+"*"
print(F3)
53 Predict the output of the following code: 1
a=[1,2,3,4,5]
for i in range(1,5):
a[i-1] = a[i]
for i in range(0,5):
print( a[i], end=" ")

a. 55123 b. 51234 c. 23451 d. 23455

54 Predict the output of the following code: 1


for x in range (10,20):
if x%2==0:
continue
print(x)
a. 15 b. 10 c. 19 d. 20

55 What is the output of the following code ? 1


a = [1, 2, 3]
[Link]([4, 5])
print(a)

56 What is the output of the following code ? 1


t = (1, 2, [3, 4])
t[2][0] = 99
print(t)

57 Consider the code below and choose the correct output from the given options: 1
customer = {"cname": "Shiv Prasoon", "country": "India", "mobile": "9956789876"}
print(customer['cname'], " :: ", [Link]('mobile'))
a. Shiv Prasoon 9956789876 b. Shiv Prasoon :: 9956789888
c. Shiv Prasoon :: 9956789876 d. Error

58 Consider the code below and choose the correct output from the given options: 1
customer = {"city": "Prayagraj", "State": "Uttar Pradesh", "capital": "Lucknow"}
print(len(customer))
a. 3 b. 6 c. 7 d. None of the Above

59 Consider the code below and write the correct output : 3


s="EXAM2025@[Link]"
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)

60 Consider the code below and choose the correct output : 3


Msg="CompuTer"
Msg1=""
for i in range(0, len(Msg)):
if Msg[i].isupper():
Msg1=Msg1+Msg[i].lower()
elif i%2==0:
Msg1=Msg1+'*'
else:
Msg1=Msg1+Msg[i].upper()
print(Msg1)

Python Functions
MULTIPLE CHOICE BASED QUESTIONS

1 Which one of the following is an incorrect way of importing the randint() function from the 1
random module?
a. import random b. from random import randint
c. import [Link] d. from random import *

2 The function which is defined by programmer and not available already in program is : 1
a. Library Function b. Customised Function
c. User Defined function d. Predefined Function

3 What will be the output of the following code? 1


def hello(name, message="Welcome"):
print(name, message)
hello("Anjali")
a. Anjali b. Anjali Welcome c. Welcome Anjali d. Error due to missing parameter

4 Which of the following function calls is incorrect if the function is defined as: 1
def calculate(a, b=2, c=3):
return a + b + c
a. calculate(1) b. calculate(1, 4) c. calculate(1, c=4) d. calculate(b=3, 1, c=2)

5 What will be the output of the following code? 1


def greet():
name = "Python"
return name
print(greet())
a. Python b. greet c. name d. Error

6 Which of the following is a correct example of a function with default parameters? 1


a. def add (x, y=5): b. def add (x=5, y):
c. def add (x y=5): d. def add (default x, y):

TRUE / FALSE BASED QUESTIONS

7 State whether the following given statement is True or False : 1


A Python function does not reduce the code redundancy.

8 State whether the following given statement is True or False : 1


random() function never returns an integer value.

9 State whether the following given statement is True or False : 1


In Python, keyword arguments must follow positional arguments in a function call.

10 State whether the following given statement is True or False : 1


A function must always be called with all parameters provided, even if some have default
values.
11 State whether the following given statement is True or False : 1
A variable declared inside a function is called a global variable.

12 State whether the following given statement is True or False : 1


The keyword return is used to send a value back to the function caller.

ASSERTION (A) REASON (R) BASED QUESTIONS

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


a. Both A and R are true, and R is the correct explanation of A.
b. Both A and R are true, but R is not the correct explanation of A.
c. A is true, but R is false.
d. A is false, but R is true.

13 Assertion (A) : A function is a building block of functions. 1


Reason (R) : Library functions are to import and use.

14 Assertion (A) : Importing a module with * makes the size of the program bigger. 1
Reason (R) : Python interpreter imports the module function code in the program before
execution.

15 Assertion (A) : In a Python function call, you can mix positional and keyword arguments. 1
Reason (R) : Python allows keyword arguments to be passed before positional arguments.

16 Assertion (A) : Default arguments in a function must be placed after all non-default 1
arguments.
Reason (R) : Python uses left-to-right evaluation for function arguments.

17 Assertion (A) : A function can return multiple values in Python. 1


Reason (R) : Python allows returning a tuple from a function.

18 Assertion (A) : Global variables can be accessed inside functions. 1


Reason (R) : Any variable inside a function is considered global by default.

ERROR FINDING BASED QUESTIONS

19 Rewrite the following code in python after removing all syntax error(s). Underline each 2
correction done in the code.
DEF calculate_sum(numbers)
sum = 0
for number in numbers:
sum = number
return Sum
print(call calculate_sum([1, 2, 3, 4, 5]))

20 Rewrite the following code in python after removing all syntax error(s). Underline each 2
correction done in the code.
def greet(name)
message = "Hello, " + name
return message
def farewell(name):
return "Goodbye " + name
print(greet(123)
print(farewell(456)
greet("John"

21 Identify the error in the following function definition or call: 1


def show(msg="Hello", name):
print(name, msg)
show("Ravi")

22 Identify the error in the function call: 1


def display(name, age=18):
print(name, age)
display(age=20, "Karan")

23 The following python code contains error(s). Rewrite the correct code and underline the 2
corrections made by you
def fun(a, b=3, c) :
Return a + b + c
x = fun (10, 20)
print(x)

24 The following python code contains error(s). Rewrite the correct code and underline the 2
corrections made by you
DEF test ( ) :
x=x+1
return x
print(x)
test ( )

FINDING OUTPUT(s) BASED QUESTIONS

25 What will be the output of the following code ? 3


def calculate_total(price, quantity=1, discount=0):
total = price * quantity
total -= total * (discount / 100)
return total
print(calculate_total(100))
print(calculate_total(100, 2))
print(calculate_total(100, 2, 10))

26 Predict the output : 3


def combine(a, b, sep=" "):
return str(a) + sep + str(b)
def wrapper():
print(combine("Hello", "World"))
print(combine("Python", "Programming", sep=" - "))
print(combine(10, 20, sep=":"))
wrapper()

27 What will be the output of the following code? 1


def info(name, grade="A", city="Delhi"):
print(name, grade, city)
info("Nina", city="Mumbai")

28 What will be printed ? 1


def func(x, y=5, z=10):
print("x:", x, "y:", y, "z:", z)
func(3, z=20)
FILE HANDLING
1 Mark Question
1. A CSV file named [Link] contains the following data: 1
RollNo, Name, Class, Marks
101, Riya, 12, 89
102, Aarav, 12, 76
103, Isha, 12, 94
104, Kabir, 12, 67

A student writes the following code:

import csv
with open('[Link]', 'r') as f:
reader = [Link](f)
next(reader)
for row in reader:
if int(row[3]) > 80:
print(row[1],end=’,’)

What will be the output of the code?


a. Riya, Aarav, Isha,
b. Riya, Isha,
c. Isha, Kabir,
d. Aarav, Kabir,
2. If row[3] represents marks as a string from a CSV file, which is the correct way to compare 1
it numerically?

a. if int(row[3]) > 50:


b. if row[3] > 50:
c. if float(row) > 50:
d. if row > 50:
3. Correct syntax of writing single row in a csv file using writer object 1
a. [Link](["Pencil","25"])
b. [Link](["Pencil","25"])
c. [Link](["Pencil","25"])
d. [Link](["Pencil","25"])
4. Predict the output of following code : 1
import csv
f = open("[Link]","w",newline="")
w = [Link](f)
[Link]([11,22,33])
[Link]()

f = open("[Link]","r")
r = [Link](f)
for x in r:
print(x[0]+x[1])

a. 33 b. 55 c. error d. 1122

5. Ms. Priyanka is trying to find out the output of the following code. Help her to find the 1
correct output of the code:
with open("[Link]", "w") as f:
[Link](["Line1\n", "Line2\n", "Line3\n"])
with open("[Link]") as f:
print([Link]())

a. Line1 b. ['Line1\n'] c. Line1\n d. Line2

6. Consider this code & find the output: 1

with open("[Link]", "w") as f:


[Link]("ABCDEF")

with open("[Link]", "r") as f:


[Link](3)
print([Link](2))

a. AB b. CD c. DE d. EF
7. What will be the output of following code? 1

with open("[Link]", "w") as f:


[Link]("Python\nRocks")

with open("[Link]", "r") as f:


for line in f:
print([Link]())

a. Python b. Python
Rocks
c. Python\nRocks d. ['Python', 'Rocks']
8. What will be the output of the code below? 1
with open("[Link]", "w") as f:
[Link]("12345")

with open("[Link]", "r") as f:


print([Link](3))
print([Link](3))
a. 12345 b. 123 c. 123 d. 1
123 45 2

9. Which of the following statement opens a binary file [Link] in write mode and writes 1
data from a list
lst1 = [1,2,3,4]

a. with open('[Link]', 'wb') as myfile:


[Link](myfile, lst1)
b. with open('[Link]', 'wb+') as myfile:
[Link](myfile, lst1)
c. with open('[Link]', 'ab') as myfile:
[Link](myfile, lst1)
d. with open('[Link]', 'wb') as myfile:
[Link](lst1 , myfile)
10. Which of the following commands is used to open a binary file “c:\[Link]” in append- 1
mode?
a. outfile= open(“c:/temp. dat”, “ab”)
b. outfile = open(“c:\temp. dat”, “wb+”)
c. outfile = open(“c:\temp. dat”, “ab”)
d. outfile = open(“c:\\temp. dat”, “r+b”)
11. What are the binary files used for? 1
a. To store ascii text
b. It is used to store data in the form of bytes.
c. To look folder good
d. None of these
12. Which of the following functions changes the position of file pointer and 1
returns its new position?
[Link]() [Link]() [Link]() [Link]()
13. 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)
Following questions are Assertion (A) and Reason (R) based questions. Mark
the correct choice as:
a. Both A and R are true, and R is the correct explanation of A
b. Both A and R are true, but R is not the correct explanation of A
c. A is true, but R is false
d. A is false, but R is true
14. Assertion (A): While writing data into a CSV file using [Link](), each
row must be passed as a list or tuple.
Reason (R): The writerow() method of [Link] class takes a single string
as input and writes it directly to the CSV file.
15. Assertion (A): The [Link] object in Python returns each row of a CSV file as a
list.
Reason (R): Each row read by [Link] can be accessed using a for loop.
16. Assertion (A): In Python, a binary file must be opened using mode "rb" and "wb"
for reading and writing respectively.
Reason (R): Binary files store data as text, which is compatible with standard
input/output functions like print().
17. Assertion (A): Opening a file in 'a' mode raises an error if the file does not
exist.
Reason (R): The 'a' mode also allows appending to existing files.
18. Assertion (A): [Link](0) can be used to re-read a file from the beginning.
Reason (R): seek() moves the file pointer to a specified location.
19. Assertion (A): Binary files store all data in text format.
Reasoning (R): Binary files data remain in its original type.
20. Assertion (A): Using the 'with' statement to open a file is considered best practice.
Reason (R): It ensures the file is automatically closed, even if an error occurs.
ANSWER KEY XII CS File Handling
1. b. Riya, Isha,

2. a. if int(row[3]) > 50:

3. c. [Link](["Pencil","25"])

4. d. 1122

5. a. Line1

6. c. DE

7. a. Python
Rocks

8. c. 123

45

9. d. with open('[Link]', 'wb') as myfile:

[Link](lst1 , myfile)

10. a. outfile = open(“c:/temp. dat”, “ab”)

11. b. It is used to store data in the form of bytes.

12. [Link]()

13. a. file_object.seek(offset [, reference_point])

14. c. A is true, but R is false

15. a. Both A and R are true, and R is the correct explanation of A

16. a. Both A and R are true, and R is the correct explanation of A

17. d. A is false, but R is true

18. a. Both A and R are true, and R is the correct explanation of A

19. d. A is false, but R is true

20. a. Both A and R are true, and R is the correct explanation of A


File Handling (Part B)
2 Marks Question
1. Differentiate between rb+ and wb+ file modes in Python. 2

2. How are text files different from binary files in case of delimiter ? 2

3. Following code is written to display the total number of words present in the file 2
from a text file “[Link]”. Write statement 1 and 2 to complete the code.

def countwords():
s = open("[Link]","r")
f = [Link]()
__________________statement 1
count = 0
_______________statement 2
count = count + 1
print ("Total number of words:", count)
4. Write a function to display those lines which start with the letter “G” from the text 2
file “[Link]” Write statement 1 and statement 2 to complete the code.

def count_lines( ):
c=0
_____________________statement 1
line = [Link]()
for w in line:
_______________statement 2
print(w)
[Link]()
5. Fill in the blank : 2
a) ___________ is a process of storing data into files and allows to performs
various tasks such as read, write, append, search and modify in files.
b) The transfer of data from program to memory (RAM) to permanent storage
device (hard disk) and vice versa are known as __________.
6. Write a Python program to create a CSV file named [Link] and store data of 2
3 students (Name, Age, Class).
7. Write a program to read [Link] using DictReader and print names only. 2

8. Differentiate between writerow() and writerows()? 2

9. Differentiate between CSV file and Text file in case retrieval of records from 2
output file?
3 Marks Question
10. Write a function that counts and display the number of 5 letter words in a text file 3
“[Link]“
11. Write a program to count the number of students in [Link] (excluding 3
header).
12. Write a program to read [Link] and display students older than 17. 3

13. Write a program to search for a student by name in [Link]? 3

14. A Binary file, [Link] has the following structure: 3


{MNO:[MNAME, MTYPE]}
Where
MNO – Movie Number
MNAME – Movie Name
MTYPE is Movie Type
Write a user defined function, findType(mtype), that accepts mtype
as parameter and displays all the records from the binary file
[Link], that have the value of Movie Type as mtype.
15. Write a method/function COUNTLINES_ET() in python to read lines from a text 3
file [Link], and COUNT those lines which are starting either with ‘E’ and
starting with ‘T’ respectively. And display the Total count separately.
4 Marks Question
16. Consider a file, [Link], containing records of the following 4
structure:
[SportName, TeamName, No_Players]
Write a function, CountRecord(),that count the number of records in the file.
Write a function, copyData(), that reads contents from the file [Link] and
copies the records with Sport name as “Cricket”to the file named [Link],
The function should return the total number of records copied to the file
[Link].
17. Aman is a Python programmer. He has written a code and created a binary file 4
[Link] with employeeid, ename and salary. The file contains 10 [Link] now
has to update a record based on the employee id entered by the user and update the
salary. The updated record is then to be written in the file [Link]. The records
which are not to be updated also have to be written to the file [Link]. If the
employee id is not found, an appropriate message should to be displayed. As a
Python expert, help him to complete the following code based on the requirement
given above:
import _______ #Statement 1
def update_data():
rec={}
fin=open("[Link]","rb")
fout=open("_____________") #Statement 2
found=False
eid=int(input("Enter employee id to update their salary :: "))
while True:
try:
rec=______________ #Statement 3
if rec["Employee id"]==eid:
found=True
rec["Salary"]=int(input("Enter new salary:: "))
pickle.____________ #Statement 4
else:
[Link](rec,fout)
except:
break
if found==True:
print("The salary of employee id ",eid," has been updated.")
else:
print("No employee with such id is not found")
[Link]()
[Link]()
(i) Which module should be imported in the program? (Statement 1)
(ii) Write the correct statement required to open a temporary file named
[Link]. (Statement 2)
(iii) Which statement should Aman fill in Statement 3 to read the data from the
binary file, [Link] ?
(iv) Write Statement 4 to write the updated data in the file, [Link]?
18. A binary file “[Link]” has structure as [account_no, cust_name,balance]. 4
i. Write a user-defined function addfile( ) and add a record to [Link].
ii. Create a user-defined function CountRec( ) to count and return the number
of customers whose balance amount is more than 100000
5 Marks Question
19. A binary file “[Link]” has structure (rollno, name, marks). 5
(i) Write a function in Python add_record() to input data for a record and add
to [Link].
(ii) Write a function in python Search_record() to search a record from binary
file “[Link]” on the basis of roll number.
20. Amaira’s teacher asked her to count the no. of times words ‘he’ and ‘she’ comes in 5
a text file “[Link]”. She wrote the code, but got confused in few statements. Help
her complete the following code.
f=open("[Link]", “___”) #Statement-1
data=f._____ #Statement-2
data=data.________ #Statement-3
c=0
c1=0
for ch in data:
ch = ch._______ #Statement-4
if ch=="HE" :
c=c+1
elif ch=="SHE":
c1+=1
print("No of She",c1)
print("No of he",c)
f._______ #Statement-5

i) Which of the following modes to be used in Statement-1while opening the file?


a. W b. r c. a d.w+
ii) What should come in statement-2 to read all the contents of the file as a single
string?
a. read() b. readline() c. readlines() d. load()
iii) Which function should come in Statement-3 to get a list of words?
a. getlist() b. splitstr() c. split() d. getword()
iv) Which function should be used in Statement-4 to convert the string in
uppercase?
a. toupper() b. ToUpper() c. uppercase() d. upper()
v) What should be written in Statement-5 to close the file?
a. close(‘[Link]’) b. close() c. end() [Link](f)

Solutions Case based questions

Data Files

1 rb+ mode: 2
• Opens a file for both reading and writing in binary format.
• The file must already exist; otherwise, an error occurs.
• The file pointer is placed at the beginning of the file.
• Existing content is preserved, and writing will overwrite from the current
file pointer position.
wb+ mode:
• Opens a file for both reading and writing in binary format.
• If the file exists, it is truncated (emptied); otherwise, a new file is created.
• The file pointer is placed at the beginning of the file.
• Any existing content is lost, and writing starts from the beginning of the
file.

2 Text Files: 2
• Store data as a sequence of characters (like ASCII or Unicode).
• Each line is terminated by a special character (EOL), typically a
newline character (\n).
• These delimiters are used to separate lines of text, allowing for easy
reading and writing of textual data.
Binary Files:
• Store data as a stream of bytes, without character encoding or line
delimiters.
• There is no concept of "lines" in the same way as in text files.
• Binary files are typically used for storing data that is not intended
for human readability, such as images, audio, or program code.

3 import pickle 2+2


def countRecord():
f=open('[Link]','rb')
count=0
while True:
try:
record=[Link](f)
count=count+1
except EOFError:
break
[Link]()
def copyData():
f1=open('[Link]','rb')
f2=open('[Link]','wb')
while True:
try:
record=[Link](f1)
if record[0]==’Cricket’:
[Link](record,f2)
except EOFError:
break
[Link]()
[Link]()
4 import pickle 3
def findType(mtype):
f=open('[Link]','rb')
while True:
try:
record=[Link](f)
for y in record:
if record[y][1]==mtype:
print(record)
except EOFError:
break
[Link]()
5 i)pickle #Statement-1 4
ii)fout=open(‘[Link]’,’wb’) #Statement-2
iii)rec=[Link](fin) #Statement-3
iv) [Link](rec,fout) Statement-4
6 def add_record(): 2+3
f=open('[Link]','ab')
roll=int(input('enter roll number'))
name=input('enter name')
marks=int(input('enter marks'))
record=[roll,name,marks]
[Link](record,f)
[Link]()
def Searchrecord():
f=open('[Link]','rb')
r=int(input(‘enter roll number to be searched’))
found=0
try:
while True:
record=[Link](f)
if record[0]==r:
print(‘record found’,record)
found=1
except EOFError:
if found==0:
print(‘record not found’)
[Link]()
7 def add_file(): 2+2
f=open('[Link]','ab')
acno=int(input('enter account number'))
name=input('enter name')
balance=int(input('enter balance))
record=[ acno,name, balance]
[Link](record,f)
[Link]()

def countRec():
f=open('[Link]','rb')
count=0
while True:
try:
record=[Link](f)
if record[2]>100000:
count=count+1
except EOFError:
break
[Link]()
return count

STACK
1. Stack implementation can be performed using a list in Python. (True / False) 1
2. The top operation does not modify the contents of a stack. (True / False) 1

3. The peek operation refers to accessing/inspecting the top element in the stack (True/False) 1

4. len() method used to find the size of stack. (True /False) 1


5. What is the process of inserting data into a stack called? 1
a. Create b. Insert c. Push d. Evaluate
6. Which pointer is associated with a stack? 1
a. First b. Front c. Rear d. Top
7. Assume a stack has size 10. If a user tries to push a 11th element to a stack, which of the 1
mentioned condition will arise?
a. Underflow b. Overflow c. Crash d. Successful Insertion

8. Which of these is not an application of stack? 1


a. Parenthesis Balancing program b. Evaluating Arithmetic Expressions
c. Reversing Data d. Data Transfer between Process

9. Assertion (A) : A stack is used to reverse a string. 1


Reason (R) : Stack follows Last-In, First-Out (LIFO) order.
Options:
a. Both A and R are true, and R is the correct explanation of A
b. Both A and R are true, but R is not the correct explanation of A
c. A is true, but R is false
d. A is false, but R is true
10. Assertion (A) : Stack allows element addition at one end only. 1
Reason (R) : Stack operations are performed at both end.

11. You have a stack named BooksStack that contains records of books. Each book record is 3
represented as a list containing book_title, author_name, and publication_year.
Write the following user-defined functions in Python to perform the specified operations on
the stack BooksStack:
● push_book(BooksStack, new_book): This function takes the stack BooksStack
and a new book record new_book as arguments and pushes the new book record
onto the stack.
● pop_book(BooksStack): This function pops the topmost book record from the
stack and returns it. If the stack is already empty, the function should display
"Underflow".
● peep(BookStack): This function displays the topmost element of the stack
without deleting it. If the stack is empty, the function should display 'None'.
12. Thushar received a message(string) that has upper case and lower-case alphabet. He want to 3
extract all the upper case letters separately .Help him to do his task by performing the
following user defined function in Python:
a. Push the upper case alphabets in the string into a STACK
b. Pop and display the content of the stack.
For example:
If the message is “All the Best for your Pre-board Examination” The output should be : E P B
A
13. Write a function in Python, Push(EventDetails) where , EventDetails is a dictionary 3
containing the number of persons attending the events–
{EventName : NumberOfPersons}. The function should push the names of those events in the
stack named ‘BigEvents’ which have number of persons greater than 200. Also display the
count of elements pushed o n to the stack.
For example: If the dictionary contains the following data:
EventDetails ={"Marriage":300, "Graduation Party":1500, "Birthday Party":80, "Get
together" :150}
The stack should contain :
Marriage Graduation Party
The output should be:
The count of elements in the stack is 2
14. A list of numbers is used to populate the contents of a stack using a function push(stack, data) 3
where stack is an empty list and data is the list of numbers. The function should push all the
numbers that are even to the stack.
Also write the function pop(stack) that removes and returns the top element of the stack on its
each call.
15. A list contains following record of a student: 3
[student_name, age, hostel]
Write the following user defined functions to perform given operations on the stack named
‘stud_details’:
(i) Push_element() - To Push an object containing name and age of students who live in hostel
“Ganga” to the stack
(ii) Pop_element() - To Pop the objects from the stack and display them. Also, display “Stack
Empty” when there are no elements in the stack.
For example:
If the lists of customer details are:
[“Barsat”,17,”Ganga”]
[“Ruben”, 16,”Kaveri”]
[“Rupesh”,19,”Yamuna”]
The output should be: [“Barsat”,17,”Ganga”]
Stack Empty
16. Write a function in Python PUSH_IN(L), where L is a list of numbers. From this list, push all 3
numbers which are multiple of 3 into a stack which is implemented by using another list.

17. Write a function in Python, Push(KItem),where KItem is a dictionary containing the details of 3
Kitchen items– {Item:price}. The function should push the names of those items in a stack
which have price less than 100. Also display the average price of elements pushed into the
stack.
For example:
If the dictionary contains the following data:
{"Spoons":116,"Knife":50,"Plates":180,"Glass":60}
The stack should contain
Glass
Knife
The output should be:
The average price of an item is 55.0
18. Given a Dictionary Stu_dict containing marks of students for three test-series in the form 3
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 Stu_Stk
(i) Push_elements(Stu_Stk, Stu_dict) : It allows pushing IDs of those students, from the
dictionary Stu_dict into the stack Stu_Stk, who have scored more than or equal to 80
marks in the TS3 Test.
(ii) Pop_elements(Stu_Stk): 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. Call both functions to execute queries.
For example: If the dictionary Stu_dict contains the following data:
Stu_dict ={5:(87,68,89), 10:(57,54,61), 12:(71,67,90), 14:(66,81,80), 18:(80,48,91)}
After executing Push_elements(), Stk_ID should contain
[5,12,14,18]
After executing Pop_elements(),
The output should be:
18
14
12
5
Stack Empty
19. Consider a list named Nums which contains random integers. 3

Write the following user defined functions in Python and perform the specified operations on
a stack named BigNums.

(1)PushBig(): It checks every number from the list Nums and pushes all such numbers which
have 5 or more digits into the stack, BigNums.
(ii) PopBig(): It pops the numbers from the stack, BigNums and displays them. The function
should also display "Stack Empty" when there are no more numbers left in the stack.

For example: If the list Nums contains the following data:

Nums [213,10025,167,254923,14,1297653,31498,386,92765)
Then on execution of PushBig(), the stack BigNums should store:
[10025, 254923, 1297653, 31498, 92765]
And on execution of PopBig (), the following output should be displayed:
92765
31498
1297653
254923
10025
Stack Empty
20. A dictionary, d_city contains the records in the following format: 3
(state:city)
Define the following functions with the given specifications:
(i) push_city (d_city): It takes the dictionary as an argument and pushes all the cities in the
stack CITY whose states are of more than 4 characters.
(ii) pop_city(): This function pops the cities and displays "Stack empty" when there are no
more cities in the stack.
SOLUTION Stack

Answers:
1. Ans. c
2. Ans. d
3. Ans. b
4. Ans. d
5. Ans. a
6. Ans. a
7. Ans. a
8. Ans. a
9. Ans. a
10. Ans. b
11. def push_book(BooksStack, new_book):
[Link](new_book)
def pop_book(BooksStack):
if len(BooksStack) == 0:
print("Underflow")
else:
return [Link]()
def peep(BooksStack):
if len(BooksStack) == 0:
print("None")

else:
print(BooksStack[-1])
return BooksStack[-1]
12. def push_uppercase(stack, message):
for char in message:
if [Link]():
[Link](char)
def pop_and_display(stack):
while stack:
print([Link](), end=' ')
print() # For newline after output
13. def Push(EventDetails):
BigEvents = [] # Stack to hold big event names
for event, persons in [Link]():
if persons > 200:
[Link](event)
# Display the stack
for event in BigEvents:
print(event)
# Display the count
print("The count of elements in the stack is", len(BigEvents))
14. def push(stack, data):
for num in data:
if num % 2 == 0:
[Link](num)
def pop(stack):
if len(stack) == 0:
return None # Or raise an error if preferred
return [Link]()
15. stud_details = [] # Stack initialized
def Push_element(student_list):
if student_list[2] == "Ganga":
stud_details.append(student_list)
def Pop_element():
if not stud_details:
print("Stack Empty")
else:
while stud_details:
print(stud_details.pop())
print("Stack Empty")
16. def PUSH_IN(L):
stack = []
for num in L:
if num % 3 == 0:
[Link](num)
return stack
17. def Push(KItem):
stack = []
total = 0
count = 0
for item, price in [Link]():
if price < 100:
[Link](item)
total += price
count += 1
# Display stack content
for i in stack:
print(i)
# Display average
if count > 0:
average = total / count
print(f"The average price of an item is {average}")
18. def Push_elements(Stu_Stk, Stu_dict):
for Stu_ID, marks in Stu_dict.items():
if marks[2] >= 80: # TS3 is the third test (index 2)
Stu_Stk.append(Stu_ID)
# Function to pop and print all elements from the stack
def Pop_elements(Stu_Stk):
while Stu_Stk:
print(Stu_Stk.pop())
print("Stack Empty")
# Main program
Stu_dict = {
5: (87, 68, 89),
10: (57, 54, 61),
12: (71, 67, 90),
14: (66, 81, 80),
18: (80, 48, 91)
}

Stu_Stk = []
# Perform operations
Push_elements(Stu_Stk, Stu_dict)
Pop_elements(Stu_Stk)
19. # Sample list of random integers
Nums = [213, 10025, 167, 254923, 14, 1297653, 31498, 386, 92765]
# Stack to hold numbers with 5 or more digits
BigNums = []
# Function to push big numbers (5 or more digits) to the stack
def PushBig():
for num in Nums:
if len(str(num)) >= 5:
[Link](num)

# Function to pop and display all elements from the stack


def PopBig():
while BigNums:
print([Link]())
print("Stack Empty")
# Example usage:
PushBig() # Push 5 or more digit numbers into the stack
PopBig() # Pop and display the numbers

20. CITY = [ ]
# Function to push cities where the state has more than 4 characters
def push_city(d_city):
for state, city in d_city.items():
if len(state) > 4:
[Link](city)
# Function to pop cities from the stack
def pop_city():
while CITY:
print([Link]())
print("Stack empty")
TOPIC : COMPUTER NETWORKING

Q. No. Particulars Marks

1. Quick Learn University is setting up its academic blocks at Prayag Nagar and planning to 5×1=5
set up a network. The university has 3 academic blocks and one human resource center
as shown in the diagram below:
As a Network Expert, need to suggest the best network-related solutions for them to
resolve the issues/problems mentioned in questions (i) to (v), keeping the following
parameters in mind :

Prayag Nagar

BUSINESS BLOCK TECHNOLOGY

LAW BLOCK HR CENTRE

Block to Block distance (in metres):

From To Distance
LAW BLOCK BUSINESS 40 m
BLOCK
LAW BLOCK TECHNOLOGY 80 m
BLOCK
LAW BLOCK HR BLOCK 105 m

BUSINESS TECHNOLOGY 30 m
BLOCK BLOCK
BUSINESS HR BLOCK 35 m
BLOCK
TECHNOLOGY HR BLOCK 15 m
BLOCK
Number of Computers in each block is as follows:
Block No. of Computers
LAW BLOCK 15
TECHNOLOGY BLOCK 40
HR CENTRE 115
BUSINESS BLOCK 25

(i). Suggest a cable layout of connection between the blocks.


(ii). Suggest the most suitable place to house the server of the organization with
suitable reason.
(iii). Which device should be placed/installed in each of these blocks to efficiently
connect all the computers within these blocks?
(iv). The university is planning to link its sales counters situated in various parts of the
CITY. Which type of network out of LAN, MAN or WAN will be formed?
(v). (a) Which network topology may be preferred between these blocks?
OR
(b) What type of network (PAN, LAN, MAN, or WAN) will be set up among the
computers connected in Prayag Nagar?

2. Rehaana Medicos Center has set up its new center in Dubai. It has four buildings as 5×1=5
shown in the diagram below:
As a Network Expert, need to suggest the best network-related solutions for them to
resolve the issues/problems mentioned in questions (i) to (v), keeping the following
parameters in mind :

ACCOUNTS RESEARCH LAB

STORE PACKAGING UNIT

Block to Block distance (in meters):


From To Distance
ACCOUNTS RESEARCH LAB 55 m
ACCOUNTS STORE 150 m
STORE PACKAGING UNIT 160 m
PACKAGING UNIT RESEARCH UNIT 60 m
ACCOUNTS PACKAGING UNIT 125 m
STORE RESEARCH UNIT 180 m

Number of Computers in each block is as follows:


Block No. of Computers
ACCOUNTS 25
RESEARCH LAB 100
STORE 15
PACKAGING UNIT 60
(i) Suggest a cable layout of connections between the buildings.
(ii) Suggest the most suitable place (i.e. buildings) to house the server of this
organization.
(iii) Suggest the placement of the Repeater device with justification.
(iv) Suggest a system (hardware/software) to prevent unauthorized access to or from the
network.
(v) (a) Suggest the placement of the Hub/ Switch with justification.
OR
(b) What type of network (PAN, LAN, MAN, or WAN) will be set up among the
computers connected in the above-mentioned diagram?

3. Total-IT Corporation, a Karnataka based IT training company, is planning to set up 5×1=5


training centers in various cities in next 2 years. Their first campus is coming up in
Kodagu district. At Kodagu campus, they are planning to have 3 different blocks, one for
AI, IoT and DS (Data Sciences) each. Each block has number of computers, which are
required to be connected in a network for communication, data and resource sharing as
shown in the diagram below:
KODAGU CAMPUS

IT IoT
COIMBATORE
CAMPUS

DS

Block to Block distance (in metres):

From To Distance
IT DS 28 m
IT IoT 55 m
DS IoT 32 m
KODAGU COIMBATORE 304 km
CAMPUS CAMPUS

Number of Computers in each block is as follows:


Block No. of Computers
IT 75
DS 50
IoT 80

As a Network Expert, need to suggest the best network-related solutions for them to
resolve the issues/problems mentioned in questions (i) to (v), keeping the following
parameters in mind:
(i) Suggest the most appropriate block/location to house the SERVER in the Kodagu
campus (out of the 3 blocks) to get the best and effective connectivity. Justify your
answer.
(ii) Suggest a device/software to be installed in the Kodagu Campus to take care of data
security.
(iii) Suggest the best wired medium and draw the cable layout (Block to Block) to most
efficiently connect various blocks within the Kodagu Campus.
(iv) Suggest the placement of the following devices with appropriate reasons: (a)
Switch/Hub (b) Router
(v) (a) Suggest a protocol that shall be needed to provide Video Conferencing solution
between Kodagu Campus and Coimbatore Campus.
OR
(b) What type of network (PAN, LAN, MAN, or WAN) will be set up among the
computers connected in above mentioned diagram?
4. Future Tech Corporation, a Bihar based IT training and development company, is 5×1=5
planning to set up training centers in various cities in the coming year. Their first center
is coming up in Surajpur district. At Surajpur center, they are planning to have 3 different
blocks - one for Admin, one for Training and one for Development. Each block has
number of computers, which are required to be connected in a network for
communication, data and resource sharing as shown in the diagram below:
As a Network Expert, need to suggest the best network-related solutions for them to
resolve the issues/problems mentioned in questions (i) to (v), keeping the following
parameters in mind :

Surajpur Centre
Development
block
Raipur
Training
block Admin block

Block to Block distance (in meters):


From To Distance
DEVELOPMENT ADMIN 28 m
DEVELOPMENT TRAINING 105 m
ADMIN TRAINING 32 m
SURAJPUR COIMBATORE 340 km
CAMPUS CAMPUS

Number of Computers in each block is as follows:


Block No. of Computers
DEVELOPMENT 90
ADMIN 40
TRAINING 50

(i) Suggest the most appropriate block/location to house the SERVER in the Surajpur
center (out of the 3 blocks) to get the best and effective connectivity. Justify your answer.
(ii) Suggest why should a firewall be installed at the Surajpur Center?
(iii) Suggest the best wired medium and draw the cable layout (Block to Block) to most
efficiently connect various blocks within the Surajpur Center.
(iv) Suggest the placement of the following devices with appropriate reasons: a)
Switch/Hub b) Router
(v) (a) Suggest the best possible way to provide wireless connectivity between Surajpur
Center and Raipur Center.
OR
(b) What type of network (PAN, LAN, MAN, or WAN) will be set up among the
computers connected in above mentioned diagram?
5. Ravya Industries has set up its new center at Kaka Nagar for its office and web-based 5×1=5
activities. The company compound has 4 buildings
as shown in the diagram below:
As a Network Expert, need to suggest the best network-related solutions for them to
resolve the issues/problems mentioned in questions (i) to (v), keeping the following
parameters in mind :

RAJ BUILDING FAZZ BUILDING

HARSH BUILDING
JAZZ BUILDING

Block to Block distance (in meters):


From To Distance
HARSH BUILDING RAJ 50 m
BUILDING
RAJ BUILDING FAZZ BUILDING 60 m
FAZZ BUILDING JAZZ BUILDING 25 m
JAZZ BUILDING HARSH 170 m
BUILDING
HARSH BUILDING FAZZ BUILDING 125 m
RAJ BUILDING JAZZ BUILDING 90 m
Number of Computers in each block is as follows:
Block No. of Computers
HARSH 15
RAJ 150
FAZZ 15
JAZZ 25
(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 appropriate reasons: a. Hub /
Switch b. Repeater
(iv) The organization is planning to link its sale counter situated in various parts of the
same city, which type of network out of LAN, MAN or WAN will be formed? Justify
your answer.
(v) (a) Suggest a device/software to be installed in the Campus to take care of data
security.
OR
(b) What type of network (PAN, LAN, MAN, or WAN) will be set up among the
computers connected in above mentioned diagram?
NETWORKING
[Link]. MCQs Marks

1. Your school has four branches spread across the city. A computer network 1
created by connecting the computers of all the school branches, is a.
[Link] [Link] [Link] [Link]
2. A user gets an email asking to click a link and enter bank details. This is an 1
example of:
a. Spam b. Phishing c. Hacking d. Malware
3. The protocol used to transfer files over the Internet is: 1
a. FTP b. HTTP c. SMTP d. IP
A set of rules that governs data communication is knowni. as: 1
a. Topology b. Protocol c. Router d. Gateway
4. Which of the following is not a type of computer network? 1
a. LAN b. MAN c. WAN d. SANITIZE
5. Which device is used to connect different networks together? 1
a. Switch b. Router c. Hub [Link]
6. A user is watching a video on YouTube. Which protocol is primarily responsible 1
for data transmission?
a. FTP b. SMTP c. TCP/IP d. POP3
7. In which topology is each computer connected to a central hub? 1
a. Ring b. Bus c. Star d. Mesh
8. Which protocol is used to transfer web pages? 1
a. FTP b. HTTP c. SMTP d. IP
9. Which protocol is used to send emails? 1
a. HTTP b. FTP c. SMTP d. SNMP
10. Which of the following is used for wireless communication? 1
a. Ethernet b. Bluetooth c. USB d. HDMI
11. Which of the following is not a web browser? 1
a. Chrome b. Firefox c. Windows d. Safari
FULL FORMS Questions
13. What does ISP stand for? 1
14. What is the full form of URL? 1
15. What is the full form of Wi-Fi? 1
Assertion and Reasoning Questions
Directions: For each question, select 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 but Reason is NOT the correct
explanation of Assertion.
(C) Assertion is true but Reason is false.
(D) Assertion is false but Reason is true.
16. Assertion (A): Star topology is more reliable than bus topology. 1
Reason (R): In star topology, each device is connected to a central hub, reducing
dependence on a single cable.
17. Assertion (A): In ring topology, data moves in multiple directions. 1
Reason (R): Ring topology has multiple paths between nodes.
18. Assertion (A): SMTP is used to receive emails. 1
Reason (R): SMTP is a sending protocol, not a receiving protocol.
19. Assertion (A): Switch operates at the Data Link Layer of the OSI model. 1
Reason (R): Switch uses MAC addresses to forward data.
20. Assertion (A): In LAN, devices are spread over a large geographical area. 1
Reason (R): LAN is designed for short distances like within a building.
[Link]. Answers Marks
1. c. MAN 1
2. b. Phishing 1
3. a. FTP 1
4. b. Protocol 1
5. d. SANITIZE 1
6. b. Router 1
7. c. TCP/IP 1
8. c. Star 1
9. b. HTTP 1
10. c. SMTP 1
11. b. Bluetooth 1
12. c. Windows 1
FULL FORMS
13. Internet Service Provider 1
14. URL: Uniform Resource Locator 1
15. Wireless Fidelity 1
Assertion and Reasoning Questions
16. A) Both A and R are true and R is the correct explanation of A. 1
17. D) Assertion is false but Reason is true. 1
(In Ring topology, data moves in only one direction unless it’s a dual ring!)
18. D) Assertion is false but Reason is true. 1
19. A) Both A and R are true and R is the correct explanation of A. 1
20. D) Assertion is false but Reason is true. 1
Database & SQL
Q. No. Question Marks

a. Both A & R are True and R is correct explanation of A


b. Both A & R are True and R is not correct explanation of A
c. A is True and R is False.
d. A is False and R is True.
Answer Question from 1 to 5.
1 Assertion(A): In SQL, aggregate function avg() calculates the average value on 1
a set of values and produces a single result.
Reason(R): The aggregate function are used to perform some fundamentals
arithmetic tasks such as min(), max(), sum() etc
2 Assertion(A): Primary key is a key which ensures unique records in a key. 1
Reason(R): A key is a attribute which retrieves a single record from the table.
3 Assertion(A): The SQL keyword like is used with wild card characters. 1
Reason(R): ‘_’ and ‘%’ are two wild card characters used with LIKE clause.
4 Assertion(A): DISTINCT clause must be used in an SQL statement to eliminate 1
duplicate rows.
Reason(R): DISTINCT only works with numeric data type only.
5 Assertion(A): A database constraints can be added or removed any time in/from 1
the database tables.
Reason(R): Alter table command is used to change the structure of the table.
6 Identify DDL and DML Commands. 1
CREATE, UPDATE, ALTER and DELETE
Consider the following table and write sql command from QN 7 to 11.

Employee

empid Empname Salary

101 ALOK GUPTA 5000

102 ANITA KANNOJIA Null

103 SANGEETA 4900

104 B L MARODIA 11000

7 Insert a record into the table employee. 1


(105, PANKAJ,5100)
a. insert into table employee values (105,’PANKAJ’,5100);
b. insert into table emp (empid, empname, salary) values
(105,’PANKAJ’,5100);
c. insert into employee (empid, empname, salary) values
(105,’PANKAJ’,5100);
d. All of above
8 Update null values in column salary with 5000. 1
a. update employee set salary = 5000;
b. update employee set salary = 5000 where salary = null;
c. update employee set salary = 5000 where salary is null;
d. None of these

9 Show the structure of the table employee. 1

a. desc employee; b. show employee; c. display employee; d. desc emp;

10 Delete the record of employee with empid 101. 1


a. drop employee where empid = 101;
b. delete from employee where empid = 101;
c. delete from employee;
d. alter table employee drop empid = 101;
11 Change the data type of empname to varchar(50). 1
a. alter table employee modify empname varchar(50);
b. alter table employee change empname varchar(50);
c. alter table employee add empname varchar(50);
d. alter table employee edit empname varchar(50);
Consider the following table and write SQL command from QN 12 to 15 and
output from 16 to 17.

TECH_COURSE

CNAME FEES TID


Animation 12000 101

Cad 15000 Null

Dca 10000 102

Dtp 9000 104

Mobile app 18000 101

Digital marketing 16000 103

12 Display course name with fees between 10000 to 20000. 1


a. select cname from tech_course where fees between 10000 and 20000;
b. select cname from tech_course where fees between 10000 or 20000;
c. select * from tech_course where fees between 10000 and 20000;
d. select cname from tech_course where fees between 10000 to 20000;
13 Count the number of Records. 1
a. select count(cname) from tech_course;
b. select count(*) from tech_course;
c. select cname, count(*) from tech_course;
d. None of these
14 Display the candidate names in ascending order. 1
a. select * from tech_course;
b. select * from tech_course order by cname;
c. select cname from tech_course;
d. select cname from tech_course order by cname;
15 Show the unique TID. 1
a. select distinct tid from tech_course;
b. select unique tid from tech_course;
c. select primary key tid from tech_course;
d. show distinct tid from tech_course

16 SELECT AVG(FEES) FROM TECH_COURSE WHERE FEES BETWEEN 1


15000 AND 17000;

a. AVG(FEES) b. 15500
15500
c. AVG(FEES) d. All of these
15500.00
17 SELECT TID, COUNT(*), MIN(FEES) FROM TECH_COURSE GROUP BY 1
TID HAVING COUNT(TID) >1;

a. TID COUNT(*) MIN(FEES) b. TID COUNT(*) MIN(FEES)


101 2 12000 101 2 12000
102 1 10000
103 1 16000
104 1 9000
c. TID COUNT(*) MIN(FEES) d. All of these
102 1 10000
103 1 16000
104 1 9000
18 Foreign Key ensures________. 1
a. Referential Integrity b. Reduction of Data Redundancy
c. Data Security d. All of these
19 Cardinality is the total number of __________ and Degree is Total number of 1
_________.
a. rows, columns b. columns, rows c. non null values d. None of these
20 How many primary keys exist in a table? 1
[Link] b. One c. Two d. Three

Answer Key
1 A 6 DDL – CREATE, ALTER 11 A 16 C

DML- UPDATE, DELETE

2 A 7 C 12 A 17 B

3 A 8 C 13 B 18 A

4 C 9 A 14 D 19 A

5 B 1 B 15 A 20 B
0

[Link]. MARKS

1 Write SQL Command for (a) to (d) 4

TABLE: GRADUATE_STUDENTS
S.N NAME STIPEND SUBJECT AVERAGE DIV
O
1 KARAN 400 PHYSICS 68 I
2 DIWAK 450 COMP Sc 68 I
AR
3 DIVYA 300 CHEMISTRY 62 I
4 REKHA 350 PHYSICS 63 I
5 ARJUN 500 MATHS 70 I
6 SABINA 400 CHEMISTRY 55 II
7 JOHN 250 PHYSICS 64 I
8 ROBERT 450 MATHS 68 I
9 RUBINA 500 COMP Sc 62 I
10 VIKAS 400 MATHS 57 II
a. List the names of those students who have obtained DIV I sorted by NAME.
[Link] a report, listing NAME, STIPEND, SUBJECT and amount of stipend
received in a year assuming that the STIPEND is paid every month.
c. To count the number of students who are either PHYSICS or COMPUTER SC
graduates.
[Link] insert a new row in the Graduate_students table: 11,”KAJOL”, 300, “computer sc”,
75, 1
2 Consider the table ORDERS as given below 4

TABLE- ORDER

O_Id C_Name Product Quantity Price


1001 Jitendra Laptop 1 12000
1002 Mustafa Smartphone 2 10000
1003 Dhwani Headphone 1 1500
1004 Alice Smartphone 1 9000
1005 David Tablet NULL 7000
A) Write the SQL commands :
a. To display the total Quantity for each Product, excluding Products with total Quantity
less than 5.
b. To display the ORDERS table sorted by total price in descending order.
c. To display the distinct customer names from the ORDERS table.
d. To display the sum of the Price of all the orders for which the quantity is NULL
OR
B) Write the output:
a. SELECT C_Name, SUM(Quantity) AS Total_Quantity
FROM ORDERS GROUP BY C_Name;
b. SELECT * FROM ORDERS WHERE Product LIKE '%phone%';
c. SELECT O_Id, C_Name, Product, Quantity, Price
FROM ORDERS WHERE Price BETWEEN 1500 AND 12000;
d. SELECT MAX(Price) FROM ORDERS;
3 Mayank creates a table RESULT with a set of records to maintain the marks secured by 4
students in sub1, sub2, sub3 and their GRADE. After creation of the table, he has entered
data of 8 students in the table.
Table : RESULT

ROLL_N SNAME sub1 sub sub3 GRADE


O 2
101 KIRAN 366 410 402 I
102 NAYAN 300 350 325 I
103 ISHIKA 400 410 415 I
104 RENU 350 357 415 I
105 ARPITA 100 75 178 IV
106 SABRINA 100 205 217 II
107 NEELIMA 470 450 471 I
103 ISHIKA 400 410 415 I
Write the statements to:

a. Add a column REMARKS in the table with datatype as varchar with 50 characters.
b. Display the name, sub1, sub2, sub3 whose grade is IV.
c. Insert the following record into the table
Roll No- 108, Name- Aaditi, sub1- 470, sub2-444, sub3- 475, Grade– I.
d. Increase the sub2 marks of the students by 3% whose name begins with ‘N’.
4 Write SQL queries for (a) to (d) which are based on the tables TRANSPORT AND 4
JOURNEY.
Table: TRANSPORT
CODE VTYPE PERKM
101 VOLVO BUS 160
102 AC DELUXE BUS 150
103 ORDINARY BUS 90
105 SUV 40
104 CAR 20
Table: JOURNEY
NO NAME TDATE KM CO NOP
DE
101 Janish Kin 2015-11-13 200 101 32
103 Vedika 2016-04-21 100 103 45
Sahai
105 Tarun Ram 2016-03-23 350 102 42
102 John Fen 2016-02-13 90 102 40
107 Ahmed 2015-01-10 75 104 2
Khan
104 Raveena 2016-05-28 80 105 4

a. To display NO, NAME, TDATE from the table TRANSPORT in descending order
of NO.
b. To display the NAME of all the travellers from the table TRANSPORT who
are travelling by vehicle with code 101 or 102.
c. To display the NO and NAME of those travellers from the table TRAANSPORT
who travelled between ‘2015-12-31’ and ‘2015-04-01’.
d. To display all the details from table TRANSPORT for the travellers, who
have travelled distance more than 100 KM in ascending order of NOP?
5 Give output of the following queries as per given table(s): 4

TABLE- WORKER

WID WNAME JOB SALAR DNO


Y

1001 RAHUL SHARMA CLERK 15000 D03

1002 MUKESH VYAS ELECTRICIAN 11000 D01

1003 SURESH FITTER 9000 D02

1004 ANKUR GUARD 8000 D01

1001 RAHUL SHARMA CLERK 15000 D03

TABLE- DEPT

DNO DNAME LOC MANAGER


D01 PRODUCTION GROUND FLOOR D K JAIN

D02 ACCOUNTS 1ST FLOOR S ARORA

D03 SECURITY 1ST FLOOR R K SINGH

a. SELECT DISTINCT JOB FROM WORKER;


b. SELECT DNAME, LOC FROM DEPT WHERE SALARY > 10000;
c. SELECT [Link], [Link] FROM WORKER AS W, DEPT
AS D WHERE [Link] = [Link];
d. SELECT WNAME FROM WORKER WHERE WNAME LIKE 'R%';
6 (A) Consider the following tables SCHOOL and ADMIN and answer the following 4
questions:
TABLE- SCHOOL

CO TEACHE SUBJECT DOJ PERIO EXPERIEN


DE R DS CE
1001 RAVI ENGLISH 12/03/20 24 10
00
1009 PRIYA PHYSICS 03/09/19 26 12
98
1203 LISA ENGLISH 09/04/20 27 5
00
1045 YASH MATHS 24/08/20 24 15
RAJ 00
1123 GAGAN PHYSICS 16/07/19 28 3
99
1167 HARISH CHEMISTR 19/10/19 27 5
Y 99
1215 UMESH PHYSICS 11/05/19 22 16
98
TABLE : ADMIN

CODE GENDER DESIGNATION

1001 MALE VICE PRINCIPAL

1009 FEMALE COORDINATOR

1203 FEMALE COORDINATOR

1045 MALE HOD

1123 MALE SENIOR TEACHER

1167 MALE SENIOR TEACHER

1215 MALE HOD

Give the output of the following sql queries:


a. SELECT DESIGNATION, COUNT(*) FROM ADMIN GROUP BY
DESIGNATION HAVING COUNT(*)<2;
b. SELECT MAX(EXPERIENCE) FROM SCHOOL;
c. SELECT TEACHER FROM SCHOOL WHERE EXPERIENCE >12 ORDER BY
TEACHER;
d. SELECT COUNT(*), GENDER FROM ADMIN GROUP BY GENDER;
7 Consider the following tables – BANK_ACCOUNT and Branch: 1+4
BANK_ACCOUNT

ACode Name Type


A01 Amit Savings
A02 Parth Current
A03 Mira Current
BRANCH

ACode City
A01 Delhi
A02 Jaipur
A01 Ajmer
a. What will be the output of the following statement?
SELECT * FROM BANK_ACCOUNT NATURAL JOIN BRANCH;

(B) Give the output of the following sql statements as per table given above-
TABLE: SPORTS

Student Cl Name Game1 Grad Game2 Grad


No ass e1 e2
10 7 Sammer Cricket B Swimming A
11 8 Sujit Tennis A Skating C
12 7 Kamal Swimmin B Football B
g
13 7 Venna Tennis C Tennis A
14 9 Archana Basketball A Cricket A
15 10 Arpit Cricket A Athletics C

a. SELECT COUNT(*) FROM SPORTS;


b. SELECT DISTINCT Class FROM SPORTS;
c. SELECT MAX(Class) FROM SPORTS;
d. SELECT COUNT(*) FROM SPORTS GROUP BY Game1;
8 (a) consider the following tables STUDENT and FEE and answer the following 4
questions
TABLE – STUDENT
RollNo Name Class Section Marks

101 Anjali 12 A 85

102 Rohan 12 B 92

103 Meera 12 A 78
104 Aditya 12 C 88

105 Arun 12 C 89

TABLE- FEE
RollNo AmountPaid PaymentDate

101 25000 2024-04-15

102 30000 2024-04-16

104 28000 2024-04-18

a. Display the names of all students along with the amount of fee they have paid.
b. Display the names of students who paid the fee between '2024-04-15' and '2024-04-
17'.
c. List names of students who belong to section 'a' and have paid more than 25000.
d. List the names of students who have not paid the fee yet.

9 consider the following tables EMPLOYEE and PROJECT and answer the following 5
questions
EMPLOYEE
EmpID Name Department Salary

201 Anil HR 50000

202 Seema Finance 60000

203 Ravi IT 55000

204 Pooja HR 52000

205 Karan IT 58000

PROJECT
ProjectID EmpID Project Name HoursWorked ProjectID

P1 201 Recruitment App 35 P1

P2 202 Payroll System 40 P2

P3 203 Inventory Mgmt 30 P3

P4 201 Employee Portal 20 P4

P5 205 Website Redesign 25 P5

a. Display all employees along with the projects they are working on.
b. List names of employees who are working on more than one project.
c. Show the total hours worked by each employee.
d. List all employees and their project names, including those who are not working on
any project.
e. Display names and departments of employees who have worked more than 30 hours
in any project.
10 consider the following tables EMPLOYEE and DEPARTMENT and answer the 4
following questions-
EMPLOYEE
EmpID Name Salary DeptID

1 Aman 50000 101

2 Priya 60000 102

3 Rakesh 45000 101

4 Sneha 70000 103

DEPARTMENT
DeptID DeptName Location DeptID

101 Sales Delhi 101

102 HR Mumbai 102

a. Show all employee details along with department name.


b. Show the List employees who work in Delhi.
c. Display the names and salaries of employees earning the highest salary.
d. Show average salary for each department
Answer
1 4
a. SELECT NAME from GRADUATE_STUDENT where DIV = ‘I’ order by NAME;
b. SELECT NAME,STIPEND,SUBJECT, STIPEND*12 from
GRADUATE_STUDENT;
c. SELECT SUBJECT,COUNT(*) from GRADUATE_STUDENT
d. group by SUBJECT having SUBJECT=’PHYISCS’ or SUBJECT=’COMPUTER SC’;
e. INSERT INTO GRADUATE_STUDENT values(11,’KAJOL’,300,’COMPUTER
SC’,75,1);
2 Ans : (A)
a. SELECT Product, SUM(Quantity) AS Total_Quantity 4
FROM ORDERS
GROUP BY Product
HAVING SUM(Quantity) >= 5;
b. SELECT O_Id, C_Name, Product, Quantity, Price
FROM ORDERS
ORDER BY Price DESC;
c. SELECT DISTINCT C_Name
FROM ORDERS;

d. SELECT SUM(Price) AS
Total_Price_Null_Quantity
FROM ORDERS
WHERE Quantity IS NULL;

OR
(B)
a. C_Name Total Quantity
Jitendra 1
Mustafa 2
Dhwani 1
Alice 1
David NULL
b.
O_Id C_Name Product Quantity Price
1002 Mustafa Smartphone 2 10000
1004 Alice Smartphone 1 9000

c.

O_Id C_Name Product Quantity Price


1001 Jitendra Laptop 1 12000
1002 Mustafa Smartphone 2 10000
1003 Dhwani Headphone 1 1500
1004 Alice Smartphone 1 9000

4
3 a. New Degree: 8 New Cardinality: 5
b. SELECT name,sub1,sub2,sub3
FROM RESULT
WHERE GRADE=’IV’,
c. A) INSERT INTO RESULT VALUES (108, ‘Aadit’, 470, 444, 475, ‘I’);
d. UPDATE RESULT SET SEM2=SEM2+ (SEM2*0.03)
WHERE SNAME LIKE “N%”;
OR (Option for part iii only)
a. DELETE FROM RESULT WHERE DIV=’IV’;

ALTER TABLE RESULT ADD (REMARKS VARCHAR(50));


4 4
a. SELECT NO, NAME, TDATE FROM TRAVEL ORDER BY NO DESC;
b. SELECT NAME FROM TRAVEL WHERE CODE=‘101’ OR CODE=’102’; or
c. SELECT NAME FROM TRAVEL WHERE CODE IN (‘101’,’102’)
d. SELECT NO, NAME from TRAVEL WHERE TDATE >= ‘2015−04−01’ AND
TDATE <= ‘2015−12−31’;

OR

SELECT NO, NAME from TRAVEL WHERE TDATE BETWEEN ‘2015-04-01’ AND
‘2015-12-31’;

5 a. JOB 4
CLERK
ELECTRICIA
N FITTER
GUARD
b.

DNAME LOC
PRODUCTION GROUND FLOOR
SECURITY 1ST FLOOR
c.
WNAME MANAGER
RAHUL SHARMA R KSINGH
MUKESH VYAS D K JAIN
SURESH S ARORA
ANKUR D K JAIN
d. WNAME

RAHUL SHARMA

6 a. Vice principal 01 4
b. 16
c. UMESH YASHRAJ
d.
5 Male
2 Female
3
7 (A) a.
ACode Name Type City
A01 Amit Savings Delhi
A01 Amit Savings Ajm
er
A02 Parth Current Jaip
ur
(B)-a. 6
b.
Class
7
8
9
10

c.10
d.
Game1 Count(*)
Cricket 2
Tennis 2
Swimming 1
8 a. SELECT STUDENT. Name, [Link] 4
FROM STUDENT
LEFT JOIN FEE ON [Link] = [Link];
b. SELECT STUDENT. Name
FROM STUDENT
INNER JOIN FEE ON [Link] = [Link]
WHERE [Link] BETWEEN '2024-04-15' AND '2024-04-17';
c. SELECT STUDENT. Name
FROM STUDENT
INNER JOIN FEE ON [Link] = [Link]
WHERE STUDENT. Section = 'A' AND [Link] > 25000
d. SELECT STUDENT. Name
FROM STUDENT
LEFT JOIN FEE ON [Link] = [Link]
WHERE [Link] IS NULL;
a. SELECT [Link], [Link] 5
9 FROM EMPLOYEE
INNER JOIN PROJECT ON [Link] = [Link];
b. SELECT EMPLOYEE. Name, COUNT([Link]) AS ProjectCount
FROM EMPLOYEE
INNER JOIN PROJECT ON [Link] = [Link]
GROUP BY EMPLOYEE. Name
HAVING COUNT([Link]) > 1;
c. SELECT EMPLOYEE. Name, SUM([Link]) AS TotalHours
FROM EMPLOYEE
INNER JOIN PROJECT ON [Link] = [Link]
GROUP BY [Link];
d. SELECT [Link], [Link]
FROM EMPLOYEE
LEFT JOIN PROJECT ON [Link] = [Link];
d. SELECT [Link], [Link]
FROM EMPLOYEE
INNER JOIN PROJECT ON [Link] = [Link]
WHERE [Link] > 30;
10 a. SELECT [Link], [Link], [Link], 4
[Link]
FROM Employee
JOIN Department ON [Link] = [Link];
b. SELECT [Link]
FROM Employee
JOIN Department ON [Link] = [Link]
WHERE Department. Location = 'Delhi';
c. SELECT Name, Salary
FROM Employee
WHERE Salary = (SELECT MAX(Salary) FROM Employee);
d. SELECT [Link], AVG([Link]) AS AvgSalary
FROM Employee
JOIN Department ON [Link] = [Link]
GROUP BY [Link];

Python-MySQL Connectivity
The fetchone() method returns results as a dictionary. (Find True or False) 1
(Q1

Q2 MySQL connector must be installed using pip install mysql. (Find True or False) 1

Q3 The …………… method is used to execute SQL queries in Python 1

Q4 To prevent SQL injection, always use ……………instead of string formatting. 1

Q5 Which cursor function is not used to send query to connection? 1


a. query() b. send() c. run() d. All
Q6 Identify the correct statement to create cursor: 1
import [Link] as msq
con = [Link]( #Connection String ) # Assuming all parameter required as passed
mycursor = ________
a. [Link]() [Link]() [Link].open_cursor() d. con.get_cursor()
Q7 Which function is used to fetch only one records from cursor? 1
a. fetch() b. fetchone() c. fetchmany() d. fetchall()
Q8 Which function is used to establish a connection between Python and MySQL? 1
[Link]() b. cursor() c. execute() d. commit()
Q9 Which function of connection is used to check whether connection to mysql is 1
successfully done or not?
import [Link] as msq
con = [Link]( #Connection String ) # Assuming all parameter required as passed
if :
print(“Connected!”)
else:
print(“ Error! Not Connected”)
a. [Link]() b. [Link]() c. con.is_connected() d . con.is_connect()
Q10. Assertion (A): Parameterized queries prevent SQL injection. 1
Reason (R): They separate SQL code from user input.
a. Both A and R are true, and R explains A.
b. Both A and R are true, but R does not explain A.
c. A is true but R is false.
d. A is false R is True

Answers : COMPETENCY BASED QUESTION: Python-MySQL Connectivity


Ans1 False

Ans2 False

Ans3 execute().

Ans4 Parameterized queries (e.g., %s placeholders)

Ans5 d All

Ans6 a [Link]()

Ans7 b. fetchone()

Ans8 a) connect()

Ans9 c. con.is_connected()

Ans10 a

Python MySQL Interface and Exception handling


Q. Question Marks
No.
1. State True or False 1
A finally block is always executed, regardless of whether an exception occurred or not.
2. State True or False 1
The except: block without specifying an exception type will catch all exceptions.
3. State whether the following statement is True or False: The finally block in Python is 1
executed only if no exception occurs in the try block.
4. How many except statements can a try-except block have? 1
a. zero b. one c. more than one d. more than zero
5. An exception is said to be caught when 1
a. Error encountered and exception object is created
b. Runtime system searches for appropriate exception handler
c. Code that is designed to handle exception is executed
d. None of these
6. What is the purpose of the cursor() method in Python’s database interaction? 1
a. To create a new database b. To execute SQL queries
c. To close the database connection d. To fetch all records from a table
7. What is the correct order to perform database operations in Python 1
a. Create connection -> Create cursor -> Execute query -> Commit (if
needed) -> close connection
b. Create cursor -> Create connection -> Execute query -> Commit (if
needed) -> close connection
c. Execute query ->Create cursor -> Create connection -> Commit (if
needed) -> close connection
d. None of these
Q9 and Q10 are Assertion(A) and Reason(R) based questions. Mark
the correct choice as:
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
9 Assertion : Exception handling handles all types of error and exceptions. 1
Reasoning : Exception handling is responsible for handling anomalous situations
during the execution of a program.
10 Assertion :A database cursor receives all the records retrieved as per the query. 1
Reason : A resultset refers to the records in the database cursor and allows
processing of individual records in it.
11 The code given below inserts the following record in the table Student: 3
RollNo – integer
Name – string
Clas – 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.
The details (RollNo, Name, Clas and Marks) are to be
accepted from the user.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the command that inserts the record in
the table Student.
Statement 3- to add the record permanently in the database
import [Link] as mysql
def sql_data():
con1=[Link](host="localhost",user="root", password="tiger",
database="school")
mycursor=_________________ #Statement 1
rno=int(input("Enter Roll Number :: "))
name=input("Enter name :: ")
clas=int(input("Enter class :: "))
marks=int(input("Enter Marks :: "))
querry="insert into student values
({},'{}',{},{})".format(rno,name,clas,marks)
______________________ #Statement 2
______________________ # Statement 3
print("Data Added successfully")
12 The code given below reads the following record from the table named student and 3
displays only those records who have marks greater than 75:
RollNo – integer
Name – string
Clas – 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
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 [Link] as mysql
def sql_data():
con1=[Link](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 data:
print(i)
print()
13 Sartaj has created a table named Student in MYSQL database, SCHOOL: 3
rno (Roll number )- integer
name (Name) - string
DOB (Date of birth) – Date
Fee – float
Note the following to establish connectivity between Python and MySQL:
Username - root
Password – tiger
Host – localhost
Sartaj, now wants to display the records of students whose fee is more than 5000. Help
Sartaj to write the program in Python.
14 Kabir wants to write a program in Python to insert the following record in the table 3
named Student in MYSQL database, SCHOOL:
rno (Roll number )- integer
name (Name) - string
DOB (Date of birth) – Date
Fee – float
Note the following to establish connectivity between Python and MySQL:
Username - root
Password - tiger
Host – localhost
The values of fields rno, name, DOB and fee has to be accepted from the user. Help
Kabir to write the program in Python.
15 A table, named STATIONERY, in ITEMDB database, has the following structure:
Field Type
itemNo Int(11)
itemName Varchar(20)
Price Float
Qty Int(11)

Write the following Python function to perform the specified operation: 4


AddAndDisplay(): To input details of an item and store it in the table STATIONERY.
The function should then retrieve and display all records from the STATIONERY table
where the Price is greater than 120.
Assume the following for Python-Database connectivity:
Host: localhost, User: root, Password: Pencil
16 Rahim wants to write a program in Python to insert the following record in the table 4
named Bank_Account in MySQL database, Bank : ·
Accno – integer
· Cname – string
· Atype – string
· Amount – float
Note the following to establish connectivity between Python and MySQL : ·
Username – admin
· Password – root
· Host – localhost
The values of fields Accno, Cname, Atype and Amount have to be accepted from the
user. Help Rahim to write the program in Python.
17 Sunil wants to write a program in Python to update the quantity to 20 of the records 4
whose item code is 111 in the table named shop in MySQL database named Keeper:
Item_code integer
Item_name String
Qty Integer
Price Integer
Consider the following to establish connectivity between Python and MySQL:
Username admin
Password 123456
Host localhost
18 Sumit wants to write a code in Python to display all the details of the passengers from 4
the table flight in MySQL database , Travel. The tables contains the following
attributes:
F_code String
F_name String
Source String
Destination String
Consider the following to eastablish connectivity between Python and MySQL:
Username admin
Password 123456
Host localhost
19 The table Bookshop in MySQL contains the following attributes: 3
B_code Integer
B_name String
Qty Integer
Price Integer
Note the following to eastablish connectivity between Python and MySQL on a
‘localhost’:
username is ‘shop’
password is ‘Book’
The table exists in a MySQL database named Bstore
The code given below updates the records from the table Bookshop in MySQL.
Statement 1 – to form the cursor object.
Statement 2 – to execute the query that updates the Qty to 20 of the records whose
B_code is 105 in the table.
Statement 3 – to make the changes permanent in the database.
import [Link] as mysql
def update_book ( ):
mydb=[Link] (host=”localhost”, user=”shop”, passwd=”Book”,
database=”Bstore”)
mycursor = _______________________ #Statement 1
qry= “update Bookshop set Qty=20 where B_code=105”
________________________ #Statement 2
________________________ #Statement 3

20 Consider the Student table of SCHOOL database with following structure. 3


Rollno Integer
name String
Dob Date
Fee float
The following credentials may be used to connect Python MySQL :
Username root
Password tiger
Host localhost
Write a Python program to display the records of students whose fees is less than
2000.
Answer-
Python MySQL Interface and Exception handling
Section -B
1. True
2. True
3. False
4. d) more than zero
5. a)
6. c. Assertion is True but Reason is False
7. a. Assertion and Reason are True. Reason is correct explanation of Assertion
8. a)
9. Assertion is False and Reasoning is True
10. d)
11. Statement 1 : [Link]()
Statement 2 : [Link](querry)
Statement 3 : [Link]()

12. Statement 1 : [Link]()


Statement 2 : [Link] (“select * from student where marks > 75”)
Statement 3 : [Link]()

13. import [Link] as mysql


Con=[Link](host = ‘localhost’, username=’root’, passwd=’tiger’,
database=’SCHOOL’)
Mycursor=[Link]()
Query=”select * from Student where Fee > 5000”
Data=[Link]()
for r in Data:
print(r)
14. import [Link] as mysql
Con=[Link](host = ‘localhost’, username=’root’, passwd=’tiger’,
database=’SCHOOL’)
Mycursor=[Link]()
rno=int(input(“Enter roll no “))
name=input(“Enter name”)
dob=input(“Enter date of birth “)
fee=float(input(“Enter fee”))
Query=”insert into student values ({},{},{},{}).format(rno,name,dob,fee)”
[Link](query)
[Link]()
15. import [Link] as mysql
def AddAndDisplay():
Con=[Link](host = ‘localhost’, username=’root’, passwd=’Pencil’,
database=’SCHOOL’)
Mycursor=[Link]()
itemno=int(input(“Enter item no “))
itemname=input(“Enter item name”)
price=float(input(“Enter price “))
Qty=int(input(“Enter quantity”))
Query=”insert into STATIONARY values
({},’{}’,{},{}).format(itemno,itemname,price,Qty)”
[Link](query)
Query=”select * from STATIONARY where price > 120”
[Link](Query)
for r in [Link]():
print(r)
16. import [Link] as mysql
Con=[Link](host = ‘localhost’, username=’admin’, passwd=’root’,
database=’Bank’)
Mycursor=[Link]()
accno=int(input(“Enter account no “))
cname=input(“Enter name”)
atype=input(“Enter account type “)
amount=float(input(“Enter amount”))
Query=”insert into student values ({},’{}’,{},{}).format(accno,cname,atype,amount)”
[Link](query)
[Link]()

17. import [Link] as mysql


Con=[Link](host = ‘localhost’, username=’admin’, passwd=’123456’,
database=’Keeper’)
Mycursor=[Link]()
Query=”update shop set qty=20 where item_code=111)”
[Link](query)
[Link]()
18. import [Link] as mysql
Con=[Link](host = ‘localhost’, username=’admin’, passwd=’123456’,
database=’Travel’)
Mycursor=[Link]()
Query=”select * from flight ”
[Link](query)
for r in [Link]():
print(r)
[Link]()

19. Statement 1 : [Link]()


Statement 2 : [Link](mycursor)
Statement 3 : [Link]()

20. import [Link] as mysql


Con=[Link](host = ‘localhost’, username=’root’, passwd=’tiger’,
database=’SCHOOL’)
Mycursor=[Link]()
Query=”select * from student where fee < 2000”
[Link](query)
Data=[Link]()
for r in Data:
print(r)
[Link]()

You might also like