Grade 12 CS Practice Material 2023-24

Download as pdf or txt
Download as pdf or txt
You are on page 1of 217

TABLE OF CONTENTS

S.
Name of the Chapters Page.No
No

1. REVISION TOUR - I 1

2. REVISION TOUR - II 24

3. WORKING WITH FUNCTIONS 64

4. FILE HANDLING 90

5. INTRODUCTION TO STACK 120

6. DATABASE AND ITS CONCEPTS 130

7. INTRODUCTION TO SQL AND ITS COMMANDS 139

8. INTERFACING PYTHON WITH MySQL 174

9. INTRODUCTION TO COMPUTER NETWORKS 188

10. EXCEPTION HANDLING 208


CHAPTER 1 – REVISION TOUR - I
PRACTICE QUESTIONS
STATE TRUE OR FALSE
1. Python is a low level language.
2. Python is a free source language.
3. Python converts low level language to high level language.
4. Python is a compiler.
5. Python is case sensitive language.
6. Python was named after famous BBC comedy show
namely Monty Python’s Flying Circus.
7. Python is not a Cross-platform Language.
8. All identifiers in Python are in lower case.
9. An identifier is a user defined name given to a variable or
a constant in a program.
10. Python does not allows same variable to hold different data
literals / data types.
11. Operators with the same precedence are evaluated in right to
left manner.
12. Interactive mode is used when a user wants to run a single line
or one block of code.
13. Script mode is used when the user is working with more than
one single code or a block of code.
14. In Python, a variable may be assigned a value of one type, and
then later assigned a value of a different type.
15. In Python, a variable must be declared before it is assigned a
value.
16. Variable names can be of any length.
17. the complement operator inverts the value of each bit of
the operand
18. print(int(6>7-6-7*4) ) will print boolean value.
19. Logical operator not has highest precedence among all the
logical operators.
20. “is” is a membership operator in python.
21. Following code will produce True as output:
x=10>5>1 and -3<-2<-1
print(x)
22. The value of expression 3/5*(7-2) and 3/(5*(7-2)) is same.
23. The expression 4**3**2 is evaluated as (4**3)**2
24. () have higher precedence that any other operator.
25. print() always inserts a newline after each output.
26. >>> 2*4+36/2-9
In the above expression 36/2 will be evaluated first by python.

APPAN RAJ D PGT- CS/IP 1


27. When syntax error is encountered, Python displays the
name of the error and a small description about the error.
28. "In Python, data type of a variable depends on its value"
29. “Python identifiers are dynamically typed.”
30. (i) -88.0 is the output of the print(3-10**2+99/11)
(ii) range( ) is also a module function
31. Comments in Python begin with a "$" symbol.
32. In a Python program, if a break statement is given in a nested
loop, it terminates the execution of all loops in one go.
33. The math.ceil() function in Python returns the smallest integer
greater than or equal to a given number.
34. In Python, the break statement is used to terminate the entire
program.
35. In Python, the math.pow () function is equivalent to the **
operator for exponentiation.
ASSERTION & REASON
1. A:It is interpreted language.
R: Python programs are executed by an interpreter.
2. A: Python is portable and platform independent.
R:Python program can run on various operating systems
and hardware platforms.
3. A: Python is case-sensitive.
R:Python does not use indentation for blocks and
nested blocks.
4. A: Python program is executed line by line.
R: Python is compiled language.
5. A: Python is an object oriented language
R: Python is a cross platform language
6. A: Python is case-sensitive.
R: NUMBER and number are not same in Python
7. A: Python is a high-level object-oriented programming
language.
R: It can run on different platforms like Windows,Linux, Unix,
and Macintosh.
8. A: An identifier cannot have the same name as of
a keyword.
R: Python interpreter will not be able to differentiate
Between a keyword and an identifier having the
same name as of a keyword.
9. >>>print('Good'+' Morning') #Output :Goodmorning
A : Incorrect Output
R: There is a syntax error

APPAN RAJ D PGT- CS/IP 2


10. A: In Python comments are interpreted and are
shown on the output screen.
R: Single line comments in python starts with #
character
11. A: The math.pow(2,4)gives the output: 16.0
R: The math.pow () method receives two float arguments,
raise the first to the second and return the result.
12. A: Python uses the concept of L-value and R-value,
that is derived from the typical mode of
evaluation on the left and right side of an
assignment statement
R: name = ‘Raj’
In the above code the value ‘Raj’ is fetched (Rvalue)
and stored in the variable named – name (L value)
13. A:>>> print(type((3 + 33)<-(-4 - 44)))
R : As output is True which is a boolean value
14. num1=input("enter a number")
print(num1+2)
A: The above code will give error message when executed.
R: input() returns a string datatype. We cannot add
string data type with a numeric datatype. So,
performing arithmetic operation on it will result in
error.
15. var1=10
var1="hello"
A: The above code is invalid. We cannot assign adata of
different data type to an existing variable.
R: Python supports implicit type casting. So it is
possible to assign a data of different data type to
an existing variable.
16. A: You will get an error if you use double quotes inside a
string that is surrounded by double quotes:
txt = "We are the so-called "Vikings" from the north."
R: To fix this problem, use the escape character \":
17. A: Variables whose values can be changed after they are
created and assigned are called immutable.
R: When an attempt is made to update the value of an
immutable variable, the old variable is destroyed and a
new variable is created by the same name in memory.
18. A: To do arithmetic python uses arithmetic
(+,*,//,**, -, / ,%)
R: Each of these operators is a binary operator

APPAN RAJ D PGT- CS/IP 3


19. A: The relational operator determine the relation among
different operand
R: It returns the Boolean value
20. A:not has a lower priority than non-Boolean operators
R: So not a==b is interpreted as not(a==b)
21. A:The ** operators is evaluated from right to left
R:All operators are left associative
22. A: for the given expression
S1='1'
S2= 1
S3= S1==S2 #value of v3 is False
R: Integer value cannot be compared with string
value.
23. A: following given expression will result into
TypeError
S="XYZ"
v1=[2]
str3=S*v1
R: operator ‘*’ cannot be applied on string
24. A: int(‘A’) The above statement will result into error
R: ‘A’ is not recognised by Python
25. A: a=9, b=int(9.2) Both a and b have same value
R: b is converted to integer explicitly
26. A: In an expression, associativity is the solution to
the order of evaluation of those operators which
clashes due to same precedence.
R: Operators in an expression may have equal
precedence due to which the order of evaluation
cannot be decided just by precedence.
27. A: An example of an infinite loop is : while(1):
R: A loop that continues repeating without aterminating
(ending) condition is an infinite loop.
28. A: The statements within the body of for loopare executed
till the range of values is exhausted.
R: for loop cannot be nested.

APPAN RAJ D PGT- CS/IP 4


29. Analyse the following code:
for i in range(1,4):
for j in range (1,i+1):
print(j,end=’ ’)
print()
A: output is
1
12
123
R: Here, range function will generate value 1,2,3 in the outer
loop and the inner loop will run for each value of “i” used
in outer loop.
30. A: Python provides two looping constructs for and while.
The for is a counting loop and while is a conditional
loop.
R: The while is a conditional loop as we check the
condition first, if it is satisfied then only we can get
inside the while. In case of for it depends upon the
counting statement of index.
31. A: for loop in Python makes the loop easy to calculate
factorial of a number
R: While loop is an indefinite iteration that is used when
a loop repeats unknown number of times and end
when some condition is met.
32. A: range(0,5) will produce list as [0,1,2,3,4]
R: These are the numbers in arithmetic progression (a.p.)
that begins with lower limit 0 and goes up till upper
limit -1.
33. A: To print the sum of following series 1 + 3 + 5…….n. Ravi
used the range function in for loop as follows:
range(1,n+1,2) # 3 parameters
R: In range function first parameter is start value, second
parameter is stop value & the third parameter is step
value.
34. x=0
for i in range(3,9,3):
x = x * 10 + i
print(x)
A: The output of the above code will be 9.
R: The loop will run for 2 times.

APPAN RAJ D PGT- CS/IP 5


35. for i in range(1, 6):
for j in range(1, i):
print("*", end=" ")
print()
A: In a nested loop, the inner loop must terminate
before the outer loop.
R: The above program will throw an error.
36. A: break statement terminates the loop.
R: The else clause of a Python loop executes when the
loop continues normally.
37. A: break statement always appears only in a nested loop.
R: If the break statement is inside the inner loop then it
will terminate the inner loop only.
38. A: break statement terminates the loop it lies within.
R: continue statement forces the next iteration of the loop
to take place, skipping any code in between.
OBJECTIVE TYPE QUESTIONS (MCQ)
1. Python uses ____ to convert its instructions into machine
language.
(a)Interpreter (b)Compiler
(c)Both of the above (d)None of the above
2. Who developed the Python language?
(a) Zim Den (b)Wick van Rossum
(c)Guido Van Rossum (d)NieneStom
3. IDLE stands for __________
(a) Integrated Development Learning
(b) Integrated Development Learning Environment
(c) Intelligent Development Learning Environment
(d) None of the above
4. Python interpreter executes ……………………….statement
(Command) at a time.
(a) Two (b) Three (c) One (d) All command
5. Which of the following is not the feature of python language?
(a) Python is proprietary software.
(b )Python is not case-sensitive.
(c) Python uses brackets for blocks and nested blocks.
(d) All of the above
6. By default, the Python scripts are saved with_____ extension.
(a) .pyp (b).pys (c).py (d)None of the above
7. What is the maximum possible length of an identifier in
python?
(a) 16 (b) 32 (c) 64 (d) None of these

APPAN RAJ D PGT- CS/IP 6


8. Which of the following is not considered a valid identifier in
Python?
(a) Two2 (b) _main (c) hello_rsp1 (d) 2 hundred
9. Which of the following is not a component of the math module in
Python?
(a) ceil() (b) mean() (c) fabs() (d) pi
10. >>> print("I" + "am" + "in" + "school") display
(a) I am in school (b)I Am In School
(c)Iaminschool (d)iaminschool
11. Which of the following is an invalid identifier to be used in
Python?
(a) per%marks (b) _for (c) While (d) true
12. Which of the following statement is correctsyntactically?
(a) print(“Hello” , sep == ‘@’ , end =' ')
(b)print(“Hello” , sep = ‘@’ , end = ' ')
(c)Print(“Hello” , sep = ‘@’ , end = ' ')
(d)print(“Hello” , sep = ‘@’ , end = ' '
13. Which of the following is not a keyword in python?
(a) eval (b) assert (c) nonlocal (d) pass
14. Which of the following is not a valid declaration?
(a) S=12 (b) V="J" (c) F=32.4 (d) H=0254
15. Evaluate the following expression:
>>> not True or not False and False
16. Predict the output of the following code snippet:
for letter in "Python":
if letter =="h":
continue
print(letter,end="")
(a)P (b) Py (c) Python (d) Pyton
17. Which of the following properly expresses the precedence of
operators (using parentheses) in the following expression:
5*3 > 10 and 4+6==11
a) ((5*3) > 10) and ((4+6) == 11))
b) (5*(3 > 10)) and (4 + (6 == 11))
c) ((((5*3) > 10) and 4)+6) == 11
d) ((5*3) > (10 and (4+6))) == 11
18. All keywords in python except True,False and None are in
____?
(a) Lower case (b) Upper case
(c) Capitalized (d) None of the above
19. What is the output of the following :
print(23//9%3, 2**2**2)
(a) 7 64 (b) 2 16 (c) 7 8 (d) 2 64

APPAN RAJ D PGT- CS/IP 7


20. Give the output for the following code:
for i in range(1,10,3):
print(i,sep=”-”,end=”*”)
(a) 1-4-7* (b) 1-4-7-10* (c) 1*4*7* (d) 1*4*7*10
21. Find the invalid identifier from the following
(a) sub%marks (b) age (c) _subname_ (d) subject1
22. Which of the following expressions is an example of type casting?
(a) 4.0+float(6) (b) 5.3+6.3 (c) 5.0+3 (d) None of these
23. Which of the following is an invalid identifier?
(a) CS_class_XII (b) csclass12
(c) _csclass12 (d) 12CS
24. Predict the output of the following code:
>>>import random
>>>random.randint(3.5,7)
(a) Error (b) Any integer between 3.5 and 7, including 7
(c) Any integer between 3.5 and 7, excluding 7
(d) The integer closest to the mean of 3.5 and 7
25. The input() function always returns a value of ……..type.
a) Integer b) float c) string d) Complex
26. To include non-graphic characters in python, which of the
following is used?
(a) Special Literals (b) Boolean Literals
(c) Escape Character Sequence (c) Special Literal – None
27. Which of the following cannot be a variable name?
(a) _init_ (b) in (c) it (d) on
28. Which is valid keyword?
(a) Int (b) WHILE (c) While (d) if
29. Predict the output of the following:
(i) >>>print(10 or 40) (ii) >>> print(22.0//5)
30. Identify the output of the following Python statements.
ans=0
for i in range (11,20,1):
if i %2==0:
ans+=4
else:
ans-=2
print(ans)
(a) 8 (b) 6 (c)10 (d) None
31. Which of the following is an invalid operator in Python?
(a) - (b) //= (c) in (d) =%
32. Which of the following operators is the correct option for
power(a,b)?
(a) a^b (b) a **b (c) a ^^b (d) a^*b

APPAN RAJ D PGT- CS/IP 8


33. Which of the characters is used in python to make a single
line comment?
(a)/ (b) // (c) # (d)!
34. Which of the following is not a core data type in python?
(a)List (b) Dictionary (c) Tuple (d) Class
35. How many times does the following while loop get executed?
K=5
L=36
while K<=L:
K+=6
(a) 4 (b) 5 (c) 6. (d) 7
36. Which of the following functions generates an integer?
(a) uniform( ) (b) randint( )
(c) random( ) (d) None of the above
37. Identify the output of the following Python statements.
b=1
for a in range(1, 10, 2):
b += a + 5
print(b)
(a) 59 (b) 51 (c) 36 (d) 39
38. What will be the output of the following code?
import random
X=[100,75,10,125]
Go=random.randint(0,3)
for i in range(Go):
print(X[i],"$$",end=" ")
(a) 100$$75$$10$$ (b) 75$$10$$125$$
(c) 75$$10$$ (d) 10$$125$$100
39. Which of the following has the highest precedence in
python?
(a)Exponential (b) Addition (c) Parenthesis (d) Division
40. What is math.factorial (4.0)?
(a) 20 (b) 24 (c) 16 (d) 64
41. Identify the invalid variable name from the following.
Adhar@Number, none, 70outofseventy, mutable
42. Which of the following belongs to complex datatype
(a) -12+2k (b) 4.0 (c) 3+4J (d) -2.05I
43. None is a special data type with a single value. It is used to
signify the absence of value in a situation
(a) TRUE (b) FALSE (c) NONE (d) NULL
44. If x=3.123, then int(x) will give ?
(a) 3.1 (b) 0 (c) 1 (d) 3
45. To execute the following code in Python, Which module need to be
imported? >>>print(_______.mean([1,2,3])

APPAN RAJ D PGT- CS/IP 9


46. Find the invalid identifier from the following
(a) Marks@12 (b) string_12 (c)_bonus (d)First_Name
47. Find the invalid identifier from the following
(a) KS_Jpr (b) false (c) 3rdPlace (d) _rank
48. Find the valid identifier from the following:
(a) Tot$balance (b) TRUE (c) 4thdata (d) break
49. Which one of the following is False regarding data types in
Python?
(a) In python, explicit data type conversion ispossible
(b) Mutable data types are those that can bechanged.
(c) Immutable data types are those that cannot bechanged.
(d) None of the above
50. Which statement will give the output as : True from the following
:
a) >>>not -5 b) >>>not 5 c) >>>not 0 d) >>>not(5-1)
51. Evaluate the following expression: 1+(2-3)*4**5//6
(a) -171 (b) 172 (c) -170 (d) 170
52. The correct output of the given expression is:
True and not False or False
(a) False (b) True (c) None (d) Null
53. What will the following expression be evaluated to in Python?
print(6*3 / 4**2//5-8)
(a) -10 (b) 8.0 (c) 10.0 (d) -8.0
54. Evaluate the following expressions:
>>>(not True) and False or True
55. >>> 16 // (4 + 2) * 5 + 2**3 * 4
(a) 42 (b) 46 (c) 18 (d) 32
56. Evaluate the following expression:
True and False or Not True
(a) True (b) False (c) NONE (d) NULL
57. The below given expression will evaluate to
22//5+2**2**3%5
(a)5 (b) 10 (c) 15 (d) 20
58. Which of the following is not a valid identifier name in Python?
a) First_Name b) _Area c) 2nd_num d) While
59. Evaluate the following Python expression
print(12*(3%4)//2+6)
(a)12 (b)24 (c) 10 (d) 14
60. Give the output of the following code:
>>>import math
>>>math.ceil(1.03)+math.floor(1.03)
a) 3 b) -3.0 c) 3.0 d) None of the above
61. >>>5 == True and not 0 or False
(a) True (b) False (c) NONE (d) NULL
APPAN RAJ D PGT- CS/IP 10
62. Predict the output of the following:
from math import*
A=5.6
print(floor(A),ceil(A))
(a) 5 6 (b) 6 5 (c) -5 -6 (d) -6 -5
63. Predict the output of the following code:
import math
print(math.fabs(-10))
(a) Error (b) -10 (c) -10.0 (d) 10.0
64. Which of the following function is used to know the data type of a
variable in Python?
(a) datatype() (b) typeof() (c) type() (d) vartype()
65. Identify the invalid Python statement from the following.
(a) _b=1 (b) b1= 1 (c) b_=1 (d) 1 = _b
66. A=100
B=A
Following the execution of above statements, python has
Created how many objects and how many references?
(a) One object Two reference (b) One object One reference
(c) Two object Two reference (d) Two object One reference
67. What is the output of the following code?
a,b=8/4/2, 8/(4/2)
print(a,b)
(a) Syntax error (b) 1.0,4.0 (c) 4.0,4.0 (d) 4,4
68. Predict output for following code
v1= True
v2=1
print(v1==v2, v1 is v2)
(a) True False (b) False True
(c) True True (d) False False
69. Find output for following given program
a=10
b=20
c=1
print(a !=b and not c)
(a) 10 (b) 20 (c) True (d) False

APPAN RAJ D PGT- CS/IP 11


70. Find output of following given program :
str1_ = "Aeiou"
str2_ = "Machine learning has no alternative"
for i in str1_:
if i not in str2_:
print(i,end='')
(a) Au (b) ou (c) Syntax Error (d) value Error
71. Find output for following given code:
a=12
print(not(a>=0 and a<=10))
(a) True (b) False (c) 0 (d)1
72. What will be value of diff?
c1='A'
c2='a'
diff= ord(c1)-ord(c2)
print(diff)
(a) Error : unsupported operator ‘-’ (b) 32
(c)-32 (d)0
73. What will be the output after the following statements?
x = 27
y=9 (a) 26 11 (b) 25 11
while x < 30 and y < 15: (c) 30 12 (d) 26 10
x=x+1
y=y+1
print(x,y)
74. What output following program will produce
v1='1'
v2= 1
v3=v1==v2
(a) Type Error (b) Value Error
(c)True will be assigned to v3 (d)False will be assigned to v3
75. Which of the following operators has highest precedence:
+,-,/,*,%,<<,>>,( ),**
(a) ** (b) ( ) (c) % (d)-
76. Which of the following results in an error?
(a) float(‘12’) (b) int(‘12’) (c) float(’12.5’) (d) int(‘12.5’)
77. Which of the following is an invalid statement?
(a) xyz=1,000,000 (b) x y z = 100 200 300
(c) x,y,z=100,200,300 (d) x=y=z=1,000,000
78. Which of following is not a decision-making statement?
(a) if-elif statement (b) for statement
(c) if -else statement (d) if statement

APPAN RAJ D PGT- CS/IP 12


79. In a Python program, a control structure:
(a) Defines program-specific data structures
(b) Directs the order of execution of the statements in the
program
(c) Dictates what happens before the program starts and
after it terminates
(d) None of the above
80. Which one of the following is a valid Python if statement?
(a) if a>=9: (b) if (a>=9) (c) if (a=>9) (d) if a>=9
81. if 4+5==10:
print("TRUE")
else:
print("false")
print ("True")
(a) False (b) True (c) false (d) None of these
82. Predict the output of the following code:
X=3
if x>2 or x<5 and x==6:
print("ok")
else:
print(“no output”)
(a) ok (b) okok (c) no output (d) none of above
83. identify one possible output of this code out of the following
options:
from random import*
Low=randint(2,3)
High=randrange(5,7)
for N in range(Low,High):
print(N,end=' ')
(a) 3 4 5 (b) 2 3 (c) 4 5 (d) 3 4 5 6
84. The for loop in Python is an _____________
(a) Entry Controlled Loop (b) Exit Controlled Loop
(c) Both of the above (d) None of the above
85. What abandons the current iteration of the loop?
(a) continue (b) break (c) stop (d) infinite
86. What will the following expression be evaluated to in Python? >>>
print((4.00/(2.0+2.0)))
a)Error b)1.0 c)1.00 d)1
87. Which of the following is not a function/method of the random
module in python?
(a) randfloat( ) (b) randint( )
(c) random( ) (d) randrange( )

APPAN RAJ D PGT- CS/IP 13


88. Given the nested if-else below, what will be the value x
when the source code executed successfully:
x=0
a=5 (a) 0 (b) 4
b=5
if a>0: (c) 2 (d) 3
if b<0:
x=x+5
elif a>5:
x=x+4
else:
x=x+3
else:
x=x+2
print (x)
89. Which of the following is False regarding loops in Python?
(a) Loops are used to perform certain tasks repeatedly.
(b) while loop is used when multiple statements are to
executed repeatedly until the given condition
becomes true.
(c) while loop is used when multiple statements are to
executed repeatedly until the given condition becomes
false
(d) for loop can be used to iterate through the elements
of lists.
90. When does the else statement written after loop executes?
(a) When break statement is executed in the loop
(b) When loop condition becomes false
(c) Else statement is always executed
(d) None of the above
91. Predict the output of the following code:
import statistics as S
D=[4,4,1,2,4]
print(S.mean(D),S.mode(D))
(a) 1 4 (b) 4 1 (c) 3 4 (d) 4 3

APPAN RAJ D PGT- CS/IP 14


92. The following code contains an infinite loop. Which is the
best explanation for why the loop does not terminate?
n = 10
answer = 1
while n > 0:
answer = answer + n
n=n+1
print(answer)
(a) n starts at 10 and is incremented by 1 each time
through the loop, so it will always be positive.
(b) Answer starts at 1 and is incremented by n each
time, so it will always be positive.
(c) You cannot compare n to 0 in the while loop. You
must Compare it to another variable.
(d) In the while loop body, we must set n to False, and
this Code does not do that.
93. What will the following code print?
for i in range(1,4):
for j in range(1,4):
print(i, j, end=' ')
94. What will be the output of the following Python code?
for x in range(1, 4):
for y in range(2, 5):
if x * y > 6:
break
print(x*y, end=“#”)
(a) 2#3#4#4#6#8#6#9#12# (b) 2#3#4#5#4#6#6#
(c) 2#3#4#4#6#6# (d) 2#3#4#6
95. Examine the given Python program and select the purpose of
the program from the following options:
N=int(input("Enter the number"))
for i in range(2,N):
if (N%i==0):
print(i)
(a) To display the proper factors(excluding 1 and the
number N itself)
(b) To check whether N is a prime or Not
(c) To calculate the sum of factors of N
(d) To display all prime factors of the Number N.

APPAN RAJ D PGT- CS/IP 15


96. If A=random.randint(B,C) assigns a random value between 1
and 6(both inclusive) to the identifier A, what should be the
values of B and C, if all required modules have already been
imported?
(a) B=0, C=6 (b) B=0,C=7 (c) B=1,C=7 (d) B=1,C=6
97. The continue statement is used:
(a) To pass the control to the next iterative statement
(b) To come out from the iteration
(c) To break the execution and passes the control to else
statement
(d) To terminate the loop
98. Which of the following is an incorrect logical operator in
python?
(a) not (b) in (c) or (d) and
99. Which of the following symbols are used for comments in
Python?
(a) // (b) & (c) /**/ (d) #
100. print (id(x)) will print_______.
(a) Value of x (b) Datatype of x (c) Size of x (d) Address of x
2 – MARKS
1. Evaluate the following expression:
False and bool(15/5*10/2+1)
2. Predict the output of the following:
M, N, O = 3, 8, 12
N, O, M = O+2, M*3, N-5.
print(N,O,M)
3. If given A=2,B=1,C=3, What will be the output of following
expressions:
(i) print((A>B) and (B>C) or(C>A)) (ii) print(A**B**C)
4. What will be the output of following Python Code:
import random as rd
high=4
Guess=rd.randrange(high)+50
for C in range(Guess, 56):
print(C,end="#")
5. Write the output of the code given below:
p=10
q=20
p*=q//3
p=q**2
q+=p
print(p,q)

APPAN RAJ D PGT- CS/IP 16


7. V, W, X = 20, 15, 10
W, V, X = X-2, V+3, W*2.
print(V,X,W)
8. Evaluate the following expressions:
(a) 5 // 10 * 9 % 3 ** 8 + 8 – 4
(b) 65 > 55 or not 8 < 5 and 0 != 55
9. Fill in the blanks to execute loop from 10 to 100 and 10 to 1
(i) for i in range(_______ ):
print(i)
(ii)for i in range( _______):
print(i)
10. Evaluate the following: >>> print(15.0/4+(8*3.0))
11. Predict the output of the following:
X,Y,Z = 3,5,-2
X *= Y + Z
Y -= X * 2 + Y
Z += X + Y
print(X, Y, Z)
12. Sona has written the following code to check whether number
is divisible by 3. She could not run the code successfully.
Rewrite the code and underline each correction done in the
code.
x=10
for I range in (a)
if i%3=0:
print(I)
else
pass
13. Rewrite the following code in Python after removing all syntax
error(s). Underline each correction done in the code.
Value=30
for VAL in range(0,Value)
if val%4==0:
print (VAL*4)
Elseif val%5==0:
print (VAL+3)
else
print(VAL+10)

APPAN RAJ D PGT- CS/IP 17


14. Mona has written a code to input a positive integer and display
all its even factors in descending order. Her code is having
errors. Rewrite the correctcode and underline the corrections
made.
n=input("Enter a positive integer: ")
for i in range(n):
if i%2:
if n%i==0:
print(i,end=' ')
Find error in the following code(if any) and correct code by
15. rewriting code and underline the correction;‐
x= int("Enter value of x:")
for in range [0,10]:
if x=y
print( x + y)
else:
print( x‐y)
16. Mithilesh has written a code to input a number and evaluate
its factorial and then finally print the result in the format: “The
factorial of the <number> is <factorial value>” His code is
having errors. Rewrite the correct code and underline the
corrections made.
f=0
num = input("Enter a number:")
n = num
while num> 1:
f = f * num
num -= 1
else:
print("The factorial of : ", n , "is" , f)
17. What is the output of the program given below:
import random
x = random.random()
y= random.randint(0,4)
print(int(x),”:”, y+int(x))
18. Evaluate the following expression and identify the correct
answer:
(i) 18 - (1 + 2) * 5 + 2**5 * 4 (ii) 10 +(5-2) * 4 + 2**3**2

APPAN RAJ D PGT- CS/IP 18


Rewrite the following code after removing the syntactical
19. error(if any).Underline each correction:
X=input("Enter a Number")
If x % 2 =0:
for i range (2*x):
print i
loop else:
print "#"
20. What possible outputs are expected to be displayed on screen
at the time of execution of the program from the following
code? Also specify the maximum value that can be assigned to
each of the variables L and U.
import random
Arr=[10,30,40,50,70,90,100]
L=random.randrange(1,3)
U=random.randrange(3,6)
for i in range(L,U+1):
print(Arr[i],"@",end="")
(i) 40 @50 @ (ii) 10 @50 @70 @90 @
(iii) 40 @50 @70 @90 @ (iv) 40 @100 @
21. Rewrite the following Python program
x=input(“Enter a number”)
if x % 2=0:
print x, “is even”
else if x<0:
print x, “should be positive”
else;
print x “is odd”
22. (i)Find the output generated by the following code:
a=5
b=10
a+=a+b
b*=a+b
print(a,b)

(ii)Answer the following questions from the following code:


num_list=["One","Two","Three","Four"]
for c in num_list:
print(c)
(a) What will be the output of the above code?
(b) How many times the loop executed?

APPAN RAJ D PGT- CS/IP 19


23. Evaluate the following expressions:
a) 7*3+4**2//5-8 b) 7>5 and 8>20 or not 12>4
24. Predict the output of the following code:
num=123
f=0
s=0
while(num > 3):
rem = num % 100
if(rem % 2 != 0):
f += rem
else:
s+=rem
num /=100
print(f-s)
25. Predict the output of the following:
for i in range(4):
if i==4:
break
else:
print(i)
else: print("Welcome")
26. Anu wrote the code that prints the sum of numbers between 1
and the number, for each number till 10.She could not get
proper output.
i=1
while (i <= 10): # For every number i from 1 to 10
sum = 0 # Set sum to 0
for x in range(1,i+1):
sum += x # Add every number from 1 to i
print(i, sum) # print the result
(a) What is the error you have identified in this code?
(b) Rewrite the code by underlining the correction/s.
27. Evaluate the following expressions:
(a) 6+7*4+2**3//5-8 (b) 8<=20 and 11
28. Predict the output of the following code:
X=3
Y=2
Z = -5
X -= Y + Z
Y //= X - Z
Z *= X + Y
print(X, Y, Z)

APPAN RAJ D PGT- CS/IP 20


29. Predict the output of the following:
a=None
b=None
x=4
for i in range(2,x//2):
if x%i==0:
if a is None:
a=i
else:
b=i
break
print(a,b)
30. Predict the output of the following:
for i in range(1, 15, 2):
temp = i
if i%3==0:
temp = i+1
elif i%5==0:
continue
elif i==11:
break
print(temp, end='$')
31. Predict the output of the following:
P,S=1,0
for X in range(-5,15,5):
P*=X
S+=X
if S==0:
break
else:
print(P, "#", S)
32. Predict the output of the following code:
import math,random
print(math.ceil(random.random())
33. Predict the output of the following:
for x in range(1, 4):
for y in range(2, 5):
if x * y > 6:
break
print(x*y, end="#")

APPAN RAJ D PGT- CS/IP 21


34. Predict the output of the following code:
N=5
C=1
while (C<8):
if (C==3 or C==5):
C+=1
continue
print(C,'*',N,'=',C*N)
C+=1
35. Which is NOT the possible output of following program from
given options:
import random
periph = ['Mouse', 'Keyboard', 'Printer', 'Monitor']
for i in range(random.randint(0,2)):
print(periph[i],'*',end=" ")
(a) Mouse *Keyboard * (b) Mouse *Keyboard* Printer*
(c) Mouse * (d) No output
36. What will be the output after the following statements?
x = 27
y = 19
while x < 30 and y > 15:
x=x+1
y=y-1
print(x,y)
37. What will be the output of the following code?
i=1
while True:
if i%3 == 0:
continue
i=i+1
print(i)
38. Predict the output of the following code:
num = 1
while num < 10:
num *= 2
if num == 4:
break
else:
num -= 1
print(num)

APPAN RAJ D PGT- CS/IP 22


39. X, Y = 2, 5
Z=1
while X < 10:
Z += 1
Y *= 2
X=Y-X
else:
print(Z, "#", X)
(a) Discuss the significance of the else clause in the context
of the provided code.
(b) When is the else block executed, and what is the output?
40. Predict the output of the following code:
X, Y = 2, 5
Z=1
while X < 10:
Z += 1
Y *= 2
if Y==20:
break
X=Y-X
else:
print(Z, "#", X)
print(Z,X,Y)
41. A, B, C = 1, 2, 3
for D in range(2):
C += A
B *= D
if D == 2:
A+= 2
break
print(A)
else:
print(A, "#", B, "#", C)
(i) Explain the role of the if statement and the break
statement within the loop
(ii) When is the else block executed in the above code?
(iii) If the break statement is removed from the code, what
output would be produced?

APPAN RAJ D PGT- CS/IP 23


CHAPTER 2 –REVISION TOUR – II

[STRINGS, LISTS, TUPLES, DICTIONARY]

PRACTICE QUESTIONS

Write a suitable Python statement for each of the following tasks


using built-in functions/methods only: [2 – MARKS]
1. (i) To delete an element "Mumbai:50" from Dictionary D.
(Example: D={'Go':45,"Mum":50,",67:"Chennai","Madurai":34})
(ii) To display words in a string S in the form of a list.
(Example: S="India@12$3")
2. (i) To insert an element 200 at the third position, in the
list "L1". (Example: L1=[10,34,54])
(ii) To Count the occurrences of the character 'A' in a string
variable "Country". (Example: Country="ARGENTINA")
3. (i) To Reverse the order of elements in a list named
"my_list".
(ii) To check whether a string named, message ends with a
full stop / period or not.
4. (i) To Convert a string variable "S" sentence to lowercase.
(Example: S="India@12$3")
(ii) To Remove a key 'Apple' from a dictionary.
(Example: d={'O':45,"M":32,",67:"G","Apple":34})
5. (i) To insert an element 200 at the third position, in the list
L1.
(ii) To check whether a string named, message starts with a
full stop/ period or not.
6. A list named studentAge stores age of students of a class. Write
the Python command to import the required module and (using
built-in function) to display the most common age value from the
given list.
7. Write a Python Program to display alternate characters of a
string my_str.
For example, if my_str = "Computer Science"
The output should be Cmue cec

APPAN RAJ D PGT- CS/IP 24


8. (i) To find the index of the element "apple" in a list named fruits.
(ii) To get the value associated with the key "price" from a
dictionary named products.
9. (i) To count the number of times the element True
appears in a tuple named booleanValues
(ii) Write a Python function that merges two dictionaries
dict1 and dict2 into a new dictionary. If a key exists in
both dictionaries, the value from dict1 should take
priority in the output.
10. (i) Write a Python function that takes two strings as input and
returns True if the second string is a substring of the first
string, otherwise False.
(ii) Implement a Python function that deletes always last key-
value pair from a dictionary based on the given key.
11. (i) To concatenate a list of strings into a single
string with a specified delimiter.
(ii) To remove all items from a dictionary.
12. (i) To capitalizes the first letter of each word.
(ii) To creates a shallow copy of a given list using a built-in
method.
TOPIC - STRINGS
STATE TRUE OR FALSE
1. String is mutable data type.
2. Python considered the character enclosed in triple quotes
as String.
3. String traversal can be done using ‘for’ loop only.
4. Strings have both positive and negative indexes.
5. The find() and index() are similar functions.
6. Indexing of string in python starts from 1.
7. The Python strip() method removes any spaces or specified
characters at the start and end of a string.
8. The startswith() string method checks whether a string starts
with a particular substring.
9. "The characters of string will have two-way indexing."

APPAN RAJ D PGT- CS/IP 25


ASSERTION & REASONING
1. A: Strings are immutable.
R: Individual elements cannot be changed in string in
place.
2. A: String is sequence data type.
R: A python sequence is an ordered collections of items where
each item is indexed by an integer.
3. A: a=’3’
b=’2’
c=a+b
The value of c will be 5
R: ‘+’ operator adds integers but concatenates strings
4. A: a = "Hello"
b = "llo"
c=a-b
print(c)
This will lead to output: "He"
R: Python string does not support - operator
5. A: str1="Hello" and str1="World" then print(str1*3) will
give error.
R : * replicates the string hence correct output will be
HelloHelloHello
6. A: str1=”Hello” and str1=”World” then
print(‘wo’ not in str) will print false
R : not in returns true if a particular substring is not present in
the specified string.
7. A: The following command >>>"USA12#'.upper()
will return False.
R: All cased characters in the string are uppercase and
requires that there be at least one cased character
8. A: Function isalnum() is used to check whether characters
in the string are alphabets or numbers.
R: Function isalnum() returns false if it either contains
alphabets or numbers
9. A: The indexes of a string in python is both forward and
backward.
R: Forward index is from 0 to (length-1) and backward
index is from -1 to (-length)

APPAN RAJ D PGT- CS/IP 26


10. A: The title() function in python is used to convert the first
character in each word to Uppercase and remaining characters
to Lowercase in the string and returns an updated string.
R: Strings are immutable in python.
OBJECTIVE TYPE QUESTIONS (MCQ)
1. What is the output of 'hello'+1+2+3?
(a) hello123 (b) hello6 (c) Error (d) Hello+6
2. If n=”Hello” and user wants to assign n[0]=’F’ what will be the
result?
(a) It will replace the first character
(b It’s not allowed in Python to assign a value to an
individual character using index
(c) It will replace the entire word Hello into F
(d) It will remove H and keep rest of the characters
3. In list slicing, the start and stop can be given beyond limits. If it is
then:
(a) Raise exception IndexError
(b) Raise exception ValueError
(c) Return elements falling between specified start and stop
values
(d) Return the entire list
4. Select the correct output of the code:
Str=“Computer”
Str=Str[-4:]
print(Str*2)
a. uter b. uterretu c. uteruter d. None of these
5. Given the Python declaration s1=”Hello”. Which of the following
statements will give an error?
(a) print(s1[4]) (b) s2=s1 (c) s1=s1[4] (d) s1[4]=”Y”
6. Predict the output of the following code:
RS=''
S="important"
for i in S:
RS=i+RS
print(RS)

APPAN RAJ D PGT- CS/IP 27


7. What will the following code print?
>>> print(max("zoo 145 com"))
(a) 145 (b) 122 (c) z (d) zoo
8. Ms. Hetvee is working on a string program. She wants to display
last four characters of a string object named s. Which of the
following is statement is true?
a. s[4:] b. s[:4] c. s[-4:] d. s[:-4]
What will be the output of following code snippet:
9. msg = “Hello Friends”
msg [ : : -1]
a)Hello b) Hello Friend c) 'sdneirF olleH' d) Friend
10. Suppose str1= ‘welcome’. All the following expression produce the
same result except one. Which one?
(a) str[ : : -6] (b) str[ : : -1][ : : -6] (c) str[ : :6] (d) str[0] + str[-1]
11. Consider the string state = "Jharkhand". Identify the appropriate
statement that will display the lastfive characters of the string
state?
(a) state [-5:] (b) state [4:] (c) state [:4] (d) state [:-4]
12. Which of the following statement(s) would give an error during
execution?
S=["CBSE"] # Statement 1
S+="Delhi" # Statement 2
S[0]= '@' # Statement 3
S=S+"Thank you" # Statement 4
(a) Statement 1 (b) Statement 2
(c) Statement 3 (d) Statement 4
13. Which of the following statement(s) would give an error after
executing the following code?
EM = "Blue Tick will cost $8" # Statement 1
print( EM) # Statement 2
ME = "Nothing costs more than Truth" # Statement 3
EM *= 2 # Statement 4
EM [-1: -3 : -1] += ME[ : 7] # Statement 5
(a) Statement 3 (b) Statement 4
(c) Statement 5 (d) Statement 4 and 5
14. Select the correct output of the following string operations
mystring = "native"
stringList = ["abc","native","xyz"]
print(stringList[1] == mystring)
print(stringList[1] is mystring)
a) True b) False c) False d) Ture
False True Flase Ture

APPAN RAJ D PGT- CS/IP 28


15. Select the correct output of the code :
n = "Post on Twitter is trending"
q = n.split('t')
print( q[0]+q[2]+q[3]+q[4][1:] )
(a)Pos on witter is rending (b)Pos on Twitter is ending
(c) Poser witter is ending (d) Poser is ending
16. What will be the result of the following command:-
>>>"i love python".capitalize()
(a) 'I Love Python' (b) 'I love python'
(c) 'I LOVE PYTHON' (d) None of the above
17. The number of element return from the partition function
is: >>>"I love to study Java".partition("study")
(a) 1 (b) 3 (c) 4 (d) 5
18. Predict the output of the following:
S='INDIAN'
L=S.partition('N')
G=L[0] + '-' + L[1] + '-' + L[2]
print(G)
(a) I-N-DIA-N (b) I-DIA- (c) I-DIAN (d) I-N-DIAN
19. What will be the output of the following command:
>>>string= "A quick fox jump over a lazy fox"
>>>string.find("fox",9,34)
(a) 28 (b) 29 (c) 8 (d) 7
20. Select the correct option for output
X="abcdef"
i='a'
while i in X:
print(i, end=" ")
(a) Error (b) a (c) infinite loop (d) No output
20. What is the output of the following code?
S1="Computer2023"
S2="2023"
print(S1.isdigit(), S2.isdigit())
a)False True b) False False
c) True False d) True True
22. What will be the output of the following statement given:
txt="cbse. sample paper 2022"
print(txt.capitalize())
a) CBSE. sample paper 2022
b) CBSE. SAMPLE SAPER 2022
c) cbse. sample paper 2022
d) Cbse. Sample Paper 2022

APPAN RAJ D PGT- CS/IP 29


23. Select the correct output of the code:
a = "Year 2022 at all the best"
a = a.split('a')
b = a[0] + "-" + a[1] + "-" + a[3]
print (b)
a) Year – 0- at All the best b) Ye-r 2022 -ll the best
c) Year – 022- at All the best d) Year – 0- at all the best
24. Select the correct output of the code:
mystr = ‘Python programming is fun!’
mystr = mystr.partition('pro')
mystr='$'.join(mystr)
(a) Python $programming is fun!
(b) Python $pro$gramming is fun!
(c) Python$ pro$ gramming is fun!$
(d) P$ython $p$ro$gramming is $fun!
25. Identify the output of the following Python statement:
s="Good Morning"
print(s.capitalize( ),s.title( ), end="!")
(a) GOOD MORNING!Good Morning
(b) Good Morning! Good Morning
(c) Good morning! Good Morning!
(d) Good morning Good Morning!
26. What is the output of the following code?
Str1="Hello World"
Str1.replace('o','*')
Str1.replace('o','*')
(a) Hello World (b) Hell* W*rld
(c) Hello W*rld (d) Error
27. State whether the statement is True or False?
No matter the underlying data type, if values are equal returns
true.
28. Predict the output of the following:
S="Hello World!"
print(S.find("Hello"))
(a) 0 (b) 3 (c) [2,3,7] (d) (2,3,7)
29. Which of the following is not a valid Python String operation?
(a) 'Welcome'+'10' (b)'Welcome'*10
(c) 'Welcome'*10.0 (d) '10'+'Welcome'

APPAN RAJ D PGT- CS/IP 30


30. Select the correct output of the following code :
s="I#N#F#O#R#M#A#T#I#C#S"
L=list(s.split("#"))
print(L)
(a) [I#N#F#O#R#M#A#T#I#C#S]
(b) [‘I’, ‘N’, ‘F’, ‘O’, ‘R’, ‘M’, ‘A’, ‘T’, ‘I’, ‘C’, ‘S’]
(c) ['I N F O R M A T I C S']
(d) ['INFORMATICS']
31. STRING="WELCOME" #Line1
NOTE= " " #Line2
for S in range[0,8] #Line3
print(STRING[S]) #Line4
print(S STRING) #Line5
Which statement is wrong in above code:
a) Line3 and Line4 b) Line4 and Line5
c) Line2 and Line3 d) Line3 and Line5
32. Consider the following code that inputs a string and removes all
special characters from it after converting it to lowercase.
s = input("Enter a string")
s = s.lower()
for c in ',.;:-?!()\'"':
_________________
print(s)
For eg: if the input is 'I AM , WHAT I AM’, it should print
i am what i am
Choose the correct option to complete the code .
a. s = s.replace(c, ' ') b. s = s.replace(c, '\0')
c. s = s.replace(c, None) d. s = s.remove(c)
33. Which of the following statement(s) would give an error after
executing the following code?
str= "Python Programming" #S1
x= '2' #S2
print(str*2) #S3
print(str*x) #S4
(a) S1 (b) S2 (c) S3 (d) S4

APPAN RAJ D PGT- CS/IP 31


2 –MARKS / 3 - MARKS
1. If S="python language" is a Python string, which method will
display the following output 'P' in uppercase and remaining in
lower case?
2. Rewrite the following code :
for Name in [Aakash, Sathya, Tarushi]
IF Name[0]= 'S':
print(Name)
3. Consider the given Python string declaration:
>>> mystring = 'Programming is Fun'
>>> print(mystring[-50:10:2].swapcase())
4. Rewrite the following:
STRING=""WELCOME
NOTE = " "
for S in range(0,8):
if STRING[S]= ’E’:
print(STRING(S))
Else:
print "NO"
5. Given is a Python string declaration:
>>>Wish = "## Wishing All Happy Diwali @#$"
Write the output of >>>Wish[ -6 : : -6 ]
6. Predict the output of the following code:
(i) message='FirstPreBoardExam@2022-23'
print(message[ : : -3].upper())
(ii) str="PYTHON@LANGUAGE"
print(str[2:12:2])
7. Predict the output of the following code:
s='Rs.10'
U=''
for i in s:
if i.upper() and i.islower():
U+=''
elif i.isdigit():
U+=i
else:
U=U
print('$'+U)

APPAN RAJ D PGT- CS/IP 32


8. Predict the output of the following:
Name = "cBsE@2051"
R=" "
for x in range (len(Name)):
if Name[x].isupper ( ):
R = R + Name[x].lower()
elif Name[x].islower():
R = R + Name[x].upper()
elif Name[x].isdigit():
R = R + Name[x-1]
else:
R = R + "#"
print(R)
Predict the output of the following:
9. >>> 'he likes tea very much'.rstrip('crunch')
>>> 'There is a mango and an apple on the table'.rstrip('ea')
10. Predict the output of the following code:
Text="Welcome@ to R3MK!"
T=" "
c=0
for i in Text:
if not i.isalpha():
T=T+"*"
elif not i.isupper():
T=T+(Text[c+1])
else:
val=ord(i)
val=val+1
T=T+chr(val)
c=c+1
print(T)

APPAN RAJ D PGT- CS/IP 33


11. Find the output
Msg1="PrEbOArD"
Msg2="Go2"
Msg3=""
for I in range(0,len(Msg2)+1):
if Msg1[I]>="A" and Msg1[I]<="M":
Msg3=Msg3+Msg1[I]
elif Msg1[I]>="N" and Msg1[I]<="Z":
Msg3=Msg3+Msg2[I]
else:
Msg3=Msg3+"*"
print(Msg3)
12. Predict the output of the following:
s="3 & Four"
n = len(s)
m=""
for i in range(0, n):
if (s[i] >= 'A' and s[i] <= 'Z'):
m = m +s[i].upper()
elif (s[i] >= 'a' and s[i] <= 'z'):
m = m +s[i-1]
if (s[i].isdigit()):
m = m + s[i].lower()
else: m = m +'-'
print(m)
13. Predict the output of the following code:
words = ['Python', 'Java', 'C++', 'JavaScript']
result = ['', '', '', '']
index = 0
for word in words:
if word[-1] in ['n', 't']:
result[index] = word.upper()
index += 1
else:
result[index] = word.lower()
index -= 1
print(result)

APPAN RAJ D PGT- CS/IP 34


14. Predict the output of the following code:
Name="PythoN3.1"
R=" "
for x in range(len(Name)):
if Name[x].isupper():
R=R+Name[x].lower()
elif Name[x].islower():
R=R+Name[x].upper()
elif Name[x].isdigit():
R=R+Name[x-1]
else:
R=R+"#"
print(R)
15. Find output generated by the following code:
string="aabbcc"
count=3
while True:
if string[0]=='a':
string=string[2:]
elif string[-1]=='b':
string=string[:2]
else:
count+=1
break
print(string)
print(count)
16. Write the output of the code snippet.
txt = "Time, will it come back?"
x = txt.find(",")
y = txt.find("?")
print(txt[x+2:y])
17. Predict the output of the following:
S='Python Programming'
L=S.split()
S=','.join(L)
print(S)
18. Predict the output of the following:
S="Good Morning Madam"
L=S.split()
for W in L:
if W.lower()==W[::-1].lower()
print(W)

APPAN RAJ D PGT- CS/IP 35


TOPIC – LIST
STATE TRUE OR FALSE
1. List immutable data type.
2. Lists hold key and values.
3. Lists once created cannot be changed.
4. The pop() and remove() are similar functions.
5. The append() can add an element in the middle of the list.
6. Del statement deletes sub list from a list.
7. Sort() and sorted() both are similar function.
8. l1=[5,7,9,4,12] 5 not in l1
9. List can be extend
10. Mutable means only we can insert elements
11. Index of last element in list is n-1, where n is total number of
elements.
12. We can concatenate only two list at one time.
13. L.pop() method will return deleted element immediately
14. L.insert() method insert a new element at the beginning of the list
only.
15. If index is not found in insert() I.e. L.insert(102,89) then it will
add 89 at the end of the list.
16. L.reverse() will accept the parameters to reverse the elements of
the list.
17. L.sort(reverse=1) will reverse the list in descending order
18. L.pop() used to delete the element based on the element of the
list.
19. L.clear() used to clear the elements of the list but memory will
exists after clear.
20. L.append() append more than one element at the end of the list.
21. L=[10,20,30]
L.extend([90,100])
print(L)
output of the above code is: [10,20,30,[90,100]]
22. After sorting using L.sort() method, the index number of the list
element will change.
23. L.remove() used to delete the element of the list based on its
value, if the specified value is not there it will return Error.

APPAN RAJ D PGT- CS/IP 36


ASSERTION & REASONING
1. A: list is mutable data Type
R: We can insert and delete as many elements from list
2. A: Elements can be added or removed from a list
R: List is an immutable datatype.
3. A: List can be changed after creation
R: List is mutable datatype.
4. A: Following code will result into output : True
a=[10,20] , b=a[:]
print( a is b)
R: "is" is used for checking whether or not both the
operands is using same memory location
5. A: list() is used to convert string in to list element
R: string will be passed into list() it will be converted into
list elements
6. A: reverse() is used to reverse the list elements.
Reason: it can reverse immutable data type
elements also
7. A: pop() can delete elements from the last index of list
R: this function can remove elements from the last index
only.
8. A: len() displays the list length
R: it is applicable for both mutable and immutable data
type.
9. A: Usha wants to sort the list having name of students of
her class in descending order using sorted() function
R: sorted() function will sort the list in ascending order
10. A: Raju is working on a list of numbers. He wants to print
the list values using traversing method. He insists that
list can be traversed in forward direction and backward
direction i.e. from beginning to last and last to
beginning.
R: List can be traversed from first element to last element
only.
11. A: Anu wants to delete the elements from the list using
pop() function.
R: Her friend Pari suggested her to use del () function to
delete more than one elements from the list.

APPAN RAJ D PGT- CS/IP 37


OBJECTIVE TYPE QUESTIONS(MCQ)
1. Which point can be considered as difference between string and
list?
(a) Length (b) Indexing and Slicing
(c) Mutability (d) Accessing individual elements
2. What is the output when we execute list(“hello”)?
(a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’] (b) [‘hello’] (c) [‘llo’] (d) [‘olleh’].
3. Predict the output of the following code:
L=["a","b","c"]
M=str(L)
print(len(L))
(a) 3 (b) 11 (c) 15 (d) 9
4. Given a List L=[7,18,9,6,1], what will be the output of
L[-2::-1]?
(a) [6, 9, 18, 7] (b) [6,1] (c) [6,9,18] (d) [6]
5. If a List L=['Hello','World!'] Identify the correct output of the
following Python command: >>> print(*L)
(a) Hello World! (b) Hello,World!
(c)'Hello','World!' (d) 'Hello','World!'
6. Consider the list aList=[ "SIPO", [1,3,5,7]]. What would the
following code print?
(a) S, 3 (b) S, 1 (c) I, 3 (d) I, 1
7. Predict the output of the following code:
L=["1","2","3"]
M=str(L)
print(len(M))
(a) 3 (b) 11 (c) 15 (d) 9
8. Suppose list1 is [1, 3, 2], What is list1 * 2 ?
a) [2, 6, 4] (b) [1, 3, 2, 1, 3]
(c) [1, 3, 2, 1, 3, 2] (d) [1, 3, 2, 3, 2, 1]
9. Suppose list1 = [0.5 * x for x in range(0,4)], list1 is
a) [0, 1, 2, 3] b) [0, 1, 2, 3, 4]
c) [0.0, 0.5, 1.0, 1.5] d) [0.0, 0.5, 1.0, 1.5, 2.0]
10. >>> L1=[6,4,2,9,7]
>>> print(L1[3:]= "100"
(a) [6,4,2,9,7,100] (b) [6,4,2,100]
(c) [6,4,2,1,0,0] (d) [6,4,2, ‘1’,’0’,’0’]

APPAN RAJ D PGT- CS/IP 38


11. Predict the output of the following code:
L=['1','2','3']
K=len(str(L))+len(L)
print(K)
(a) 3 (b) 11 (c)
12. Which statement is not correct
a) The statement x = x + 10 is a valid statement
b) List slice is a list itself.
c) Lists are immutable while strings are mutable.
d) Lists and strings in pythons support two way indexing
13. Which one is the correct output for the following code?
a=[1,2,3,4]
for x in range(0,len(a)):
b=[sum(a[0:x+1])
print (b)
(a) 10 (b) [1,3,5,7] (c) 4 (d) [1,3,6,10]
14. What will be the output for the following python code:
L=[10,20,30,40,50]
L=L+5
print(L)
(a) [10,20,30,40,50,5] (b) [15,25,35,45,55]
(c) [5,10,20,30,40,50] (d) Error
15. Select the correct output of the code:
L1, L2 = [10, 23, 36, 45, 78], [ ]
for i in range(len(L1)) :
L2.insert(i, L1.pop( ) )
print( L1, L2, sep=’@’)
(a) [78, 45, 36, 23, 10] @ [ ]
(b) [10, 23, 36, 45, 78] @ [78, 45, 36, 23, 10]
(c) [10, 23, 36, 45, 78] @ [10, 23, 36, 45, 78]
(d) [ ] @ [78, 45, 36, 23, 10]
16. The append() method adds an element at
(a) First (b) Last (c) Specified index (d) At any location
17. The return type of x in the below code is
txt = "I could eat bananas all day"
x = txt.partition("bananas")
(a) string (b) List (c) Tuple (d) Dictionary

APPAN RAJ D PGT- CS/IP 39


18. S1: Operator + concatenates one list to the end of another
list.
S2: Operator * is to multiply the elements inside the list.
Which option is correct?
(a) S1 is correct, S2 is incorrect
(b) S1 is incorrect, S2 is incorrect
(c) S1 is incorrect, S2 is incorrect
(d) S1 is incorrect, S2 is correct
19. Which of the following statement is true for extend() list method?
(a) Adds element at last
(b) Adds multiple elements at last
(c) Adds element at specified index
(d) Adds elements at random index
20. What is the output of the following code?
a=[1,2,3,4,5]
for i in range(1,5): (a) 5 5 1 2 3 (b) 5 1 2 3 4
a[i-1]=a[i]
for i in range(0,5): (c) 2 3 4 5 1 (d) 2 3 4 5 5
print(a[i],end=" ")

21. What is the output of the functions shown below?


min(max(False,-3,-4),2,7)
(a) -3 (b) -4 (c) True (d) False
22. If we have 2 Python Lists as follows:
L1=[10,20,30]
L2=[40,50,60]
If we want to generate a list L3 as:
then best Python command out of the following is:
(a) L3=L1+L2 (b) L3=L1.append(L2)
(c) L3=L1.update(L2) (d) L3=L1.extend(L2)
23. Identify the correct output of the following Python code:
L=[3,3,2,2,1,1]
L.append(L.pop(L.pop()))
print(L)
(a) [3,2,2,1,3] (b)[3,3,2,2,3] (c)[1,3,2,2,1] (d)[1,1,2,2,3,3]
24. Predict the output of the following:
L1=[1,4,3,2]
L2=L1
L1.sort()
print(L2)
(a) [1,4,3,2] (b)[1,2,3,4] (c) 1 4 3 2 (d) 1 2 3 4

APPAN RAJ D PGT- CS/IP 40


25. If PL is Python list as follows:
PL=['Basic','C','C++']
Then what will be the status of the list PL after
PL.sort(reverse=True) ?
(a) ['Basic','C','C++'] (b) ['C++','C','Basic']
(c) ['C','C++','Basic'] (d) PL=['Basic','C++','C']
26. Given list1 = [34,66,12,89,28,99]
Statement 1: list1.reverse()
Statement 2: list1[::-1]
Which statement modifies the contents of original list1.
(a) Statement 1 (b) Statement 2
(c) Both Statement 1 and 2. (d) None of the mentioned
27. which command we use can use To remove string "hello" from
list1, Given, list1=["hello"]
(a) list1.remove("hello") (b) list1.pop(list1.index('hello'))
(c) Both A and B (d) None of these
28. Predict the output of the following:
S=[['A','B'],['C','D'],['E','F']]
print(S[1][1])
(a)'A' (b) 'B' (c) 'C' (d) 'D'
29. Which of the following statement(s) would give an error during
the execution of the following code?
numbers = [15, 25, 35, 45, 55]
print(numbers) # Statement 1
print(numbers[2] / 0) # Statement 2
print(min(numbers)) # Statement 3
numbers[1] = "twenty-five" # Statement 4
(a) Statement 1 (b) Statement 2
(c) Statement 3 (d) Statement 4
30. Predict the output of the following:
L1=[1,2,3]
L2=[4,5]
L3=[6,7]
L1.extend(L2)
L1.append(L3)
print(L1)
(a) [1,2,3,4,5,6,7] (b)[1,2,3,[4,5],6,7]
(c) [1,2,3,4,5,[6,7]] (d)[1,2,3,[4,5],[6,7]]

APPAN RAJ D PGT- CS/IP 41


31. State True or False "There is no conceptual limit to the size of a
list."
32. The statement del l[1:3] do which of the following task?
(a) Deletes elements 2 to 4 elements from the list
(b) Deletes 2nd and 3rd element from the list
(c) Deletes 1st and 3rd element from the list
(d) Deletes 1st, 2nd and 3rd element from the list
33. Which of the following will give output as: [23, 2, 9, 75]?
If list1=[6,23,3,2,0,9,8,75]
(a) print(list1[1:7:2]) (b) print(list1[0:7:2])
(c) print(list1[1:8:2]) (d) print(list1[0:8:2])
34. Find the output
values = [[3, 4, 5, 1 ], [33, 6, 1, 2]]
for row in values:
row.sort()
for element in row:
print(element, end = " ")
print()
(a). The program prints on row 3 4 5 1 33 6 1 2
(b). The program prints two rows 3 4 5 1
followed by 33 6 1 2
(c). The program prints two rows 3 4 5 1
followed by 33 6 1 2
(d). The program prints two rows 1 3 4 5
followed by 1 2 6 33
2 MARKS / 3 MARKS
1. (a) >>>L=[1,"Computer",2,"Science",10,"PRE",30,"BOARD"]
>>>print(L[3:])
(b) Identify the output of the following Python statements.
>>>x = [[10.0, 11.0, 12.0],[13.0, 14.0, 15.0]]
>>>y = x[1][2]
>>>print(y)
2. Predict the output of the following code:
L=["1","2","3","5"]
M=str(L)
print(M.find("3"))

APPAN RAJ D PGT- CS/IP 42


3. Predict the output of the following code:
LST=[1,2,3,4,5,6]
for i in range(6):
LST[i-1]=LST[i]
print(LST)
4. Predict the output of the following code:
L=['a','b','c']
K=str(L)
S=ord(K[1])
P=ord(max(L))+S
print(P)
5. Write the output of following code:
lst1=[10,15,20,25,30]
lst1.insert(3,4)
lst1.insert(2,3)
print(list1[-5])
6. Write output for the following code:
list1=[x+2 for x in range(5)]
print(list1)
7. What will be the output of the following code?
a=[1,2,3,4]
s=0
for a[-1] in a:
print(a[-1])
s+=a[-1]
print(‘sum=’,s)
8. Predict the output of the following code:
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=" ")
9. Predict the output of the following:
L=[10,20]
L1=[30,40]
L2=[50,60]
L.append(L1)
L.extend(L2)
print(L)

APPAN RAJ D PGT- CS/IP 43


10. Predict the output of the following:
L=['a','b','c']
K=str(L)
P=ord(K[2])
S=chr(P).lower()
if S.islower():
print((K[7].title()).swapcase())
11. Predict the output of the following:
M=[11, 22, 33, 44]
Q=M
M[2]+=22
L=len(M)
for i in range (L):
print("Now@", Q[L-i-1], "#", M[i])
12. Predict the output of the following:
L=[10,20]
K=L
L[0]=100
print(K)
S=K.copy()
S[2]=90
print(K)
print(S)
13. Predict the output of the following:
L1=[100,212,310]
print(L1)
L1.extend([33,52])
for i in range(len(L1)):
if L1[i]%2==0:
L1[i]=L1[i] /5
else:
L1[i]=L1[i]%10
print(L1)
14. Predict the output of the Python code given below:
l=[ ]
for i in range(4):
l.append(2*i+1)
print(l[::-1])

APPAN RAJ D PGT- CS/IP 44


15. Predict the output of the following code:
S= ['CS','IP','IT']
L=S
New= [ ]
for i in S:
if S.index(i)%2!=0:
New.append(S.pop())
elif S.index(i) //2 ==0:
New.append(S.insert(len(S)-1,S.pop()))
print(New,L,S,sep='#')
12. What will be the output of the following code?
Values=[10,20,30,40]
for Val in Values:
for I in range(1, Val%9):
print(I,"*",end= " " )
print()
13. Predict the output of the following:
TXT = ["10","20","30","5"]
CNT = 3
TOTAL = 0
for C in [7,5,4,6]:
T = TXT[CNT]
TOTAL = float (T) + C
print (TOTAL)
CNT-=1
14. Predict the output of the following code:
P = (10, 20, 30, 40, 50 ,60,70,80,90)
Q =list(P)
R=[]
for i in Q:
if i%3==0:
R.append(i)
R = tuple(R)
print(R)
15. Predict the output of the following code:
for i in "QUITE":
print([i.lower()], end= "#")

APPAN RAJ D PGT- CS/IP 45


16. Write the output of the following python code:
Numbers =[9,18,27,36]
for num in Numbers:
for N in range(1,num%8):
print(N,"$",end="")
print()
17. Predict the output of the following code:
L1=[10,15,20]
L2=L1
L3=[0,0,0,0]
print("L2->",L2)
print("L3->",L3)
j=0
L1.append(51)
for i in range(len(L1)):
if L1[i]%5==0:
L2[j]=L2[j]*L2[j]
L3[j]=L2[j]%5
j+=1
print("L1->",L1)
print("L2->",L2)
print("L3->",L3)
18. Write the output of the following:
x = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
result = []
for items in x:
for item in items:
if item % 2 == 0:
result.append(item)
print(result)
19. Predict the output of the following:
List1 = list("Examination")
List2 =List1[1:-1]
new_list = []
for i in List2:
j=List2.index(i)
if j%2==0:
List1.remove(i)
print(List1)

APPAN RAJ D PGT- CS/IP 46


20. Predict the output of the following code:
L= [3,1,4]
M= [11, 5, 9]
L.insert(1,21)
M.insert(0,7)
K = len(L)
N= [ ]
for a in range (K) :
N.append(L[a]+M[a])
print(N)
21. Predict the output of the following:
fruit_list1 = ['Apple', 'Berry', 'Cherry', 'Papaya']
fruit_list2 = fruit_list1
fruit_list3 = fruit_list1[:]
fruit_list2[0] = 'Guava'
fruit_list3[1] = 'Kiwi'
sum = 0
for ls in (fruit_list1, fruit_list2, fruit_list3):
if ls[0] == 'Guava':
sum += 1
if ls[1] == 'Kiwi':
sum += 20
print(sum)
22. Predict the output of the following:
L1,L2=[10,15,20,25],[ ]
for i in range(len(L1)):
L2.insert(i,L1.pop())
print(L1,L2,sep='&')
23. Predict the output of the following:
L1=[10,20,30,20,10]
L2=[ ]
for i in L1:
if i not in L2:
L2.append(i)
print(L1,L2,sep='$')
24. Predict the output of the following:
num=[10,20,30,40,50,60]
for x in range(0,len(num),2):
num[x], num[x+1]=num[x+1], num[x]
print(num)

APPAN RAJ D PGT- CS/IP 47


25. Predict the output of the following:
L=[1,2,3,4,5]
Lst=[]
for i in range(len(L)):
if i%2==1:
t=(L[i],L[i]**2)
Lst.append(t)
print(Lst)
26. Predict the output of the following:
sub=["CS", "PHY", "CHEM", "MATHS","ENG"]
del sub[2]
sub.remove("ENG")
sub.pop(1)
print(sub)
27. Predict the output of the following:
Predict the output:
list1 =['Red', 'Green', 'Blue', 'Cyan','Magenta','Yellow',]
print(list1[-4:0:-1])
28. Predict the output of the following:
L=[10,20,40,50,60,67]
L[0:3]="100"
print(L)
29. Write the output of the following:
print(list(i*2 for i in range(5)))
print(list(range(4)))
30. Predict the output of the following code:
P=[10,21,35,50]
Q=4
for i in range(Q):
if P[i]%7 == 0 :
P[i] //= 7
if P[i]%2 == 0 :
P[i] //= 2
for i in P:
print(i, end="#")
31. Predict the output of the following:
lst = [40, 15, 20, 25, 30]
lst.sort()
lst.insert(3, 4)
lst.append(23)
sorted(lst)
print(lst)

APPAN RAJ D PGT- CS/IP 48


32. Predict the output of the following:
L=[10,2,5,-1,90,23,45]
L.sort(reverse=True)
S=L.pop(2)
L.insert(4,89)
sorted(L)
L.reverse()
L.pop(3)
print(L)
33. Predict the output of the following:
L=[10,2,5,-1,90,23,45]
L.sort(reverse=True)
G=L.append(L.pop(L.pop()))
print(G)
34. Predict the output of the following:
L=['30','40','20','50']
count=3
Sum=0
P=[]
for i in[6,4,5,8]:
T=L[count]
Sum=float(T)+i
P.append(Sum)
count-=1
print(P)
print(P[3:0:-1])
for i in[0,1,2,3]:
P[i]=int(P[i])+10
print(P)
35. Predict the output of the following:
L=['FORTRAN','C++','Java','Python']
L.insert(2,"HTML")
del L[4]
L.remove('Java')
L.pop()
L.insert(1,"PHP")
L.sort()
L.pop()
print(L)

APPAN RAJ D PGT- CS/IP 49


TOPIC – TUPLES
STATE TRUE OR FALSE
1. Tuple data structure is mutable
2. tuples allowed to have mixed lengths.
3. tuple have one element for Ex: S=(10)
4. We Can concatenate tuples.
5. The elements of the of a tuple can be deleted
6. A tuple storing other tuples is called as nested tuple
7. The + Operator adds one tuple to the end of another tuple
8. A tuple can only have positive indexing.
ASSERTION & REASONING
1. A: Tuples are ordered
R: Items in a tuple has an defined order that will not be
changed.
2. A: A tuple can be concatenated to a list, but a list cannot
be concatenated to a tuple.
R: Lists are mutable and tuples are immutable in Python
3. A: Tuple is an in inbuilt data structure
R: Tuple data structure is created by the programmers and
not by the creator of the python
4. a=(1,2,3)
a[0]=4
A: The above code will result in error
R: Tuples are immutable. So we cant change them.
5. A: A tuple cannot be sorted inline in python and therefore
sorted () returns a sorted list after sorting a tuple.
R: Tuples are non-mutable data type
6. >>> tuple1 = (10,20,30,40,50)
>> tuple1.index(90)
A: Above statements gives ValueError in python
R: ValueError: tuple.index(x): x not in tuple
7. T1 = (10, 20, (x, y), 30)
print(T1.index(x))
A: Above program code displays the index of the element ‘x’
R: Returns the index of the first occurrence of the
element in the given tuple
8. >>>tuple1 = (10,20,30,40,50,60,70,80)
>>>tuple1[2:]
Output: (30, 40, 50, 60, 70, 80)
A: Output given is incorrect
R: Slicing in above case ends at last index

APPAN RAJ D PGT- CS/IP 50


9. A:
t=(10,20,30)
t[1]=45
the above-mentioned question will throw an error.
R: Tuple are used to store sequential data in a program
10. A: Forming a tuple from individual values is called packing
R: Many individual data can be packed by assigning them
to one single variable, where data is separated by
comma.
OBJECTIVE TYPE QUESTIONS (MCQ)
1. Which of the following statement creates a tuple?
a) t=[1,2,3,4] b) t={1,2,3,4} c) t=<1,2,3,4> d) t=(1,2,3,4)
2. Which of the following operation is supported in python with
respect to tuple t?
a) t[1]=33 b) t.append(33) c) t=t+t d) t.sum()
3. Which of the following is not a supported operation in Python?
(a) “xyz”+ “abc” (b) (2)+(3,) (c) 2+3 (d) [2,4]+[1,2]
4. Predict the output:
T=('1')
print(T*3)
(a) 3 (b) ('1','1','1') (c) 111 (d) ('3')
5. Identify the errors in the following code:
MyTuple1=(1, 2, 3) #Statement1
MyTuple2=(4) #Statement2
MyTuple1.append(4) #Statement3
print(MyTuple1, MyTuple2) #Statement4
(a) Statement 1 (b) Statement 2
(c) Statement 3 (d) Statement 2 &3
6. Suppose a tuple Tup is declared as Tup = (12, 15, 63, 80) which
ofthe following is incorrect?
(a) print(Tup[1]) (b) Tup[2] = 90
(c) print(min(Tup)) (d) print(len(Tup))
7. Predict the output of the following code:
t1=(2,3,4,5,6)
print(t1.index(4))
(a) 4 (b) 5 (c) 6 (d) 2

APPAN RAJ D PGT- CS/IP 51


8. Given tp = (1,2,3,4,5,6). Which of the following two statements will
give the same output?
print(tp[:-1]) # Statement 1
print(tp[0:5]) # Statement 2
print(tp[0:4]) # Statement 3
print(tp[-4:]) # Statement 4
(a) Statement 1 and 2 (b) Statement 2 and 4
(c) Statement 1 and 4 (d) Statement 1 and 3
9. What will be the output for the following Python statement?
T=(10,20,[30,40,50],60,70)
T[2][1]=100
print(T)
(a) (10,20,100,60,70) (b) 10,20,[30,100,50],60,70)
(c) (10,20,[100,40,50],60,70) (d) None of these
10. Which of the following is an unordered collection of elements
(a) List (b) Tuple (c) Dictionary (d) String
11. Write the output:-
myTuple = ("John", "Peter", "Vicky")
x = "#".join(myTuple)
print(x)
(a) #John#Peter#Vicky (b) John#Peter#Vicky
(c) John#Peter#Vicky# (d) #John#Peter#Vicky#
12. Consider the following statements in Python and the
question that follows:
i. Tuple is an ordered list
ii. Tuple is a mutable data type
From the above statements we can say that
(a) Only (i) is correct
(b) Only (ii) is correct
(c) Both (i) and (ii) are correct
(d) None of (i) and (ii) are correct
13. Which of the following is not a tuple in Python?
(a) (1,2,3) (b) (“One”,”Two”,”Three”) (c) (10,) (d) (“One”)
14. Suppose a tuple T is declared as T=(10,20,30) and a list L=["mon",
"tue", "wed","thu", "fri", "sat", "sun"], which of the following is
incorrect ?
a) min(L) b) L[2] = 40 c) T[3] = “thurs” d) print( min(T))
15. Suppose a Python tuple T is declared as:
T=('A','B','C')
Which of the following command is invalid?
(a) T=('D') (b) T=('D',) (c) T+=('D') (d) T+=('D',)

APPAN RAJ D PGT- CS/IP 52


16. Predict the output:
tup1 = (2,4,[6,2],3)
tup1[2][1]=7
print(tup1)
(a)Error (b) (2,4,[6,2],3) (c)(2,4,[6,7],3) (d)(2,4,6,7,3)
17. Consider a tuple t=(2,4,5), which of the following will give error?
(a) list(t)[-1]=2 (b) print(t[-1]) (c) list(t).append(6) (d) t[-1]=7
18. Suppose a tuple T1 is declared as T1 = (10, 20, 30, 40, 50) which of
the following is incorrect?
a)print(T[1]) b) T[2] = -29 c) print(max(T)) d) print(len(T))
19. What will be the output of the following Python code ?
T1= ( )
T2=T1 * 2
print(len(T2))
(a) 0 (b) 2 (c) 1 (d) Error
20. Predict the output:
Tup=(3,1,2,4)
sorted(Tup)
print(Tup)
(a) (3,1,2,4) (b) (1,2,3,4) (c) [3,1,2,4] (d) [1,2,3,4]
21. Predict the output of the following:
S=([1,2],[3,4],[5,6])
S[2][1]=8
print(T)
(a) ([1,2],[8,4],[5,6])
(b) ([1,2],[3,4],[8,6])
(c) ([1,2],[3,4],[5,8])
(d) Will generate an Error as a Tuple is immutable
22. Consider a tuple T1=(2,3, {1:"One",2:"Two",3:"Three'}).
Identify the statement that will result in an error.
(a) print(2 in T1) (b) print(T1[0]) (c) print(T1[3]) (d) print(len(T1))
**************************************************************

APPAN RAJ D PGT- CS/IP 53


2 MARKS / 3 MARKS
1. Predict the output of the following:
test_list = [5, 6, 7]
test_tup = (9, 10)
res = tuple(list(test_tup) + test_list)
print(str(res))
2. Predict the output of the following:
tuple1 = (5, 12, 7, 4, 9 ,6)
list1 =list(tuple1)
list1.insert(2,8)
list1.pop()
tuple1=tuple(list1)
print(tuple1)
3. Predict the output of the following code:
tuple1 = ([7,6], [4,4], [5,9] , [3,4] , [5,5] , [6,2] , [8,4])
listy = list( tuple1)
new_list = list()
for elem in listy :
tot = 0
for value in elem:
tot += value
if elem.count(value) == 2:
new_list.append(value)
tot = 0
else:
print( tuple(new_list) )
4. Write the output of the code given below:
a,b,c,d = (1,2,3,4)
mytuple = (a,b,c,d)*2+(5**2,)
print(len(mytuple)+2)
5. Write the output of following code and explain the difference
between a*3 and (a,a,a)
a=(1,2,3)
print(a*3)
print(a,a,a)

APPAN RAJ D PGT- CS/IP 54


TOPIC - DICTIONARY
STATE TRUE OR FALSE
1. Dictionary values are immutable
2. List can be converted in Dictionary
3. It is always not necessary to enclose dictionary in { }.
4. Dictionary keys are unique and always of string type
5. D.popitem() is used to delete the last items of the dictionary.
6. D.get() method is used to insert new key:value pair inside of the
dictionary.
ASSERTION & REASONING
1. A: Dictionaries are mutable.
R: Individual elements can be changed in dictionary in
place.
2. A: Dictionary in Python holds data items in key-value pairs
R: Immutable means they cannot be changed after creation.
3. A: Key of dictionary can’t be changed.
R: Dictionary Key’s are immutable.
4. A: Key of dictionary must be single element.
R: Key of dictionary is always string type.
5. A: Dictionary and set both are same because both enclosed
in { }.
R: Dictionary is used to store the data in a key-value pair
format.
6. A: The pop() method accepts the key as an argument and
remove the associated value
R: pop() only work with list because it is mutable.
7. A: The items of the dictionary can be deleted by using the
del keyword.
R: del is predefined keyword in python.

APPAN RAJ D PGT- CS/IP 55


OBJECTIVE TYPE QUESTIONS (MCQ)
1. Which statement is correct for dictionary?
(a) A dictionary is a ordered set of key: value pair
(b) each of the keys within a dictionary must be unique
(c) each of the values in the dictionary must be unique
(d) values in the dictionary are immutable
2. Which of the following is the correct statement for checking the
presence of a key in the dictionary?
a) <key> in <dictionary_obj>
b) <key> not in <dictionary_obj>
c) <key> found in <dictionary_obj>
d) a) <key> exists in <dictionary_obj>
3. What will be the output for the following Python statements?
D= {“Amit”:90, “Reshma”:96, “Suhail”:92, “John”:95}
print(“John” in D, 90 in D, sep= “#”)
(a) True#False (b)True#True (c) False#True (d) False#False
4. Choose the most correct statement among the following –
(a) a dictionary is a sequential set of elements
(b) a dictionary is a set of key-value pairs
(c) a dictionary is a sequential collection of elements key-
value pairs
(d) a dictionary is a non-sequential collection of elements
5. What will be output of the following code:
d1={1:2,3:4,5:6}
d2=d1.popitem()
print(d2)
(a) {1:2} (b) {5:6} (c) (1,2) (d) (5,6)
6. Which of the following statements create a dictionary?
(a) d = { } (b) d = {"john":40, "peter":45}
(c) d = {40: "j", 45: "p"} (d) All of the mentioned above
7. What will be output of following:
d = {1 : "SUM", 2 : "DIFF", 3 : "PROD"}
for i in d: print (i)
8. Predict the output of the following:
D={1:"One",2:"Two",3:"Three"}
L=[ ]
(a) [1,2,3]
for K,V in D.items():
(b) ["One","Two","Three"]
if V[0]=="T":
(c) [2,3]
L.append(K)
print(L) (d) ["Two","Three"]

APPAN RAJ D PGT- CS/IP 56


9. Given the following dictionary
employee={'salary':10000,'age':22,'name':'Mahesh'}
employee.pop('age')
print(employee)
What is output?
(a) {‘age’:22}
(b) {'salary': 10000, 'name': 'Mahesh'}
(c) {'salary':10000,'age':22,'name':'Mahesh'}
(d) None of the above
10. D={'A':1, 'B':2, 'C':3}
Then, which of the following command will remove the entire
dictionary from the memory?
(a) del(D) (b) D.del() (c) D.clear() (d) D.remove()
11. Predict the output of the following:
D1={'A':5,'B':5,'C':9,'D':10}
D2={'B':5,'D':10}
D1.update(D2)
print(D1)
(a) {'A':5,'B':5,'C':9,'D':10} (b) {'A':5,'B':5,'C':9,'B':5,'D':10}
(c) {'A':5,'C':9,'D':10} (d) {'B':7,'D':10,'A':5,'C':9}
12. Predict the output of the following:
D1={1:2,2:3,3:4}
D2=D1.get(1,2)
print(D2)
(a) 2 (b) 3 (c) [2,3] (d) {1:2,2:3}
13. Which of the following operation(s) supported in Dictionary?
(a) Comparison(only = and !=) (b) Membership
(c) Concatenation (d) Replication
14. Predict the output of the following:
D1={1:10,4:56,100:45}
D2={1:10,4:56,45:100}
print(D1==D2)
(a) True (b) False
(c) Cannot Compare the dictionaries (d) Error
15. Predict the output of the following:
D1={1:10,4:56,100:45}
D2={1:10,4:56,45:100}
print(D1<=D2)
(a) True (b) False (c) Error (d) None of the above

APPAN RAJ D PGT- CS/IP 57


16. Write a python command to create list of keys from a dictionary.
dict={'a':'A', 'b':'B','c':'C', 'd':'D'}
(a) dict.keys() (b) keys() (c) key.dict() (d) None of these
17. Which of the following statement(s) would give an error after
executing the following code?
d = {"A" : 1, "B": 2, "C": 3, "D":4} #statement 1
sum_keys = 0 #statement 2
for val in d.keys(): #statement 3
sum_keys = sum_keys + val #statement 4
print(sum_keys)
(a) Statement 1 (b) Statement 2
(c) Statement 3 (d) Statement 4
18. What will the following code do?
dict={“Phy”:94,”Che”:70,”Bio”:82,”Eng”:95}
dict.update({“Che”:72,”Bio”:80})
(a) It will create new dictionary as dict={“Che”:72,”Bio”:80}
and old dict will be deleted.
(b) It will throw an error as dictionary cannot be updated.
(c) It will simply update the dictionary as
dict={“Phy”:94,”Che”:72,”Bio”:80, “Eng”:95}
(d) It will not throw any error but it will not do any changes
in dict.
19. Consider the coding given below and fill in the blanks:
Dict_d={‘BookName’:’Python’,’Author’:”Arundhati Roy”}
Dict_d.pop() # Statement 1
List_L=[“java”,”SQL”,”Python”]
List_L.pop() # Statement 2
(i) In the above snippet both statement 1 and 2 deletes the
last element from the object Dict_d and
List_L________(True/False).
(ii) Statement_______(1/2) alone deletes the last element in
its object
20. Identify the output of following code
d={'a':'Delhi','b':'Mumbai','c':'Kolkata'}
for i in d:
if i in d[i]:
x=len(d[i])
print(x)
(a) 6 (b) 0 (c) 5 (d) 7

APPAN RAJ D PGT- CS/IP 58


21. What will be the output of the following code?
D1={1: "One",2: "Two", 3: "C"}
D2={4: "Four",5: "Five"}
D1.update(D2)
print (D1)
a) {4: "Four",5: "Five"}
b) Method update() doesn’t exist for dictionary
c) {1:"One",2:"Two", 3: "C"}
d) {1:"One",2: "Two",3: "C",4:"Four",5: "Five"}
22. What will the following code do?
dict={"Exam":"AISSCE", "Year":2022}
dict.update({"Year”:2023} )
a. It will create new dictionary dict={” Year”:2023}and old
dictionary will be deleted
b. It will throw an error and dictionary cannot updated
c. It will make the content of dictionary as
dict={"Exam":"AISSCE","Year":2023}
d. It will throw an error and dictionary and do nothing
23 Given the following dictionaries
Dict1={'Tuple': 'immutable', 'List': 'mutable', 'Dictionary':
'mutable', 'String': 'immutable'}
Which of the following will delete key:value pair for
key=‘Dictionary’ in the above mentioned dictionary?
(a) del Dict1['Dictinary'] (b) Dict1[‘Dictionary’].delete()
(c) delete (Dict1.["Dictionary"]) (d) del(Dict1.[‘Dictionary’])
2 MARKS / 3 -MARKS
1. Write a statement in Python to declare a dictionary whose keys
are Sub1, Sub2, Sub3 and values are Physics, Chemistry, and
Math respectively.
2. Identify the output of the following Python statements.
d={2:{1:'one',2:'two'},3:{1:'one',2:'two',3:'three'},4:{1:'one',2:'two',3:'t
hree',4:'four'}}
print(d[4][3])
3. Debug the following code and underline the correction made:
d=dict{ }
n=input("enter number of terms")
for i in range(n):
a=input("enter a character")
d[i]=a

APPAN RAJ D PGT- CS/IP 59


4. Write the output of the code given below:
>>squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
>>>print(squares.pop(4))
5. Write the output of the code given below :
Emp = { "SMITH":45000 , "CLARK":20000 }
Emp["HAPPY"] = 23000
Emp["SMITH"] = 14000
print( Emp.values())
6. What will be the output of the following Python code?
d1={"a":10,"b":2,"c":3}
str1=""
for i in d1:
str1=str1+str(d1[i])+" "
str2=str1[ : -1]
print(str2[: : -1])
7. Predict the output of the Python Code given below:
d={"Rohan":67,"Ahasham":78,"naman":89,"pranav":79}
print(d)
sum=0
for i in d:
sum+=d[i]
print(sum)
print("sum of values of dictionaries",sum)
8. Predict the output of the following code:
d={2:'b',4:'c'}
d1={1:'a'}
d.update(d1)
d[1]='v'
print(list(d.values()))
9. Write the output of the code given below:
d1={'rno':25, 'name':'dipanshu'}
d2={'name':'himanshu', 'age':30,'dept':'mechanical'}
d2.update(d1)
print(d2.keys())

APPAN RAJ D PGT- CS/IP 60


10. Predict the output of the following code:
Mydict={ }
Mydict[(1,2,3)]=12
Mydict[(4,5,6)]=20
Mydict[(1,2)]=25
total=0
for i in Mydict:
total=total+Mydict[i]
print(total)
print(Mydict)
Write the output of the code given below:
11. d1 = {"name": "Aman", "age": 26}
d2 = {27:'age','age':28}
d1.update(d2)
print(d1.values())
12. Write the output of the following code given below:
Marks = {'Sidhi':65, 'Prakul':62, 'Suchitra':64, 'Prakash':50}
newMarks = {'Suchitra':66,'Arun':55,'Prkash':49}
Marks.update(newMarks)
for key,value in Marks.items():
print(key,'scored',value,'marks in Pre Board',end=' ')
if(value<55):
print(‘and needs imporovement’end=’.’)
print()
13. Predict the output of the following:
D={ }
T=("Raj","Anu","Nisha","Lisa")
for i in range(1,5):
D[i]=T[i-1]
print(D)
14. Predict the output of the following:
S="UVW"
L=[10,20,30]
D={ }
N=len(S)
for i in range(N):
D[L[i]]=S[i]
for K,V in D.items():
print(K,V,sep="*",end=",")

APPAN RAJ D PGT- CS/IP 61


15. What will be the output, given by the following piece of code:
D1= {"A":12, "B": 6, "C" : 50, "D" : 70}
print (50 in D1,"C" in D1,sep="#")
16. Predict the output of the following:
P=1400
D={'KTM':45,'RoyalEnfield':75,'Jawa':33,'TVS':89,
'Yamaha':111}
for j in D:
if(len(j)>5):
P=P-D[j]
print(j)
X={'Suzuki':1000,'Bajaja':21}
D.update(X)
print(X)
print(D)
print(D.get('Jawa','KTM'))

*****************************************************************

APPAN RAJ D PGT- CS/IP 62


CHAPTER 3 – WORKING WITH FUNCTIONS
PRACTICE QUESTIONS

THEORY QUESTIONS

1. Define Function. Give an example.


2. Write any two Advantages and Disadvantages of Function.
3. Write the difference between the following with example:
(i) Built in function vs User defined function.
(ii) Function Defined in module vs Built in function.
(iii) Actual Parameter vs Formal Parameter.
4. List out various types of Arguments available in Function.
5. Write the difference between the following with an example:
(i) Positional vs Keyword arguments.
(ii) Keyword vs Default arguments.
(iii) Positional arguments vs Default.
(iv) Local vs global variable.
(v) Call By value vs Call by reference.
6. What is the purpose of the following keywords in function:
(i) nonlocal (ii) global
7. What is the meaning of return value of a function? Give an
example.
8. What is LEGB?
9. Is it possible to access outer function variable’s value in inner
function? If so how?
***********************************************************************

APPAN RAJ D PGT- CS/IP 63


STATE TRUE OR FALSE
1. Function makes a program more readable and reduces the
program size?
2. In python functions can return only one value.
3. Actual parameters are the parameters specified within a pair of
parentheses in the function definition
4. Python passes parameters by value.
5. Value returning functions should be generally called from inside
an expression.
6. Function header and function definition is same thing.
7. In Python, Keyword arguments are available in function definition.
8. You can call a function only once after defining .
9. The following is a valid function definition (T/F)?_______

def Disp(x=0,y):
print(x,y)
10. User can change the functionality of a built in functions.
11. The variable declared outside a function is called a global variable.
12. The following code is a valid code (T/F)_______?
def Disp(sub1,sub2):
print(sub1,sub2)
Disp(sub=100,sub2=89) #Calling
13. The default valued parameter specified in the function header
becomes optional in the function calling statement.
14. The following Python code is a example of Positional argument
(T/F)
def Swap(x,y):
x,y=y,x

p=90
q=78
Swap(p,q)#Calling
15. Default parameters can be skipped in function call?
16. Variable defined inside functions cannot have global scope?
17. A python function may return multiple values?
18. Positional arguments can follow keyword arguments?
19. If function returns multiple values, then it will return as List.

APPAN RAJ D PGT- CS/IP 64


ASSERTION & REASONING
1. A: The function header ‘def read (a=2, b=5, c):’ is not
correct.
R: Non default arguments can’t follow default arguments.
2. A function code is given as follows:
def study (num = 5):
print(num + 5)
A: We can call the above function either by statement
'study(7)' or 'study( )'.
R: As the function contains default arguments, it depends
on the caller that the above function can be called with
or without the value.
3. A: len( ), type( ), int( ), input( ) are the functions that are
always available for use.
R: Built in functions are predefined functions that are
always available for use. For using them we don’t need
to import any module.
4. A:
def Disp(x,y,z):
print(x+y+z)
z=10
Disp(x=67,y=78,z)

R: The above code depicts the concept of keyword


argument. But, during execution it will show an error.
5. A: Every function returns a value if the function does not
explicitly return a value, then it will return ‘Zero’.
R: Zero is equivalent to None.
6. A: A function is a block of organized and reusable code
that is used to perform a single related action.
R: Function provides better modularity for your
application and a high degree of code reusability.
7. Consider the following code:
x = 100
def study( ):
global x
x = 50
print(x)
study()
A: 50 will be the output of above code.
R: Because the x used inside the function study( ) is of
local scope.

APPAN RAJ D PGT- CS/IP 65


8. A: The number of actual parameters in a function call may
not be equal to the number of formal parameters of the
function.
R: During a function call, it is optional to pass the values
to default parameters
9. A: The function definition calculate (a, b, c=1, d) will give
error.
R: All the non-default arguments must precede the default
arguments.
10. A: Key word arguments are related to the function calls
R: When you use keyword arguments in a function call,
the caller identifies the arguments by the parameter
name.
11. A: The default arguments can be skipped in the function
call.
R: The function argument will take the default valueseven
if the values are supplied in the function call
12. A: global keyword is used inside a function to enable the
function alter the value of a global variable.
R: A global variable cannot be accessed by a function
without the use of global keyword.
13. A: Keyword arguments were the named arguments with
assigned values being passed in the function call.
R: Default arguments cannot be skipped while calling the
function while keyword arguments are in function call
statement.
14. A: Keyword arguments are related to function calls.
R: When you use keyword arguments in a function call, the
caller identifies the arguments by the values passed.
15. A: If the arguments in function call statement match
the number and order of arguments as defined in the
function definition, such arguments are called
positional arguments.
R: During a function call, the argument list first contains
default argument(s) followed by positional argument(s).

APPAN RAJ D PGT- CS/IP 66


16. A: A function header has been declared as
def MYFUN(A, B=30):
The function call MYFUN(20, 60, B=80)
will give an error.
R: During a function call, the same parameter
should not be provided two values.

17. A: The writerow function of csv module takes a


list having length equal to the number of
columns in CSV file.
R: The data inside a CSV file is stored in the
form of a string.
18. A: Python allows function arguments to have default
values; if the function is called without the argument,
the argument gets its default value.
R: During a function call, the argument list first contains
default argument(s) followed by positional argument(s).
19. A: A CSV file stores data in rows and the values in
each row is separated with a separator, also known as
a delimiter.
R: You cannot change the by default comma as a value
separator.
20. A: Global variable is declared outside the all the
functions.
R: It is accessible through out all the functions.
21. A: If the arguments in function call statement
match the number and order of arguments
as defined in the function definition, such
arguments are called positional arguments.

R: During a function call, the argument list first contains


default argument(s) followed by positional argument(s).
22. A: A variable is still valid if it is not defined inside the
function. The values defined in global scope can be
used.
R: Python used LEGB rule to resolve the scope of a
variable.
23. A: When passing a mutable sequence as an argument,
function modifies the original copy of the sequence.
R: Function can alter mutable sequences passes to it.

APPAN RAJ D PGT- CS/IP 67


24. A: Key word arguments are related to function calls.
R: When you use keyword arguments in function call, the
caller identifies the arguments by the parameter name.
25. A: Keyword arguments are related to the function calls
R: When you use keyword arguments in a function call,
the caller identifies the arguments by the parameter
name.
OBJECTIVE TYPE QUESTIONS (MCQ)
1. When large programs are broken down into smaller units known
as…
(a) sub program (b) functions
(c) class (d) None of the above
2. Select which of the following is NOT TRUE for Python function:
(a) A function only executes when it is called and we can
reuse it in a program.
(b) In a python function a keyword argument can not be
followed by a positional argument.
(c) A Python function can return multiple values.
(d) Python function doesn’t return anything unless and until
you add a return statement.
3. Which of the following is a valid function name?
(a) start_function( ) (b) start function( )
(c) start-function( ) (d) All of the above
4. Which of the following functions header is correct?
(a) def study(a=2, b=5, c) : (b) def study(a=2, b, c=5) :
(c) def study(a, b=2, c=5): (d) None of the above
5. The values being passed through function-call statement are
called________________.
(a) Arguments (b) Parameter
(c) Values (d) None of these
6. These are predefined functions that are always available for use.
For using them we don’t need to import any module.
(a) Built in function (b) Predefined function
(c) User defined (d) None of the above
7. Aman wants to write a function in python. But he doesn’t know
how to start with it! Select the keyword used to start a function out
of the following:
(a) function (b) start (c) def (d) fun
8. How many values can be returned by a function in python? (a) 0
(b) 1 (c) more than one (d) 2

APPAN RAJ D PGT- CS/IP 68


9. Python passes arguments to function by
(a) Reference (b) Value
(c) Both (d) None of the above
10. Which of the following is not a part of the python function?
(a) function header (b) return statement
(c) parameter list (d) function keyword
11. A variable created or defined in a function body is known as…
(a) local (b) global (c) built-in (d) instance
12. What will be output of following code:
X = 50
def funct(X):
X=2
funct (X)
print("X is now:", X)
a) X is now: 50 b) X is now: 2
c) Error d) None of the above
13. Predict the output of the following code:
def Super():
x=10
y=8
assert x>y, 'X too Small'
Super()

(a) Assertion Error (b) 10 8 (c) No output (d) 108


14. For a function header as follows:
def cal(x,y=20):
Which of the following function calls will give an error?
(a) cal(15,25) (b) cal(x=15,y=25) (c) cal(y=25) (d) cal(x=25)
15. The values received in function definition/header statement are
called ___________ .
(a) Arguments (b) Parameter (c) Values (d) None
What will be the output of the following code:
16. def calculate(a, b):
return a+b, a-b
res = calculate(7, 7)
print(res)
(a) (14,0) (b) [14, 0] (c) 14 (d) 0
17. By default all functions will return ________?
18. In which part of memory does the system stores the parameter and
local variables of function call.
(a) Heap (b) Stack
(c) Both a and b (d) None of the above

APPAN RAJ D PGT- CS/IP 69


19. When you use multiple type argument in function then default
argument take place_______
(a) At beginning (b) At end
(c) Anywhere (d) None of the above
20. A Function that does not have any return value is known
as……………….
(a) Library function (b) Void function
(c) Fruitful function (d) None of the above
21. Which of the following is not a part of the python function?
(a) Function header (b) Return statement
(c) Parameter list (d) Function keyword
22. A variable created or defined within a function body is
(a) local (b) global (c) built in (d) instance
23. In _______________ arguments we can skip the default argument,
but all the arguments should match the parameters in the function
definitions.
(a) keyword (b) required
(c) default (d) None of the above.
24. Predict the output of the following code:
def max_of_two(x,y):
if x > y: (a) 3 (b) 6
return x
else: (c) -5 (d) error
return y
def max_of_three( x,y,z ):
return max_of_two( x, max_of_two(y,z))

print(max_of_three(3, 6, -5))
25. By default if you return multiple value separated by comma, then it
is returned as
(a) List (b) Tuples (c) String (d) None of the above.
26. Find the output of following code :
x=100
def study(x):
global x
x=50
print(“Value of x is :”, x)
a. 100 b. 50 c. Error d. None of the above

APPAN RAJ D PGT- CS/IP 70


27. What will be the output of the following Python code?
def change(i = 1, j = 2):
i=i+j
j=j+1
print(i, j)
change(j = 1, i = 2)

(a) An exception is thrown because of conflicting values


(b) 1 2
(c) 3 3
(d) 3 2
28. Predict the output of the following code:
def Findoutput():
L="earn" (a)EArn (b)EA3n
X=" "
L1=[] (c)EA34 (d)EARN
Count=1
for i in L:
if i in ['a','e','I','o','u']:
X=X+i.swapcase()
else:
if(Count%2!=0):
X=X+str(len(L[:Count]))
else:
X=X+i
Count=Count+1
print(X)

Findoutput()
29. If a function doesn’t have a return statement, which of the
following does the function return?
(a) int (b) null (c) None
(d) An exception is thrown without the return statement
30. The values being passed through a function call statements are
called
(a) Actual parameter (b) Formal parameter
(c) default parameter (d) None of these
31. How many types of arguments are there in function?
(a) 1 (b) 2 (c) 3 (d) 4

APPAN RAJ D PGT- CS/IP 71


32. Predict the output of the following code:
def fun(x):
yield x+1
g=fun(8)
print(next(g))
(a) 8 (b) 9 (c) 7 (d) Error
33. Predict the output of the following code:
def New(x):
yield x+1
print("Hi")
yield x+2
G=New(9)
(a) Error (b) Hi (c) Hi (d) No output
10
12
34. Consider square numbers defined as follows:
compute(1) = 1
compute(N) = compute(N-1) + 2N-1
According to this definition, what is compute (3)?
(a)compute(3) = compute(2) +compute(1)
(b)compute(3) = compute(2) -2*3+1
(c)compute(3) = compute(2) + 2*3-1
(d)compute(3) = compute(3) +2*3-1
35. Predict the output of the following code:
def fun1():
x=20 (a) 10
def fun2(): (b) 20
nonlocal x (c) Error
x=10 (d) None of the above
print(x)
fun1()

APPAN RAJ D PGT- CS/IP 72


2 MARKS/3 MARKS
1. (a) Differentiate between positional parameters and default
Parameters with suitable example program for each.
(b) How can a function return multiple values? Illustrate
with an example program.
2. Rewrite the following program after finding the error(s)
DEF execmain():
x = input("Enter a number:")
if (abs(x)=x):
print ("You entered a positive number")
else:
x=*-1
print "Number made positive:"x
execmain()
3. Uma is a student of class XII. Help her in completing the assigned
code.
……. fun(x, y): # Statement-1
………. a # Statement-2
a = 10
x, y = …………. # Statement-3
b = 20
b = 30
c = 30
print (a, b, x, y) # Statement-4
a, b, x, y = 1, 2, 3,4
……………(50, 100) # Statement-5
fun()
print(a, b, x, y) # Statement-6
1. Write the suitable keyword for blank space in the line marked
as Statement-1.
2. Write the suitable keyword to access variable a globally for
blank space in the line marked as Statement-2.

3. Write down the python to swap the values of x and y for the
blank space in the line marked as Statement-3.
4. Mention the output for the line marked as Statement-4.
5. The missing code for the blank space in the line marked as
Statement-5.

APPAN RAJ D PGT- CS/IP 73


4. Give Output of :
def Change (P, Q=30) :
P=P+Q
Q=P-Q
print (P,"@",Q)
return P
R =150
S= 100
R=Change(R, S)
print(R,"@",S)
S=Change (S)
5. Predict the output of the following code:
def Fun():
G=(i for in range(5,15,3))
print(G)
Fun()
6. Give output of the following code:
def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c)
func(3, 7)
func(25, c = 24)
func(c = 50, a = 100)
7. Predict the output of the following code?
def my_func(a=10,b=30):
a+=20
b-=10
return a+b,a-b
print(my_func(a=60)[0],my_func(b=40)[1])
8. Write a function DIVI_LIST() where NUM_LST is a list of numbers
passed as argument to the function. The function returns two list
D_2 and D_5 which stores the numbers that are divisible by 2 and
5 respectively from the NUM_LST. Example:
NUM_LST=[2,4,6,10,15,12,20]
D_2=[2,4,6,10,12,20] D_5=[10,15,20]

APPAN RAJ D PGT- CS/IP 74


9. Predict the output of the following code:
def Get(x,y,z):
x+=y
y-=1
z*=(x-y)
print(x,'$',y,'#',z)

def Put(z,y,x):
x*=y
y+=1
z*=(x+y)
print(x,'$',z,'%',y)

a=10
b=20
c=5
Put(a,c,b)
Get(a,b,c)
Put(b,a,c)
10. Predict the output of the Python code given below:
value = 50
def display(N):
global value
value = 25
if N%7==0:
value = value + N
else:
value = value - N
print(value, end="#")

display(20)
print(value)
11. 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

APPAN RAJ D PGT- CS/IP 75


12. Consider the program given below and justify the output.
c = 10
def add():
global c
c=c+2
print("Inside add():", c)

add()
c=15
print("In main:", c)

Output:
Inside add() : 12
In main: 15
What is the output if “global c" is not written in the function
add()?
13. Predict the output of the following code:
L=5
B=3
def getValue():
global L, B
L = 10
B=6
def findArea():
Area = L * B
print("Area = ", Area)
getValue()
findArea()
14. Predict the output of the following code:
def process_strings():
words = ['Python', 'Java', 'C++', 'JavaScript']
result = ['', '', '', '']
index = 0
for word in words:
if word[-1] in ['n', 't']:
result[index] = word.upper()
index += 1
else:
result[index] = word.lower()
index -= 1
print(result) process_strings()#calling function

APPAN RAJ D PGT- CS/IP 76


15. 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)
16. Predict the output of the following code:
def OUTER(Y, ch):
global X, NUM
Y=Y+X
X=X+Y
print(X, "@", Y)
if ch == 1:
X = inner_1(X, Y)
print(X, "@", Y)
elif ch == 2:
NUM = inner_2(X, Y)
def inner_1(a, b):
X=a+b
b=b+a
print(a, "@", b)
return a
def inner_2(a, b):
X = 100
X=a+b
a=a+b
b=a-b
print(a, "@", b)
return b

X, NUM = 100, 1
OUTER(NUM, 1)
OUTER(NUM, 2)
print(NUM, "@", X)
17. Rewrite the correct program:
Def fun():
x = input("Enter a number")
for i in range[x):
if (int(s.fabs(x)) % 2== 0) :
print ("Hi")
Else:
print("Number is odd")

APPAN RAJ D PGT- CS/IP 77


18. Rewrite the code after correcting it and underline the
corrections.
def sum(arg1,arg2):
total=arg1+arg2;
print(”Total:”,total)
return

sum(10,20)
print("Total:",total)
19. Predict the output of the following code:
def hello():
a=['MDU','MS','CGL','TBM']
k=-1
for i in ['MDU','MS','CGL','TBM'][:-2]:
if i in ['A','E','I','O','U']:
a[k]=['MDU','MS','CGL','TBM'][k]
k+=1
else:
a[k]=['MDU','MS','CGL','TBM'][k]
k-=1
print(a)
hello()
20. Write a function in python named SwapHalfList(Array), which
accepts a list Array of numbers and swaps the elements of 1st
Half of the listwith the 2nd Half of the list, ONLY if the sum of
1st Half is greaterthan 2nd Half of the list.
Sample Input Data of the list
Array= [ 100, 200, 300, 40, 50, 60],
Output Array = [40, 50, 60, 100, 200, 300]
21. Predict the output of the following code:
L = [5,10,15,1]
G=4
def Change(X):
global G
N=len(X)
for i in range(N):
X[i] += G
Change(L)
for i in L:
print(i,end='$')

APPAN RAJ D PGT- CS/IP 78


22. Predict the output of the following:
def Facto(x):
a=None
b=None
for i in range(2,x//2):
if x%i==0:
if a is None:
a=i
else:
b=i
break
return a,b
S=Facto(4)
print(S)
23. Write a Python Program containing a function
FindWord(STRING,SEARCH), that accepts two arguments :
STRING and SEARCH, and prints the count of occurrence of
SEARCH in STRING. Write appropriate statements to call the
function.
For example, if STRING = "Learning history helps to know
about history with interest in history" and
SEARCH = 'history', the function should display:
The word history occurs 3 times.
24. Rewrite the code after correcting it and underline the
corrections.
Def swap(d):
n={}
values = d.values()
keys = list(d.keys[])
k=0
for i in values
n(i) = keys[k]
k=+1
return n
result = swap({‘a’:1,’b’:2,’c’:3})
print(result)

APPAN RAJ D PGT- CS/IP 79


25. Predict the output of the following:
def fun(s):
k=len(s)
m=""
for i in range(0,k):
if(s[i].isupper()):
m=m+s[i].lower()
elif s[i].isalpha():
m=m+s[i].upper()
else:
m=m+'bb'
print(m)
fun('school2@com')
26. Predict the output of the following code:
def runme(x=1, y=2):
x = x+y
y+=1
print(x, '$', y)
return x,y

a,b = runme()
print(a, '#', b)
runme(a,b)
print(a+b)
27. Write a function Interchange (num) in Python, which accepts a
list num of integers, and interchange the adjacent elements of the
list and print the modified list as shown below: (Number of
elements in the list is assumed as even) Original List:
num = [5,7,9,11,13,15]
After Rearrangement num = [7,5,11,9,15,13]
28. Rewrite the corrected code and underline each correction.
def Tot (Number):
Sum=0
for C in RANGE (1, Number + 1):
Sum + = C
return Sum
print(Tot [3])

APPAN RAJ D PGT- CS/IP 80


29. Predict the output of the following:
def ChangeVal(M,N):
for i in range(N):
if M[i]%5 == 0:
M[i] //= 5
if M[i]%3 == 0:
M[i] //= 3
L=[25,8,75,12]
ChangeVal(L,4)
for i in L :
print(i, end='#')
30. Predict the output of the following:
R=0
def change( A , B ) :
global R
A += B
R +=3
print(R , end='%')
change(10 , 2)
change(B=3 , A=2)
31. Write a function sumcube(L) to test if an element from list L is
equal to the sum of the cubes of its digits i.e. it is an "Armstrong
number". Print such numbers in the list.
If L contains [67,153,311,96,370,405,371,955,407]
The function should print 153,370,371,407
32. Predict the output of the following code:
def result(s):
n = len(s)
m=''
for i in range(0, n):
if (s[i] >= 'a' and s[i] <= 'm'):
m = m + s[i].upper()
elif (s[i] >= 'n' and s[i] <= 'z'):
m = m + s[i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
else:
m = m + '#'
print(m)
result('Cricket') #Calling

APPAN RAJ D PGT- CS/IP 81


33. Predict the output of the following:
def Bigger(N1,N2):
if N1>N2:
return N1
else:
return N2

L=[32,10,21,54,43]
for c in range (4,0,-1):
a=L[c]
b=L[c-1]
print(Bigger(a,b),'@', end=' ')
34. What will be the output of following Python Code:
def change(num):
for x in range(0,len(num),2):
num[x], num[x+1]=num[x+1], num[x]
data=[10,20,30,40,50,60]
change(data)
print(data)
35. Write a function listchange(Arr,n)in Python, which accepts a list
Arr of numbers and n is an numeric value depicting length of the
list. Modify the list so that all even numbers doubled and odd
number multiply by 3 Sample Input Data of the list: Arr= [
10,20,30,40,12,11], n=6 Output: Arr = [20,40,60,80,24,33]
36. Predict the output of the following:
def Compy(N1,N2=10):
return N1 > N2

NUM= [10,23,14,54,32]
for VAR in range (4,0,-1):
A=NUM[VAR]
B=NUM[VAR-1]
if VAR >len(NUM)//2:
print(Compy(A,B),'#', end=' ')
else:
print(Compy(B),'%',end=' ')

APPAN RAJ D PGT- CS/IP 82


37. Predict the output of the following:
p=8
def sum(q,r=5):
global p
p=(r+q)**2
print(p, end= '#')
a=2;
b=5;
sum(b,a)
sum(r=3,q=2)
38. Mr.Raja wants to print the city he is going to visit and the
distance to reach that place from his native. But his coding is not
showing the correct: output debug the code to get the correct
output and state what type of argument he tried to implement in
his coding.
def Travel(c,d)
print("Destination city is ",city)
print("Distance from native is ",distance)
Travel(distance="18 KM",city="Tiruchi")
39. Predict the output of the following:
value = 50
def display(N):
global value
value = 25
if N%7==0:
value = value + N
else:
value = value - N
print(value, end="#")

display(20)#Calling
print(value)
40. Predict the output of the following code:
def f():
global s
s += ' Is Great'
print(s)
s = "Python is funny"
s = "Python"
f()
print(s)

APPAN RAJ D PGT- CS/IP 83


41. Write a function in python named SwapHalfList(Array), which
accepts a list Array of numbers and swaps the elements of 1st
Half of the listwith the 2nd Half of the list, ONLY if the sum of 1st
Half is greaterthan 2nd Half of the list. Sample Input Data of the
list Array= [ 100, 200, 300, 40, 50, 60],
Output Array = [40, 50, 60, 100, 200, 300]
42. Predict the output of the following:
def func(b):
global x
print('Global x=', x)
y=x + b
x=7
z=x-b
print('Local x =',x)
print('y=',y)
print('z=',z)
x=3
func(5)
43. Write a function LShift(Arr,n) in Python, which accepts a list Arr
of numbers and n is a numeric value by which all elements of the
list are shifted to left. Sample Input
Data of the list
Arr= [ 10,20,30,40,12,11], n=2
Output Arr = [30,40,12,11,10,20]
44. Predict the output of the following:
def change(A):
S=0
for i in range(len(A)//2):
S+=(A[i]*2)
return S
B = [10,11,12,30,32,34,35,38,40,2]
C = change(B)
print('Output is',C)

APPAN RAJ D PGT- CS/IP 84


45. Write the output for the following python code:
def Change_text(Text):
T=" "
for K in range(len(Text)):
if Text[K].isupper():
T=T+Text[K].lower();
elif K%2==0:
T=T+Text[K].upper()
else:
T=T+T[K-1]
print(T)

Text="Good go Head"
Change_text(Text)
46. Write a function called letter_freq(my_list) that takes one
parameter, a list of strings(mylist) and returns a dictionary where
the keys are the letters from mylist and the values are the
number of times that letter appears in the mylist, e.g.,if the
passed list is as: wlist=list("aaaaabbbbcccdde")
then it should return a dictionary as{‘a’:5,’b’:4,’c’:3,’d’:2,’e’:1}
47. Write the output for the following python code:
def Quo_Mod (L1):
L1.extend([33,52])
for i in range(len(L1)):
if L1[i]%2==0:
L1[i]=L1[i] /5
else:

L1[i]=L1[i]%10
L=[100,212,310]
print(L)
Quo_Mod(L)
print(L)

APPAN RAJ D PGT- CS/IP 85


48. Predict the output for the following code:
def test(i, a =[]):
a.append(i)
return a
test(25)
test(32)
s = test(17)
print(s)
49. Write a function in Shift(Lst), Which accept a List ‘Lst’ as argument
and swaps the elements of every even location with its odd location
and store in different list eg. if the array initially contains 2, 4, 1, 6,
5, 7, 9, 2, 3, 10
then it should contain 4, 2, 6, 1, 7, 5, 2, 9, 10, 3
50. Write the output given by following Python code.
x=1
def fun1():
x=3
x=x+1
print(x)
def fun2():
global x
x=x+2
print(x)
fun1()
fun2()
51. Predict the output of the following:
def changer(p, q=10):
p=p/q
q=p%q
print(p,'#',q)
return p
a=200
b=20
a=changer(a,b)
print(a,'$',b)
a=changer(a)
print(a,'$',b)

APPAN RAJ D PGT- CS/IP 86


52. Write a Python function SwitchOver(Val) to swap the even and odd
positions of the values in the list Val. Note : Assuming that the list
has even number of values in it.
For example : If the list Numbers contain [25,17,19,13,12,15] After
swapping the list content should be displayed as
[17,25,13,19,15,12]
53. Define a function ZeroEnding(SCORES) to add all those values in
the list of SCORES, which are ending with zero (0) and display the
sum. For example : If the SCORES contain [200, 456, 300, 100,
234, 678] The sum should be displayed as 600
54. Determine the output of the following code fragments:
def determine(s):
d={"UPPER":0,"LOWER":0}
for c in s:
if c.isupper( ):
d["UPPER"]+=1
elif c.islower( ):
d["LOWER"]+=1
else:
pass
print("Original String:",s)
print("Upper case count:", d["UPPER"])
print("Lower case count:", d["LOWER"])
determine("These are HAPPY Times")
55. Write a function in Display which accepts a list of integers and its
size as arguments and replaces elements having even values with
its half and elements having odd values with twice its value . eg: if
the list contains 5, 6, 7, 16, 9 then the function should rearranged
list as 10, 3,14,8, 18

APPAN RAJ D PGT- CS/IP 87


56. Predict the output of the Python code given below:
def Alpha(N1,N2):
if N1>N2:
print(N1%N2)
else:
print(N2//N1,'#',end=' ')

NUM=[10,23,14,54,32]
for C in range (4,0,-1):
A=NUM[C]
B=NUM[C-1]
Alpha(A,B)
57. Write a function INDEX_LIST(L), where L is the list of elements
passed as argumentto the function. The function returns another
list named ‘indexList’ that stores theindices of all Non-Zero
Elements of L. For example: If L contains [12,4,0,11,0,56] The index
List will have - [0,1,3,5]
58. Predict the output of the code given below:
def Convert(Old):
l=len(Old)
New=" "
for i in range(0,1):
if Old[i].isupper():
New=New+Old[i].lower()
elif Old[i].islower():
New=New+Old[i].upper()
elif Old[i].isdigit():
New=New+"*"
else:
New=New+"%"
return New

Older="InDIa@2022";
Newer=Convert(Older)
print("New String is: ", Newer)

APPAN RAJ D PGT- CS/IP 88


59. Give output of the following program:
Predict the output of the following code:
def div5(n):
if n%5==0:
return n*5
else:
return n+5
def output(m=5):
for i in range(0,m):
print(div5(i),'@',end=" ")
print('\n')
output(7)
output()
output(3)
60. Write a function INDEX_LIST(S), where S is a string. The function
returnsa list named indexList‘ that stores the indices of all vowels
of S. For example: If S is "Computer", then indexList should be
[1,4,6]
61. Write a function INDEX_LIST(L), where L is the list of elements
passed as argument to thefunction. The function returns another
list named ‘indexList’ that stores the indices of allElements of L
which has a even unit place digit.
For example: If L contains [12,4,15,11,9,56]
The indexList will have - [0,1,5]
*********************************************************

APPAN RAJ D PGT- CS/IP 89


CHAPTER – 4 FILE HANDLING

[TEXT FILE, BINARY FILE AND CSV FILE]

THEORY QUESTIONS [ 2 – MARKS]

1. Define the following: (i) File. (ii) Data File.


2. List out various types of files available in Python.
3. What is Text file, Binary file and CSV file?
4. What is meant by Pickling?
5. What is the advantage of using a csv file for permanent
storage?
6. Write the difference between the following:
(i) Text file and CSV file. (ii) Text file vs Binary File
(iii) Binary file vs CSV file. (iv) open() vs with statement
(iv) Serialization vs de-serialization
(v) pickle.dump() vs pickle.load() (vi) seek() vs tell()
(vii) writerow() vs writerows()
7. List out various types of file modes available in text file.
8. Differentiate between the following:
(i) 'w' vs 'a' (ii) 'w+' vs 'r+'
9. What is the purpose of the following?
(i) csv.writer() (ii) flush() (iii) csv.reader()
10. What is the purpose of the following parameters csv file:
(i) Delimiter (ii) newline
*******************************************************************

APPAN RAJ D PGT- CS/IP 90


ASSERTION & REASONING
1. A: A file is a bunch of bytes.
R: Byte is a unit of memory
2. A: File created by notepad cannot be access in python
program. R: A text file can be created by Notepad.
3. A: The full name of a file or a directory is called Absolute
path.
R: relative path is relative to current working directory
4. A: The relative paths are relative to current working
directory.
R: The relative path for a file always remains same even
after changing the directory.
5. A: When you open a file for writing, if the file does not
exist, an error occurs.
R: When you open a file for writing, if the file exists, the
existing file is overwritten with the new file.
6. A: Text file stores information in ASCII or unicode
characters.
R: In text file, there is no delimiter for a line.
7. A: File can be opened in append mode.
R: In append mode file content does not get overwritten
and user can append the content after existing content.
8. A: EOL character is a line terminator in text file.
R: By default, EOL Character is the new line character in
Text File.
9. A: with statement can be used to open any file, be it csv file
or binary file and while using with statement to open
any file there is no need to close the file.
R: with statement groups all the statements related to file
handling and make sure to close the file implicitly. It
Closes the file even when any error occurs during the
execution of statements in a with statement.
10. A: It's mandatory to mention file mode while opening a file
for reading.
R: By default, the file opens in read mode.
11. A: Binary file stores data in a format understand easily by
the computer hardware.
R: Computer hardware only understand the binary
language.

APPAN RAJ D PGT- CS/IP 91


12. A: File can be opened using open() function and
“with open() as f:” syntax.
R: Once a file is opened it can’t be closed
13. A: pickle.load( ) deserialise the python object
R: Deserialise object process involves conversion of
python object into string.
14. A: CSV files are used to store the data generated
by various social media platforms.
R: CSV file can be opened with MS Excel.
15. A:
d={'a':12, 'b':10}
f=open('data.dat', 'b')
f.write(d)
f.close( ) => Python object d is serialised onto file using file
object f.
R:
d={'a':12, 'b':10}
f=open('data.dat', 'wb')
pickle.dump( d,f)
f.close( ) => Python object d is serialised onto file using file
object f
16. A: If a text file already containing some text is opened in
Write mode the previous contents are overwritten.
R: When a file is opened in write mode the file pointer is
Present at the beginning position of the file.
17. A: The ‘with’ block clause is used to associate a file object
to a file.
R: It is used so that at the end of the ‘with’ block the file
resource is automatically closed
18. A: When we open the file in write mode the content of the
file will be erased if the file already exist.
R: Open function will create a file if does not exist, when
we reate the file both in append mode and write mode.
19. A: The readline( ) method reads one complete line from a
text file.
R: The readline( ) method reads one line at a time ending
with a newline(\n). It can also be used to read a
specified number (n) of bytes of data from a file but
maximum up to the newline character(\n)

APPAN RAJ D PGT- CS/IP 92


20. A: The file access mode ‘a’ is used to append the data in
the file.
R: In the access mode ‘a’ the text will be appended at the
end of the existing file. If the file does not exist, Python
will create a new file and write data into it.
21. A: Python overwrites an existing file or creates a non-
existing file when we open a file with ‘w’ mode .
R : 'a+' mode is used only for write operations
22. A: open() is a method of python.
R: open() method is used to open a file in Python and
it returns a file object called file handle. The file
handle is used to transfer data to and from the file by
calling the function defined in Python’s io module.
23. A: Serialization is the process of transforming data to a
stream of bytes
R: It is also known as Picking
24. A: The The CSV File is delimited File.
R: Only Comma (,) can be use as delimiter in CSV file.
25. A: To specify a different delimiter while writing into a csv
file, delimiter argument is used with csv.writer ().
R: The CSV file can only take a comma as a delimiter
26. A: We can open a CSV file in the same way as a text file for
reading and writing data.
R: A CSV file is a text file that uses a delimiter to separate
values.
27. A: To open a CSV file employee.csv in write mode, we can
give python statement as follows:
fh=open('employee.csv’)
R: If we try to write on a csv file that does not exist, the file
gets Created.
28. A: While writing data to csv file, we set the value of
parameter newline to "" in the open() function to
prevent blank rows.
R: EOL translation is suppressed by using newline="".
29. A: CSV (Comma Separated Values) is a file format for data
storage which looks like a text file.
R: The information is organized with one record on each
line and each

APPAN RAJ D PGT- CS/IP 93


30. A: Binary file is faster than text file, so it is mostly used for
storing data.
R: Text file stores less character as compared to the binary
file.
31. A: with statement can be used to open a file and should be
preferred over other ways to open a file.
R: with statement is a block of statement that makes sure
the file is closed in case of any run-time error and
buffer is cleared to avoid data loss.
32. A: The tell method will stores/get the current location of
the file pointer.
R: Python seek method returns the current position of the
file read/write pointer with the file.
33. A : The tell( ) method returns an integer that specifies the
current position of the file object in the file.
R: Offset can have any of the three values – 0, 1 and 2.
OBJECTIVE TYPE QUESTIONS (MCQ)
TEXT FILE
1. Anu is learning to use word processing software for the first time.
She creates a file with some text formatting features using notepad.
What type of file is she working on?
(a) Text file (b) CSV file (c) Binary file (d) All of the above
2. The _________ files are used to store large data such as images,
video files, audio files etc.
(a) Text (b) Binary (c) CSV (d) None of the Above
3. Which type of the file executes faster?
(a) Text File (b) CSV File (c) Binary File (d) Word File
4. How many types of file path(s) are available in file handling?
(a) 1 (b) 2 (c) 3 (d) 4
5. To open a file Myfile.txt for appending , we can use
(a) F=open("Myfile.txt","a")
(b) F=open(“Myfile.txt","w+")
(c) F=open(r"d:\Myfolder\Myfile.txt","w")
(d) F=open("Myfile.txt","w")
6. What is the use of File Object?
(a) File Object Serves as a link to a file
(b) File Objects are used to read and write data to the file
(c) A file Object is a reference to a file on disk
(d) All of the above

APPAN RAJ D PGT- CS/IP 94


7. Another name of file object is
(a) File handle (b) File name
(c) No another name (d) File
8. In text file each line is terminated by a special character
called ?
(a) EOL (b) END (c) Full Stop (d) EOF
9. What error is returned by following statement, if file
“try.txt” does not exist?
f = open(“try.txt”)
(a) Not Found (b) File Not Found Error
(c) File Does Not Exist (d) No Error
10. Suppose content of ‘mytext.txt’ file is:
"The key to success is focus on goals,not obstacles."
What will be the output of the following code?
file = open("mytext.txt","r")
txt = file.read()
print(file.read(10))
(a) The key to (b) obstacles. (c) Error (d) No Output
11. Which of the following statements is correct regarding file access
modes?
(a) In ‘r’ mode, we can read and write data from/in the file.
(b) In ‘a’ mode, the existing data will be over-written if the
file exists.
(c) In ‘w’ mode, the data in the file is retained and new data
will be appended to the end.
(d) In ‘a+’ mode, both reading and writing operations can
take place and new data is appended to the end of the
existing file.
12. Which of the following statements is used to open a text
file to add new contents at the end of the already existing
text file named ‘mydiary.txt’?
(i) with open(“mydiary.txt”, ‘w’) as fileobj:
(ii) fileobj = open(“mydiary.txt”, ‘a’)
(iii) with open(“mydiary.txt”,’a’) as fileobj:
(iv) with open(“mydiary”, ‘r+’) as fileobj:
(a) Only (i) (b) Only (ii)
(c) Both (ii) and (iii) (d) Both (i) and (iv)

APPAN RAJ D PGT- CS/IP 95


13. “The information is stored in machine-readable format
and pickle module is used for reading and writing
data from/in the file.” Identify the type of file discussed in the
above lines?
(a) Text files (b) CSV files
(c) Binary file (d) All of the above
14. By default, in which mode a file open.
(a) r (b) w (c) a (d) None of the above
15. While using an open function in which mode a text file will be
created, if it does not exist already.
(a) r+ (b) w (c) Both of the above (d) None of the above
16. While using an open function in which mode a text file
will not be created, if it does not exist already.
(a) r+ (b) r (c) Both of the above (d) None of the above
17. When open a file in append mode, by default new data
can be added at the?
(a) Beginning of the file (b) End of the file
(c) At the middle of the file (d) All of the above
18. Which of the following is not a valid file access mode?
(a) a+ (b) r (c) w (d) b+
19. The _____ file mode is used when user want to write and
read data into Text file.
(a) rb (b) w+ (c) r+ (d) w
20. The _____ file mode is used when user want to append
data into Text file.
(a) rb (b) w+ (c) r+ (d) a
21. Consider the following Pyhton command:
F=open("Myfile","a")
which of the following option cannot be true?
(a) 'Myfile' can be a text file
(b) 'Myfile' can be a csv file
(c) 'Myfile' can be a binary file
(d) 'Myfile' will be created if not exist
22. Which of the following is not true for the Python command:
F=open("Story.txt",'a+')
(a) More text can be written into "Story.txt"
(b) Content of the file "Story.txt" can be read.
(c) Content of the file "Story.txt" can be modified
(d) Command generate error, if the file "Story.txt" does not
exists.

APPAN RAJ D PGT- CS/IP 96


23. Which method is used to write multiple strings/lines in a
text file?
(a) write() (b) writeline()
(c) writelines() (d) writesingle()
24. Which function is used to read single line from file?
(a) readline() (b) readlines()
(c) readstatement( ) (d) readfulline()
25. The readlines() method returns
(a) String (b) A List of integers
(c) A list of characters (d) A List of Lines
26. To read 4th line from text file, which of the following statement is
true?
(a) dt = f.readlines()
print(dt[3])
(b) dt=f.read(4)
print(dt[3])
(c) dt=f.readline(4)
print(dt[3])
(d) All of these
27. Suppose the content of "Rhymes.txt" is:
Baa baa black sheep,
Have you any wool?
What will be the output of the following code?
F=open("Rhymes.txt")
S=F.read()
L=S.split()
for i in L:
if len(i)%3!=0:
print(i,end=" ")
(a) Baa baa you any (b) black have wool?
(c) black sheep, have wool? (d) Error
28. seek() is a method of?
(a) csv module (b) pickle module
(c) text module (d) file object

APPAN RAJ D PGT- CS/IP 97


29. Examine the given Python code and select the best purpose of
the program from the given options:
F=open("Poem.txt",'r')
print(len(F.readline().split()))
F.close()
(a) To count the number of words present in the file.
(b) To count the number of lines present in the file.
(c) To count the number of characters present in the file.
(d) To count the number of words present in the first line of
the file.
30. To read the remaining lines of the file from a file object F,
we use________
(a) F.read (b) F.read() (c) F.readlines() (d) F.readline()
31. Consider the following Python Program:
F=open("Poem.txt","r")
T=F.readline()
Identify the data type of T:
(a) String(str) (b) List (c) Tuple (d) Dictionary
32. In which format does the readlines( ) function give the
output?
(a) Integer type (b) list type (c) string type (d) tuple type
33. What is the difference between r+ and w+ modes?
(a) No difference.
(b) In r+ mode, the pointer is initially placed at the
beginning of the file and for w+, the pointer is placed
at the end.
(c) In w+ mode, the pointer is initially placed at the
beginning of the file and for r+, the pointer is placed at
the end.
34. Consider the file "Rhythm.txt": Power to Empower
What will be the output of the following code?
fileobj = open('forest.txt', 'r')
R1 = (fileobj.readline().split())
for word in R1:
for ch in range(len(word)-1,-1,-1):
print(word[ch],end='')
print(end='')
fileobj.close()
(a) rewoPot.rewopmE (b) rewopmE rewoPot
(c) Empower. to Power (d) Power Empower. to

APPAN RAJ D PGT- CS/IP 98


35. Suppose the context of “Rhymes.txt” is
Hickory Dickory Dock
The mouse went up the clock
What will be the output of the following Python code?
f=open(“Rhymes.txt”)
l=f.readlines()
x=["the","ock"]
for i in l:
for w in i.split():
if w in x:
print(w,end="*")
(a) the* (b) the*the* (c) Dock*the*clock* (d) error
36. What is the use of seek() method in files?
(a) sets the file‟s current position at the offset
(b) sets the file‟s previous position at the offset
(c) sets the file‟s current position within the file
(d) none of the mentioned
37. The syntax of seek() is: file_object.seek(offset [,
reference_point]) What is reference_point indicate?
(a) Reference_point indicates the starting position of the file
object.
(b) Reference_point indicates the ending position of the file
object.
(c) Reference_point indicates the current position of the file
object.
(d) All of the above.
38. The syntax of seek() is:file_object.seek(offset [,
reference_point]) What all values can be given as a reference
point?
(a)1 (b) 2 (c) 0 (d)All of the above
39. What happens if no arguments are passed to the seek()?
(a) file position is set to the start of file
(b) file position is set to the end of file
(c) file position remains unchanged
(d) results in an error

APPAN RAJ D PGT- CS/IP 99


40. Suppose the content of "Rhymes.txt" is:
One, two, three, four, five
Once I caught a fish alive.
F=open("Rhymes.txt")
S=F.read()
print(S.count('e',20))

(a)20 (b) 1 (c) 3 (d) 6


41. Which statement is used to retrieve the current position within
the file?
(a) fp.seek() (b) fp.tell() (c) fp.loc (d) fp.pos
42. Suppose the content of "Story.txt" is:
Good Morning Madam
F=open("Story.txt")
L=F.read().split()
for W in L:
if W.lower()==W[::-1].lower():
print(W)

(a) Good (b) Morning (c) Madam (d) Error


43. Assume you are reading from a text file from the
beginning and you have read 10 characters. Now you
want to start reading from the 50th character from the
beginning. Which function will you use to do the same?
(a) seek(50,1) (b) seek(50,2)
(c) seek(40,0) (d) seek(50,0)
44. Write the output of the following:
f=open("test.txt","w+")
f.write("File-Handling")
f.seek(0)
a=f.read(5)
print(a)
(a) File(b) File (c) File-H (d) No Output
45. Which of the following functions transfer the data to file Before
closing the file?
(a) flush() (b) close() (c) open() (d) fflush()

APPAN RAJ D PGT- CS/IP 100


46. Write the output of the following:
f=open("test.txt","w+")
f.write("FileHandling")
f.seek(0)
a=f.read(-1)
print(a)
(a) File (b) Handling
(c) File Handling (d) No Output
47. A text file is opened using the statement
f = open(‘story.txt’). The file has a total of 10 lines. Which of the
following options will be true if statement 1 and statement 2 are
executed in order?
Statement 1: L1 = f.readline( )
Statement 2: L2 = f.readlines( )
(a) L1 will be a list with one element and L2 will be list with
9 elements.
(b) L1 will be a string and L2 will be a list with 10
elements.
(c) L1 will be a string and L2 will be a list with 9 elements.
(d) L1 will be a list with 10 elements and L2 will be an
empty list.
48. Consider the following directory structure:

There are three directories under root directory ‘Admin’.


The current working directory is Final. Identify the relative path
name for file ‘Result1.xlsx’.
(a) .\Result1.xlsx
(b) Admin\Final\First Term\Result1.xlsx
(c) ..\First Term\Result1.xlsx
(d) First Term\Result1.xlsx

APPAN RAJ D PGT- CS/IP 101


BINARY FILE
49. What is Binary File?
(a) These files cannot be read by humans directly.
(b) No delimiter for a line
(c) Processing of file is faster than text file
(d) All
50. A Binary file stores information in the form of ______ .
(a) A stream of bytes
(b) A stream of ASCII characters
(c) A stream of UNICODE characters
(d) All of the above
51. What are the examples of Binary file in Python?
(a) .jpeg (b) .gif (c) .bmp (d) All of the above
52. Which module is needed to be imported to work with
binary file?
(a) csv module (b) random module
(c) binary module (d) pickle module
53. The process of converting the structure to a byte stream before
writing to the file is known as ______.
(a) Pickling (b) Unpickling (c) Conversion (d) Changing
54. Name the Python module need to be imported to invoke the
function load()?
(a) csv (b) pickle (c) sql (d) binary
55. Which of the following is not a correct statement for
binary files?
(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’
56. Which of the following file mode will refer to the BINARY mode?
(a) binary (b) b (c) bin (d) w
57. Which file mode is invalid?
(a) ab (b) rb+ (c) wb (d) rw
58. Which file mode is valid?
(a) b+ (b) rb+ (c) rw+ (d) rw

APPAN RAJ D PGT- CS/IP 102


59. Which command is used to open a binary file in Python in
append mode?
(a) F = open("Data.dat","ab")
(b) F = open("Data.dat", "wb")
(c) F = open("Data.dat", "rb") (d) None of the Above
60. Which operations can be performed in Python using "rb+" mode?
(a) Read (b) Write
(c) Append (d) Both Read and Write
61. Which operations can be performed in Python using
"wb+" mode?
(a) Read (b) Write
(c) Append (d) Both Read and Write
62. When we open a Binary file in append mode , by default
new data can be added at the?
(a) Beginning of the file (b) End of the file
(c) At the middle of the file (d) All of the above
63. Which of the following file mode open a file for reading and
writing both in the binary file?
(a) r (b) rb (c) rb+ (d) rwb
64. To open a file c:\scores.dat in binary for reading, we use__:
(a) infile = open("c:\scores.txt", "r")
(b) infile = open("c:\\scores.dat","rb")
(c) infile = open(file = "c:\scores.txt", "r")
(d) infile = open(file = "c:\\scores.txt”, "r")
65. Which function is used to write data in binary mode?
(a) write (b) writelines (c) pickle (d) dump
66. Which function is used to read data in binary mode?
(a) read (b) load (c) pickle (d) dump
67. The method used to serialise the python objects for writing data
in binary file
(a) dump( ) (b) open( ) (c) write( ) (d) serialise( )
68. The method used to unpickling the data from a binary file
(a) unpickle( ) (b) load( ) (c) deserialise( ) (d) read( )

APPAN RAJ D PGT- CS/IP 103


69. Which of the following functions can accept more than
one positional argument?
(a) pickle.load( ) (b) pickle.dump( )
(c) pickle.loads( ) (d) None of these
70. Fill in the blank in the given code :
import pickle
f = open("data.dat", "wb")
L = [1, 2, 3]
pickle._______
f.close()
(a) dump(L,f) (b) dump(f,L) (c) load(L,f) (d) load(f,L)
71. Raja is working on a binary file and he wants to write
data from a list to a binary file. Consider list object as l1,
binary file "sum_list.dat", and file object as f. Which of
the following can be the correct statement for her?
(a) f = open(‘sum_list’,’wb’); pickle.dump(l1,f)
(b) f = open(‘sum_list’,’rb’); l1=pickle.dump(f)
(c) f = open(‘sum_list’,’wb’); pickle.load(l1,f)
(d) f = open(‘sum_list’,’rb’); l1=pickle.load(f)
72. Find output of following code
import pickle
fileobject=open(‘data.dat’ , ‘wb’)
L=[3,4,5,9]
pickle.dump(L, fileobject)
fileobject.close( )
fileobject=open(‘data.dat’ , ‘rb’)
print( pickle.load(fileobject)[1]*2)
fileobject.close( )
(a) [3, 4, 5, 9 ] (b) [6,8,10,18] (c) 6 (d) 8
73. ____ function return the current position of the file pointer.
(a) tell() (b) seek()
(c) both A and B (d) None of the above
74. f.seek(10,0) will move 10 bytes forward from _______.
(a) beginning (b) End
(c) Current (d) None of the above
75. Which statement will move file pointer 10 bytes backward from
end position.
(a) F.seek(-10,2) (b) F.seek(10,2)
(c) F.seek(-10,1) (d) None of the above

APPAN RAJ D PGT- CS/IP 104


Aman opened the file “myfile.dat” by using the following syntax.
76. His friend told him few advantages of the given syntax. Help him
to identify the correct advantage.
with open("myfile.dat", 'ab+') as fobj:
(a) In case the user forgets to close the file explicitly the file
will closed automatically.
(b) File handle will always be present in the beginning of the
file even in append mode.
(c) File will be processed faster
(d) None of the above.
CSV FILE
77. Which of the following is a task cannot be done or difficult with
CSV module?
(a) Storing data in tabular form (b) Finding data uniquely
(c) Saving data permanently (d) All of these
78. Which is the correct way to import a csv module?
(a) import csv (b) from csv import *
(c) None of the above (d) Both A & B
79. How many delimiters we can use in CSV file?
(a) 1 (b) 3 (c) 4 (d) 6
80. CSV files are Comma Separated Values saved as a ______
(a) Text file (b) Binary File
(c) MySQL table (d) Random file
81. In regards to separated value in files such as .csv and .tsv,
what is the delimiter?
(a) Any character such as the comma (,) or tab ;) used to
Separate the column data.
(b) Delimiters are not used
(c) Only the comma (,) character is used in the file
(d) Any character such as the comma (,) or tab ;) used to
separate the row data.
82. Which of the following statement(s) are true for csv files?
(a) Existing file is overwritten with the new file if already
exist.
(b) If the file does not exist, a new file is created for writing
purpose.
(c) When you open a file for reading, if the file does not
exist, an error occurs.
(d) All of the above.

APPAN RAJ D PGT- CS/IP 105


83. Which of the following is a function of csv module?
(a) writerrow() (b) reading() (c) writing() (d) readline()
84. The writer() function of csv module has how many
mandatory parameters?
(a) 4 (b) 3 (c) 2 (d) 1
85. To read the entire content of the CSV file as a nested list
from a file object infile, we use __________ command.
(a) infile.read() (b) infile.reader()
(c) csv.reader(infile) (d) infile.readlines()
86. Which of the following is not a valid mode to open CSV file?
(a) a (b) w (c) r (d) ab
87. Which of the following Python statement is used to read the
entire content of the CSV file as a nested list from a file object
infile?
(a) infile.read() (b) infile.reader()
(c) csv.reader(infile) (d) infile.readlines()
88. When iterating over an object returned from csv.reader(),
what is returned with each iteration? For example, given the
following code block that assumes csv_reader is an object
returned from csv.reader(), what would be printed to the console
with each iteration?
for item in csv_reader:
print(i)
(a) The individual value data that is separated by the
delimiter.
(b) The row data as a list.
(c) The column data as a list.
(d) The full line of the file as a string.
89. Read following statement about features of CSV file and select
which statement is TRUE?
S1: Only database can support import/export to CSV format.
S2: CSV file can be created and edited using any text editor
S3: All the columns of CSV file can be separated by comma
only.
(a) S1 and S2 (b) S2 and S3 (c) S2 (d) S3

APPAN RAJ D PGT- CS/IP 106


90. The command used to skip a row in a CSV file is
(a) next() (b) skip() (c) omit() (d) bounce()
91. Which of the following parameter needs to be added with open
function to avoid blank row followed by each row in the CSV file?
(a) quotechar (b) quoting (c) newline (d) skiprow
92. EOL character used in windows operating system in CSV
files is: (a) \r\n (b) \n (c) \r (d) \0
93. To write data into CSV from python console, which of the
following function is correct?
a) csv.write(file) b) csv.writer(file)
c) csv.Write(file) d) csv.writerow()
94. What is the output of the following program?
import csv
d=csv.reader(open('city.csv'))
for row in d:
print(row)
break
If the file called city.csv contains the following details
Bhubaneshwar, Kolkata,Guwahati, Silchar
(a) Guwahati, Silchar
(b) Bhubaneshwar, Kolkata
(c) Bhubaneshwar, Kolkata
Guwahati, Silchar
(d) Bhubaneshwar Guwahati
************************************************************

APPAN RAJ D PGT- CS/IP 107


PREDICT THE OUTPUT OF THE FOLLOWING QUESTIONS
1. Suppose the content of "Myfile.txt" is :-

What will be the output of the following code?


myfile = open("Myfile.txt")
record = myfile.readlines()
print(len(record))
myfile.close()
2. Suppose the content of “Essay.txt" is :-

What will be the output of the following code?


myfile = open("Essay.txt")
line_count = 0
data = myfile.readlines()
for line in data:
if line[-2] in 'Rr':
line_count += 1
print(line_count)
myfile.close()
3. Suppose the content of
“Story.txt" is :-
What will be the content of
the file “Poem.txt” after
execution of following
Python Code?
File1 = open("Story.txt")
File2 = open("Poem.txt", ‘w’)
content = File1.read()
data=content.split()
for word in data:
if 'o' in word :
File2.write(word+“ ”) File1.close() File2.close()
APPAN RAJ D PGT- CS/IP 108
4. The following program copies all record from binary file games.dat
to athelete.dat. Complete the missing statement
import pickle as pk
file1=open("games.dat","rb")
file2=open("athelete.dat","wb")
try:
while True:
_________________ # statement-1 : to read record
_________________ # statement-2 : to write record
except EOFError:
print("file copied ")
file1.close() file2.close()
5. Suppose the content of “story.txt" is :-
Always Think Positive
What will be the output of the following Python code?
file1=open("story.txt",'r')
print(file1.tell(),end="#")
file1.seek(7,0)
data=file1.read(5)
print(data) file1.close()
6. Fill the Blank
fobj = open (“STUDENT.DAT”, “rb”)
num =0
try:
while True:
rec = ___________ # Statement1 to read object
if ___ > 80: # Statement2 to compare the student
attribute with marks
print (rec[0], rec[1], rec[2], sep=”\t”)
num = num +1
except:
fobj.close ( ) print(num)
*************************************************************

APPAN RAJ D PGT- CS/IP 109


TEXT FILE (3 – MARKS)
1. Write a method in Python to read lines from a text file INDIA.TXT,
to find and display the occurrence of the word 'India'.
2. Write a Python function which reads a text file “poem.txt” and
prints the number of vowels in each line of that file, separately.
3. Write a method/function BIGLINES() in Python to read lines from a
text file CONTENT.TXT, and display those lines, which are bigger
than 20 characters.
4. Write a function COUNTTEXT( ), which reads a text file Book.txt
and displays all the words of the file whose length is more than 3
or those which start with ‘A’ or ‘a’ . in the form of a list. For
example, if the Book.txt file contains
India is my country. They are studying.
then the output should be: [“India”, “country”, “They”, “are”,
“studying”]
5. Write a Python program that writes the reverse of each line in
“input.txt” to another text file “output.txt”. Eg: if the content of
input.txt is:
The plates will still shift
and the clouds will still spew.
The content of “output.txt” should be:
tfihs llits lliw setalp ehT
.weps llits lliw sduolc eht dna
6. Write a function named COUNT_CHAR() in python to count and
display number of times the arithmetic operators
(+,-,*,/) appears in the file “Math.txt” .
Example:
Solve the following:
1.(A+B)*C/D 2.(A-B)*(A+B)/D-(E/F)
3. A+B+C/D*(E/F)
The function COUNT_CHAR() must display the output as
Number of ‘+’ sign is 4 Number of ‘-‘ sign is 2
Number of ‘*’ sign is 3 Number of ‘/’ sign is 5
7. Write a function V_COUNT() to read each line from the text file and
count number of lines begins and ends with any vowel.
8. Write a user-defined function named Count() that will read the
contents of text file named“Report.txt” and count the number of
lines which starts with either "I" or "M".
9. Write a function/method DISPLAYWORDS( ) in python to read lines
from a text file STORY.TXT and display those words, which are less
than 4 characters.

APPAN RAJ D PGT- CS/IP 110


10. Write a function stats( ) that accepts a filename and reports the
file’s longest line.
11. Write a function countdigits() in Python, which should read each
character of a text file “marks.txt”, count the number of digits and
display the file content and the number of digits.
Example: If the “marks.txt” contents are as follows:
Harikaran:40, Atheeswaran:35, Dahrshini:30, Jahnavi:48
The output of the function should be:
('Total number of digits in the file:', 8)
12. Write a function in Python to count the number of lines in a text
file ‘STORY.TXT’which is starting with an alphabet ‘A’.
13. Write a method SHOWLINES() in Python to read lines from text file
TESTFILE.TXT‘ and display the lines which do not contain 'ke'.
14. Write a function RainCount() in Python, which should read the
content of a text file ―TESTFILE.TXT and then count and display
the count of occurrenceof word RAIN (case-insensitive) in the file.
Example: If the file content is as follows:
It rained yesterday It might rain today
I wish it rains tomorrow too I love Rain
The RainCount() function should display the output as:
Rain – 2
15. Define a function SHOWWORD () in python to read lines from a
text file STORY.TXT, anddisplay those words, whose length is less
than 5.
16. Write a user defined function in python that displays the number
of lines starting with 'H' in the filepara.txt
17. Write a function in Python to print those words which contains
letter ‘S’ or ‘s’ anywhere in the word in text file “STORY.txt”
18. Write a function COUNTLINES( ) which reads a text file STORY.TXT
and then count anddisplay the number of the lines which starts
and ends with same letter irrespective of itscase.

APPAN RAJ D PGT- CS/IP 111


BINARY FILE [3/5 MARKS]
1. A binary file "STUDENT.DAT" has structure (admission_number,
Name, Percentage). Write a function countrec() in Python that
would read contents of the file "STUDENT.DAT" and display the
details of those students whose percentage is above 75. Also
display number of students scoring above 75%
2. A binary file “Book.dat” has structure:
[BookNo, Book_Name, Author,Price].
i. Write a user defined function CreateFile() to input data
for a recordand add to Book.dat.
ii. Write a function CountRec(Author) in Python which
accepts theAuthor name as parameter and count and
return number of books bythe given Author are stored
in the binary file “Book.dat”
3. A binary file “Toy.dat” has structure:
[TID, Toy, Status, MRP].
i. Write a user defined function CreateFile() to input data
for a record and add to "Toy.dat"
ii. Write a function OnOffer() in Python to display the detail
of those Toys, which has status as “ON OFFER” from
"Toy.dat" file.
4. Considering the following definition of dictionary MUL, write a
method in python to search and display all the content in a
pickled file CINEMA.DAT, where MTYPE key of the dictionary is
matching with the value "Comedy".
MUL = {'MNO': _____, 'MNAME": _____, 'MTYPE': _____}
5. A binary file “Book.dat” has structure:
[BookNo, Book_Name, Author, Price].
Write a function CountRec(Author) in Python which accepts the
Author name as parameter and count and return number of books
written by the given Author.

APPAN RAJ D PGT- CS/IP 112


6. Consider a binary file 'INVENTORY.DAT' that stores information
about products using tuple with 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
CSV FILE [5 MARKS]
1. (i) Differentiate between the writerow and writerows
function.
(ii) Write a Program in Python that defines and calls the
following user defined functions:
(a) add() – To accept and add data of an employee to a CSV
file‘EMP.CSV’. Each record consists of a list with
field elements as EId, EName and ESal to store
respectively.
(b) search() - To display the records of the furniture whose
price is morethan 10000
2. (a) What is the use of seek() function ? Write a python
program that defines and calls the following user
defined functions.

(b) Add_book() – To read the details of the books from the


user and write into the csv file named
“book.csv”. The details of the books
stored in a list are book_no, name, author.
Search_book() - To read the author name from the user
and display the books written by the
author.

APPAN RAJ D PGT- CS/IP 113


3. (a) How to open the file using with statement? Write a
python program that defines and calls the user defined
functions given below.
(b) Add_rating() – To read product name and rating from
the user and store the same into the
csv file “product.csv”
Display() – To read the file “product.csv” and display
the products where the rating is above 10
4. Write a program in python that defines and calls the following user
defined functions:
(i) insertData() – To accept and add data of a customer
and add it to a csv file 'customerData.csv’.
Each record should contain a list
consisting customer name, mobile no,
date of Purchase, item purchased.
(ii) Frequency (name) – To accept the name of a customer
and search how many times the customer
has purchased any item. The count
and return the number.
5. A csv file “result.csv” contains record of student in following order
[rollno, name, sub1,sub2,sub3,total]
Initially student total field is empty string as example data is given
below
['1', 'Anil', '40', '34', '90', ''] ['2', 'Sohan', '78', '34', '90', '']
['3', 'Kamal', '40', '45', '9', '']
A another file "final.csv" is created which reads records of
“result.csv” and copy all records after calculating total of marks
into final.csv. The contents of final.csv should be
['1', 'Anil', '40', '34', '90', '164']
['2', 'Sohan', '78', '34', '90', '202']
['3', 'Kamal', '40', '45', '9', '94']
(a) Define a function createcsv() that will create the
result.csv file with the sample data given above.
(b) Define a function copycsv() that reads the result.csv
and copy the same data after calculating total field
into final.csv file.

APPAN RAJ D PGT- CS/IP 114


6. Create a function maxsalary() in Python to read all the records
from an already existing file record.csv which stores the records of
various employees working in a department. Data is stored under
various fields as shown below:

Function should display the row where the salary is maximum.


Note: Assume that all employees have distinct salary.
**************************************************************

COMPLETE THE PROGRAM BY WRITING THE MISSING LINES


[4 – MARKS]
1. Arun is a class XII student of computer science. The CCA in-
charge of his school wants to display the words form a text file
which are less than 4 characters. Do the needful with the
following python code.
def FindWords():
c=0
file=open("NewsLetter.TXT", "____ ") #Statement-1
line = file.____________ #Statement-2
word =______________ #Statement-3
for c in word:
if _____________: #Statement-4
print(c)
________________#Statement-5
FindWords()
(i) Write mode of opening the file in statement-1?
(ii) Fill in the blank in statement-2 to read the data from
the file.
(iii) Fill in the blank in statement-3 to read data word by
word.
(iv) Fill in the blank in statement-4, which display the
word having lesser than 4 characters.
(v) Fill in the blank in Statement-5 to close the file.
(vi) Which method of text file will read only one line of the
file?

APPAN RAJ D PGT- CS/IP 115


2. Anu got some errors while executing the program so she deleted
those lines. As a python programmer guide her to fill the missing
statements.
_____________ # Statement 1
def modify():
e=[ ]
____________ # Statement 2
found=False
T_eno=int(input("enter employee no"))
try:
while True:
____________ # Statement 3
e=pickle.load(f)

if e[0] == T_eno:
e[2]=float(input("enter new salary"))
f.seek(pos)
__________ # Statement 4
found=True
except:
f.close()
if found==True:
print("employee record found and updated")
else:
print("employee record not found and updating not
possible")
(i) Write the statement to import the needed module.
(ii) Write the statement to open the file named "emp.bin"
as per the need of the code.
(iii) Write the statement to store the position of the file
pointer.
(iv) Complete the blank with the statement to write the
object "e" into the file.
3. As a programmer, help Raj to successfully execute the given
task.
import _______# Line 1
def addCsvFile(UserName,PassWord):
f=open(' user.csv','____') # Line 2
newFileWriter = csv.writer(f)
newFileWriter.writerow([UserName,PassWord])
f.close()
def readCsvFile():

APPAN RAJ D PGT- CS/IP 116


with open(' user.csv','r') as newFile:
newFileReader = csv._______(newFile) # Line 3
for row in newFileReader:
print (row[0],row[1])
newFile.______________ # Line 4
addCsvFile(“Arjun”,”123@456”)
addCsvFile(“Arunima”,”aru@nima”)
addCsvFile(“Frieda”,”myname@FRD”)
(a) Name the module he should import in Line 1.
(b) In which mode, Anuj should open the file to add data
into the file.
(c) Fill in the blank in Line 3 to read the data from a csv
file.
(d) Fill in the blank in Line 4 to close the file.
4. Aaruni’s teacher has given her the following incomplete code,
which is creating a binary file namely Mydata.dat and then opens
, reads and displays the content of the created files.
________________ #Fill_Line 1
sqlist = list()
for k in range(10):
sqlist.append(k*k)
fout = ______________ #Fill_Line2A
____________________ #Fill_Line3
fout.close()
fin = __________________ #Fill_Line2B
______________________ #Fill_Line4
fin.close()
print(“Data from file:”,mylist)
Help her complete the above code as per the instructions given
below:
(a) Complete Fill_Line1 so that the required Python library
becomes available to the program.
(b) Complete Fill_Line2A so that the above mentioned
binary file is opened for writing in the file object fout.
Similarly, complete Fill_Line2B, which will open the
same binary file for reading in the file object fin.
(c) Complete Fill_Line3 so that the list created in the code,
namely Sqlist is written in the open file.
(d) Complete Fill_Line4 so that the contents of the open file
in the file handle fin are read in a list namely mylist.

APPAN RAJ D PGT- CS/IP 117


5. import pickle
sturno = int(input("Enter roll number :"))
stuname = input("Enter name:")
stumarks = float(input("Enter marks :"))
Stul = {"RNo. ":sturno, "Name": name, "Marks":stumarks}
with ______________________ as fh: # Fill_Line 1
_____________________ # Fill_Line 2
___________________ as fin: #Fill_Line 3
________________________ #Fill_Line 4
print(Rstu)
if Rstu["Marks"] >= 85:
print("Eligible for merit certificate")
else:
print("Not eligible for merit certificate")
(a) Complete Fill_Line1 so that the mentioned binary file is
opened for writing in fh object using a with statement.
(b) Complete Fill Line2 so that the dictionary Stul's
contents are written on the file opened in step (a).
(c) Complete Fill_Line3 so that the earlier created binary
file is opened for reading in a file object namely fin,
using a with statement.
(d) Complete Fill_Line4 so that the contents of open file in
fin are read into a dictionary namely Rstu.
6. Atharva is a programmer, who has recently been given a task to
write a Python code to perform the following binary file operation
with the help of a user defined function/module :
Copy_new() : To create a binary file new_items.dat and write all
the item details stored in the binary file,tems.dat, except for the
item whose item_id is 101. The data is stored in the following
format : {item_id:[item_name,amount]}
import ____ # Statement 1
def Copy_new():
f1=_____ # Statement 2
f2=_____ # Statement 3
item_id=int(input("Enter the item id"))
item_detail=_____ # Statement 4
for key in item_detail:
if ______: # Statement 5
pickle.____ # Statement 6
f1.close()
f2.close()

APPAN RAJ D PGT- CS/IP 118


(i) Which module should be imported in the program?
(Statement 1)
(ii) Write the correct statement required to open the binary
file "items.dat". (Statement 2)
(iii) Which statement should Atharva fill in Statement 3 to
open the binary file "new_items.dat" and in Statement
4 to read all the details from the binary file "items.dat".
(iv) What should Atharva write in Statement 5 to apply the
given condition and in Statement 6 to write data in the
binary file "new_items.dat".
7. Help to Vaishnavi to complete the following code based on the
requirement given above:
import ______________ #Statement 1
def shift_contact( ):
fin = open(“phonebook.dat”,’rb’)
fblock = open( ) #Statement 2
funblock = open( ___________________ ) #Statement 3
while True :
try:
rec = __________________ # Statement 4
if rec*“blocked”+ == ‘Y’:
pickle___________________ #Statement 5
if rec*“blocked”+ == ‘N’:
pickle__________________ # Statement 6
except: break
(i) Which module should be imported in the program?
(Statement 1)
(ii) Write the correct statement required to open a
blocked.dat and unblocked.dat binary files (Statement
2 and 3)
(iii) which statement should Vaishnavi use in statement 4
to read the data from the binary file, phonebook.dat
(iv) which statement should Vaishnavi use in statement 5 & 6
to write data to theblocked.dat and unblocked.dat

APPAN RAJ D PGT- CS/IP 119


8. Help Raj to complete the program :
__________ #Statement 1
headings = ['Country','Capital','Population']
d=[['India', Delhi',130],['US','Washington',50],[Japan,Tokyo,2]]
f = open('country.csv','w', newline="")
csvwriter = csv.writer(f)
csvwriter.writerow(headings)
_______ #Statement 2
f.close()
f = open('country.csv','r')
csvreader = csv.reader(f)
head = ____ #Statement 3
print(head)
for x in ______: #Statement 4
if int(x[2])>50:
print(x)
a) Statement 1 – Write the python statement that will allow
Sudheer work with csv files.
b) Statement 2 – Write a python statement that will write
the list containing the data available as a
nested list in the csv file
c) Statement 3 – Write a python statement to read the
header row in to the head object.
d) Statement 4 – Write the object that contains the data
that has been read from the file.
*****************************************************************

APPAN RAJ D PGT- CS/IP 120


CHAPTER 5 – INTRODUCTION TO STACK
PRACTICE QUESTIONS

THEORY QUESTIONS
1. What are Data structures?
2. List out the various types of Data structure.
3. Differentiate between primitive and non-primitive data structres.
4. Define Stack.
5. Write the applications of stack.
6. Differentiate between Push and Pop operations in the context of
stacks.
7. At what situation Underflow occurs in Stack?
8. Is Overflow possible in Python in the context of stack?
9. What is meant by peek operation?

ASSERTION & REASONING


1. A: The start index of a stack is -1
R: Stack Data structure can be implemented through list
in Python
2. A: If the size of a stack is 5 and a sixth element is inserted,
then Underflow happens
R: Overflow is a condition which occurs in bounded stack
3. A: A stack has 2 elements in it. If the stack undergoes 3
pop operations one after another then Underflow occurs.
R: Underflow is a condition which occurs when deletion
happens on an empty stack.
4. A: Stack is a linear data structure.
R: A data structure in which elements are organized in a
sequence is called linear data structure.
5. A: Stack is a linear data structure that works on the
principle of FIFO(First In First OUT)
R: The stack is created with the help of a list with some
restrictions. It manages a pointer called stack
pointer (SP) that will increase or decrease by 1, if an
element is entered or removed from the stack.

APPAN RAJ D PGT- CS/IP 121


OBJECTIVE TYPE MCQ
1. What is the name of a data structure in which insertion and
deletion is done from one end only, usually referred to as TOP.
(a) QUEUE (b) STACK (c) LISTS (d) DICTIONARY
2. Stack data structure works on the following principle.
(a) LILO (b)DIFO (c) FIFO (d) LIFO
3. Expand the following term: LIFO
(a) Least in First Out (b) Last in First Out
(c) Last in Fast Out (d) Least in Fast Out
4. Which of the following is not an application of stack in real-life?
(a) Pile of clothes in an almirah
(b) Multiple chairs in a vertical pile
(c) Persons buying movie tickets from a counter
(d) Bangles worn on wrist
5. Traditionally the end of a stack from where PUSH and POP take
place, popularly known as: ______
(a) Front (b) Top (c) LIFO (d) FIFO
6. Which of the following are two basic operations performed on a
stack for insertion and deletion of elements?
(a) INSERT and DELETE (b) ADD and REMOVE
(c) PUSH and POP (d) APPEND and DELETE
7. Inspecting the value at the stack’s top without removing it. (a)
peak operation (b) insert operation
c) pop operation (d) push operation
8. Stacks serve major role in ______________
(a) Simulation of recursion
(b) Simulation of linked list
(c) Simulation of limited resource allocation
(d) Simulation of all data
9. What is the process of inserting data into a stack called?
(a)Create(b)Insert(c) Push(d) Evaluate
10. What is the process of deleting data from a stack called?
(a)Drop (b) Delete (c) Erase (d) Pop
11. Which of the following exception results when we try to add an
element to a full stack?
(a) Underflow (b) Common flow (c) Down flow(d) Overflow
12. Which pointer is associated with a stack?
(a) First (b) Front (c) Rear (d) Top

APPAN RAJ D PGT- CS/IP 122


13. Assume a stack has size 4. If a user tries to push a fifth element
to a stack, which of the mentioned condition will arise?
(a) Underflow (b) Overflow (c)Crash (d) Successful Insertion
14. If a user tries to pop an empty stack, which of the mentioned
condition will arise?
(a)Empty data (b) Overflow (c) Underflow (d) No error
15. Which of the following condition is necessary 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
16. Predict the output of the following Python code.
V = list( )
V.append('Cha') (a)['Cha', 'Bala']
V.append('Bala') (b) ChaBala
V1 = V.pop()
V2 = V.pop() (c) 'Cha' 'Bala'
V3 = V.pop()
(d) IndexError: pop from
print(V1, V2, V3)
empty list
17. Choose correct output for the following sequence of
operations.push(5) push(8) pop push(2) push(5) pop poppop
push(1) pop
(a) 8 5 2 51 (b) 8 5 5 2 1 (c) 8 2 5 5 1 (d) 8 1 2 5 5
18. Anu is assigned a stack program which has a function
push_data() to push elements into a stack which is
divisible by 2. She has newly learnt Python Language and is
facing some difficulty in completing the code. Help her in
completing the code. Incomplete Code:
def push_data(list_all):
for i in range(0,________): # statement2
if i%2==0:
Stack.______ # statement 3
print(Stack) #statement 4

def pop_data():
if ________ ==0: #statement5
print("Empty Stack,Cant pop")
return -1

else:

APPAN RAJ D PGT- CS/IP 123


pop_item=Stack[-1]

Stack.______ #statement6
return pop_item

Stack=_______________________ # statement1
push_data ([20,11,30,15,2])
print(pop_data())
1. Identify the missing code in statement 1.
2. Identify the missing code in statement 2 for completing
the stop parameter in the for loop.
3. Identify the missing function in statement 3 for inserting
Data into the stack.
4. What will be the contents of stack which will be printed
in statement 4?
5. Identify the missing code in statement 5 in pop_data()
function.
6. Identify the missing code in statement 6 for popping the
element in the stack.
3- MARKS
1. Write a function in Python PUSH(Arr), where Arr is a list of
numbers. From this list push all numbers divisible by 5 into a
stack implemented by using a list. Display the stack if it has at
least one element, otherwise display appropriate error message.
2. Write a function in Python POP(Arr), where Arr is a stack
implemented by a list of numbers. The function returns the value
deleted from the stack.
3. Alam has a list containing 10 integers. You need to help him
create a program with separate user defined functions to perform
the following operations based on this list.
● Traverse the content of the list and push the even
numbers into a stack.
● Pop and display the content of the stack. For Example:
If the sample Content of the list is as follows:
N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
Sample Output of the code should be: 38 22 98 56 34 12

APPAN RAJ D PGT- CS/IP 124


4. Jiya has a list containing 8 integers. You need to help her create
a program with two user defined functions to perform the
following operations based on this list.
• Traverse the content of the list and push those numbers
into a stack which is divisible by both 5 and 3.
• Pop and display the content of the stack.
For example: If the sample Content of the list is as follows:
L=[5,15,21,30,45,50,60,75] Sample Output of the code should
be: 75 60 45 30 15
5. Varun has a list containing integers. You need to help him create
a program with separate user defined functions to perform the
following operations based on this list.
● Traverse the content of the list and push the 2 digit
numbers into a stack.
● Pop and display the content of the stack.

For Example:
If the sample Content of the list is as follows:
N=[2, 131, 34, 56, 21, 379, 98, -22, 35, 38]
Sample Output of the code should be:
38 35 -22 98 21 56 34
6. Write the definition of a function POP_PUSH(LPop, LPush, N) in
Python.
The function should Pop out the last N elements of the list LPop
and Push them into the list LPush.
For example :
If the contents of the list LPop are [10, 15, 20, 30]
And value of N passed is 2,
then the function should create the list LPush as [30,20] And the
list LPop should now contain [10, 15]

NOTE : If the value of N is more than the number of elements


present in LPop, then display the message
"Pop not possible"

APPAN RAJ D PGT- CS/IP 125


7. A list contains following record of a doctor:
[Doc_ID, Doc_name, Phone_number, Specialization]
Write the following user defined functions to perform given
operations on the stack named "status":
(i) Push_element() - To Push an object containing Doc_ID
and Doc_nameof doctors who
specialize in Anesthesia 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.
9. Write a function in Python, Push(stack, SItem) where , SItem is
a List containing the details of stationary items in a format like –
[Name , price , Unit , Company , MRP ].
The function should push the company names of those items in
the stack whose price is 10% percent less than its MRP. Also
write a function print_stack( ) to display the Item Names and the
count of Items pushed into the stack.
10. Raja received a message(string) that has upper case and lower-
case alphabet. He want to 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
11. A dictionary R contains the following records:
R={"OM":76, "JAI":45, "BOB":89, "ALI":65, "ANU":90,
"TOM":82}
Write the following user defined functions to perform given
operations on the stack named "STU_NAME"
(i) Push() – Push the keys (name of the student) of the
dictionary into a stack, where the
corresponding value (marks) is greater than
75.
(ii) Pop() – Pop and display the content of the stack.

APPAN RAJ D PGT- CS/IP 126


12. Write a function in Python, Push(KItem), where KItem is a
dictionary containing the details of Kitchen items– {Item:price}.
The function should push the names of those items in a stack
which have priceless 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
13. Two list Lname and Lage contain name of person and age of
person respectively. A list named Lnameage is empty. Write
functions as details given below
(i) Push_na() :- It will push the tuple containing pair of
name and age from Lname and Lage
whose age is above 50.
(ii) Pop_na() : It will remove the last pair of name and age
and also print name and age of removed
person. It should also print “underflow” if
There is nothing to remove.
For example the two lists has following data:
Lname=[‘narender’, ‘jaya’, ‘raju’, ‘ramesh’, ‘amit’,’anu’]
Lage=[45,23,59,34,51,43]
After Push_na() the contains of Lnameage stack is
[(‘raju’,59),(‘amit’,51)]
The output of first execution of pop_na() is
The name removed is amit
The age of person is 51

APPAN RAJ D PGT- CS/IP 127


14. A list contains following record of course details for a University
: [Course_name, Fees, Duration]
Write the following user defined functions to perform given
operations on the stack named 'Univ' :
(i) Push_element(): To push an object containing the
Course_name, Fees and Duration of a
course, which has fees greater than
100000 to the stack.
(ii) Pop_element(): To pop the object from the stack and
display it.

15. A dictionary stu contains rollno and marks of students. Two


empty list stack_roll and stack_mark will be used as stack.
Two function push_stu() and pop_stu() is defined and perfom
following operation
(a) Push_stu() :- It reads dictionary stu and add keys into
stack_roll and values into stack_marks for
all students who secured more than 60
marks.
(b) Pop_stu() :- It removes last rollno and marks from both
list and print "underflow" if there is
nothing to remove
For example:
stu={1:56,2:45,3:78,4:65,5:35,6:90}
values of stack_roll and stack_mark after push_stu()
[3,4,6] and {78,65,90}

APPAN RAJ D PGT- CS/IP 128


16. Given a Dictionary Stu_dict 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 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
*********************************************************************

APPAN RAJ D PGT- CS/IP 129


CHAPTER 6 – INTRODUCTION TO DBMS AND ITS CONCEPTS

PRACTICE QUESTIONS

THEORY QUESTIONS

1. Define Database.
2. Define DBMS and how it is different from RDBMS.
3. List out any two database software names.
4. Define the following: (i) Relation (ii) Tuple (iii) Attribute.
5. What do you mean by term Domain in context of RDBMS? What will
be the domain for an attribute called "Age" of voters of a village?
6. What is View?
7. What is the purpose of Key in RDBMS?
8. Differentiate the following with an example:
(i) Degree and Cardinality of the Relation.
(ii) Candidate Key and Primary Key.
(iii) Alternate Key vs Candidate Key.
(iv) Primary Key vs Alternate Key.
(v) Primary Key vs Foreign Key.

9. Observe the following table and


answer the parts (i) and (ii):

(i) In the above table, can we have Qty as


primary key. [Answer as yes/no]. Justify your
answer.

(ii) What is the cardinality and degree of the


above table?

APPAN RAJ D PGT- CS/IP 130


OBJECTIVE TYPE QUESTIONS
1. RDBMS stands for
(a) Relational Database Management System
(b) Rotational Database Management System
(c) Reliable Database Management System
(d) None of these
2. Each row of data in a relation(table) is called
(a) attribute (b) tuple (c) domain (d) None of these
3. A table has initially 5 columns and 8 rows. Consider the following
sequence of operationsperformed on the table –
i. 8 rows are addedii. 2 columns are added
iii. 3 rows are deletediv. 1 column is added
What will be the cardinality and degree of the table at the end of
above operations?
(a) 13,8 (b) 8, 13 (c) 14,5 (d) 5,8
4. A database can have only one table(True/False)
5. Which one of the following refers to the copies of the same data
(or) information occupying the memory space at multiple places.
(a) Data Repository (b)Data Inconsistency
(c)Data Mining (d)Data Redundancy
6. A ………………is a virtual table that does not really exist in its
own right but is instead derived from one or more underlying base
table(s) in DBMS
(a)SQL (b) map (c) view (d) query
7. A table has 5 rows and 3 columns. A new row is added to it. What
will be its cardinality and degree?
(a)5, 4 (b) 6, 3 (c)6, 4 (d)5, 3
8. The number of attributes in a relation is called the ___________ of
the relation
(a) Degree (b) Cardinality
(c) Domain (d) None of these
9. The number of tuples in a relation is called the ___________ of the
relation
(a) Degree (b) Cardinality
(c) Domain (d) None of these

APPAN RAJ D PGT- CS/IP 131


10. A candidate key that is not the primary key is called
(a) Composite Key (b) Foreign Key
(c) Alternate Key (d) None of these
11. In relational model, tables are called
(a) Domains (b) Relations (c) Tuples (d) None of these
12. ___________ can take NULL values in it
(a)Primary Key
(b)Foreign Key
(c)Both Primary Key and Foreign Key
(d)None of these
13. The term _________ is used to refer to a record in a table.
(a) Attribute (b) Tuple (c) Field (d) Instance
14. Which of the following attributes cannot be considered as a choice
for primary key?
(a) Id (b) License Number (c) Dept_Id (d) Street
15. 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
16. What is the format used for storing date using date datatype?
(a) dd-mm-yy (b) dd-mm-yyyy
(c) mm-dd-yyyy (d) yyyy-mm-dd
17. In MYSQL database, if a table, Alpha has degree 5 and cardinality
3, and another table, Beta has degree 3 and cardinality 5, what
will be the degree and cardinality of the Cartesian product of
Alpha and Beta?
18. A table Can have _______ Primary Key.
(a) 1 (b) 2 (c) It will not take any (d) None of the above.
19. A table Can have _______ Foreign Key.
(a) 1 (b) Exactly 2
(c) More than two (d) None of the above.
************************************************************

APPAN RAJ D PGT- CS/IP 132


3 - MARKS
1. Sagar a cloth merchant creates a table CLIENT with a set of
records to maintain the client’ s order volume in Qtr1, Qtr2, Qtr3
and their total.

Based on the data given above answer the following questions:


(i) Identify the most appropriate column, which can be
considered as Primary key.
(ii) What is the product of degree and cardinality of the
above table ?
(iii) Write the statements to: Update a record present in the
table with data for Qtr2 – 200 , Qtr3 = 600 , total –
sum of all Qtrs where the Client_ID is C660
(OR)
(iii) (a) Delete all records where total is between 500 to 900
(b) Add a column RATINGS with data type integer
whose value must lie between 1 to 5.
2.

(i) Write a query to make Item code as primary key in the


above existing table.
(ii) Write the command to remove the column Discount.
(iii) (a) Write the command to display the structure of the
table infants which is Shop database.
(b) Write the degree and cardinality of the table.
(OR) (Option given for part (iii) only)
(iii) (a) Add a new row with the following values in respective
attributes. Itemcode=106, Item=BathTub,
Datepurchase=2015-10-22, Unitprice=1500
(b) Write the command to display Item, Unitprice in
descending order.

APPAN RAJ D PGT- CS/IP 133


3. Consider the table SALES_DONE to maintain the sales made by
his sales
department.

Based on the above table answer the following questions:


(i) Identify the candidate key, primary key from the above
table.
(ii) He added two more employee in the month of February and if
a new column is added for each month, at the end of May
month what is the degree and cardinality of the table.
(iii) Write the SQL statement to do the following:
(a) Insert the following record into the above table.
106,"Venkatesh Gour",256489,200,300
(b) Change the name of the employee as "Sri Nikethan"
whose emp no is 104.
(OR)
(iii) Write the MYSQL statement for the following:
(a) Add a new column Total_sales of type integer with
NOT NULL constraint.
(b) Fill the column Tot_sales by adding values in Jan
and Feb columns.
4.

(i) Identify the attribute best suitable to be declared as a


Candidate Key(s).
(ii) Write the degree and cardinality of the table Collections.
(iii) Write SQL command to increment the quantity by 20
Wherever quantity is below 50.

APPAN RAJ D PGT- CS/IP 134


(iv) Anu wants to remove the entire data from table
Collections. Which command will she use from the
following:
(a) DELETE FROM Collections; (b) DELETE Collections;
(c) DROP DATABASE CB; (d)DELETE * FROM Collections;
5. Consider the below
given ITEM table:

Write SQL queries for the following:


(i) Display Kitchen and Living items in descending order of
Price
(ii) Display the average price for each Type.
(iii) (a) Display the Stockdate for recently added item.
(b) Display the Itemname whose name ends with ‘s’.
OR (Option for part iii only)
(iii) (a) Delete the Item having price less than 10000.
(b) Update the price of item having NULL price to 1000.
6. Consider the following table ITEMS:

(a) Identify the attributes suitable to be declared as primary


key.
(b) Write the query to add the row with following details
(2010,"Notebook",23,155)

APPAN RAJ D PGT- CS/IP 135


(c)
(i) Abhay wants to remove the table STORE from the
database MyStore, Help Abhay in writingthe
command for removing the table STORE from the
database MyStore.
(ii) Now Abhay wants to display the structure of the table
STORE i.e.name of the attributes and their respective
data types that he has used in the table.
Write the query to display the same.
(OR)
(i) Abhay wants to ADD a new column price with data type
as decimal. Write the query to add the column.

(ii) Now Abhay wants to remove a column price from the table
STORE. Write the query.
7. Mayank creates a table RESULT with a set of records:

(i) Identify the


most appropriate column, which can be
considered as Primary key.
(ii) If two columns are added and 2 rows are deleted from
the table result, what will be the new degree and
cardinality of the above table?
(iii) Write the statements to:
a. Insert the following record into the table
Roll No- 108, Name- Aaditi, sub1- 470, sub2-444,
sub3-475,Grade– I.
b. Increase the sub2 marks of the students by 3%
whose name begins with ‘N’.
OR (Option for part iii only)
(iii) Write the statements to:
a. Delete the record of students securing Grade-IV.
b. Add a column REMARKS in the table with data type
as varchar with 50 characters.

APPAN RAJ D PGT- CS/IP 136


8. Dinesh creates a table COMPANY with a set of 06 records

(a) Identify the most appropriate column, which can be


considered as Primary key.
(b) If 3 columns are added and 2 rows are deleted from the
table result, what will be the new degree and
Cardinality of the above table?
(c) Write the statements to:
(i) delete a record which has C_ID as C24
(ii) Decrease the Fee of all by 500.
9. Consider the table Personal given below:

Based on
the given table, write SQL queries for the following:
(i) Decrease the salary by 5% of personals whose allowance
is known.
(ii) Display Name and Total Salary (sum of Salary and
Allowance) of all personals. The column heading ‘Total
Salary’ should also be displayed.
(iii) Delete the record of personals who have salary greater
than 25000.

APPAN RAJ D PGT- CS/IP 137


10 Navdeep creates a table RESULT with a set of records to maintain
the marks secured by students in Sem1, Sem2, Sem3, and their
divisions. After the creation of the table, he entered data of 7
students in the table.

Based on the data given above answer the following questions:


(i) Identify the columns which can be considered as
candidate keys?
(ii) If 2 more columns are added and 3 rows are deleted
from the table result, what will be the new degree and
cardinality of the above table?
(iii) Write a statement to increase the SEM2 marks by 3%
for the students’ securing marks between 70 to 100.
************************************************************************

APPAN RAJ D PGT- CS/IP 138


CHAPTER 7 – INTRODUCTION TO SQL AND ITS CONCEPTS

PRACTICE QUESTIONS

THEORY QUESTIONS

1. Define SQL.
2. Write the difference between Single row functions and multi
row functions with an example.
3. What is the referential integrity constraint?
4. List out Various commands available under DDL and DML.
5. Write the appropriate command for the following situations:
(i) To Show the structure of the table.
(ii) To Create table/database.
(iii) To List out an existing database name.
(iv) To open an existing database.
(v) To List out existing table name.
6. Define Constraints. List out its types.
7. Differentiate the following with an example:
(i) DBMS vs RDBMS (ii) DDL vs DML (iii) Char vs Varchar
(iv) Primary key vs Unique (v) Primary key vs foreign key
(vi) Default vs NOT NULL
8. Write the appropriate command for the following situation:
(i) To delete structure of the table.
(ii) To add a new attribute in a table.
(iii) To Eliminates redundant data from a Query Result.
(iv) To display the records in ascending order of an attribute.
(v) To modify the structure of the table.
(vi) To delete records of the table.
(vii) To modify the structure of the table.
(viii) To add primary key in an existing table.

APPAN RAJ D PGT- CS/IP 139


9. Categorize following commands into DDL and DML commands:
INSERT INTO, DROP TABLE, ALTER TABLE, UPDATE, SELECT
10. Raj needs to display names of students, who have not been
Assigned any stream or have been assigned Course_name
that ends with "Economics". He wrote the following
command, which did not give the desired result.
SELECT Name, Class FROM Students WHREE
Course_name=Null OR Course_name="%Economics";
Help him to run the query by removing the error and write
the correct query.

11. Write the appropriate operator for the following situation


with its syntax:
(i) To select range of values.
(ii) To Perform Pattern Matching.
(ii) To select partially known string or phrase from a table.
(iii) To select Unknown Record(s) from a SQL table.
12. Differentiate between the following with an example.
(i) IN vs BETWEEN (ii) OR vs IN operator (ii) == vs LIKE
(iii) Wildcards: % (percentage) vs _ (Underscore)
(iv) UPDATE vs ALTER (v) DELETE vs DROP
13. Write the difference between the following SQL Queries:
(i) ALTER TABLE EMP DROP AGE;
(ii) DROP TABLE EMP;
14. Categorize the following commands as DML or TCL:
COMMIT, UPDATE, DELETE, SAVE POINT
15. Give one difference between ROLLBACK and COMMIT
commands used in MySql.
16. Define aggregate functions. List out its types.
17. In SQL, write the name of the aggregate function which
will display the cardinality of a table.

APPAN RAJ D PGT- CS/IP 140


18. Consider the following two commands with reference to a
table, named Employee having a column named
Department.

(a) SELECT COUNT(DEPT) FROM EMPLOYEE;


(b) SELECT COUNT(*) FROM EMPLOYEE;
If these two commands are producing different results,
(i) What may be the possible reason?
(ii) Which command (a) or (b) might be giving a higher value?
19. Differentiate between the following with an example:
(i) Order By Clause vs Group By Clause
(ii) Where Clause vs Having Clause.
20. Neelam, a database administrator needs to display Class
wise total number of students of ‘XI’ and ‘XII’ house. She is
encountering an error while executing the following query:
SELECT CLASS, COUNT (*) FROM STUDENT ORDER BY
CLASS HAVING CLASS=’XI’ OR CLASS= ‘XII’;
Help her in identifying the reason of the error and write
the correct query by suggesting the possible correction (s).
21. Mr. Rehan, a database administrator wants to display
highest salary in each department from table Employee
with columns Ecode, Ename, Salary, Gender, Dept. He is
encountering an error while executing the following query:
SELECT DEPT, MAX(SALARY) FROM EMPLOYEE;
Help her in identifying the reason of the error and write the
correct query by suggesting the possible correction (s).
22. Ram wants to count number of staffs under each category
where the number of staffs is more than 2. He has executed
the following query:

SELECT CATEGORY, SUM(SALARY) FROM HOTEL WHERE


COUNT(*)>2 GROUP BY CATEGORY;

APPAN RAJ D PGT- CS/IP 141


But he got an error. Identify the error(s) and rewrite the query.
Also underline the correction(s) done.
22. What is meant by Joins? List out the various types of joins
in SQL.
23. Define Cartesian product with an example.
24. Write the difference between:
(i) Equi- Join and Cross Join.
(ii) Equi-Join and Natural Join.
STATE TRUE OR FALSE
1. SQL is a programming language.
2. Unique is used to eliminate the duplicate rows from the output in
SQL query.
3. Delete command deletes the table structure and Drop command
deletes the data from a SQL Table .
4. Null (unavailable and unknown) values are entered by the
following command:
5. INSERT INTO TABLE_NAME VALUES (“NULL”);
6. Foreign key column derives its value from the primary key of the
parent table.
7. ALTER TABLE command is used to modify the structure of the
table.
8. DML commands are used to define a database, including
creating, altering, and dropping tables and establishing
constraints.
9. Unique and Primary key constraints are the same.
10. NOT NULL is a constraint that can be defined only at the column
level.
11. DDL is similar to a computer programming language for defining
data structures, especially database schemas.
12. The condition in a WHERE clause in a SELECT query can refer to
only one value.
13. The rows of the result relation produced by a SELECT statement
can be sorted but only by one column.
14. The WHERE clause is used to specify filtering conditions for
groups.

APPAN RAJ D PGT- CS/IP 142


15. The SQL statement: SELECT salary + Comm AS Total FROM Emp;
adds two fields salary and comm from each row together and lists
there results in a column named Total.
16. The BETWEEN operator includes both begin and end values.
17. Logical operators and Relational operators cannot be used together.
18. Update and delete statements are DDL statements.
19. When multiple operators are used in a SQL Query, low precedence
operators are evaluated in last.
20. A user may specify two or more columns as using the SELECT –
DISTINCT clause
21. MIN and MAX can only be used with numeric columns.
22. The SQL keyword GROUP BY instructs the DBMS to group together
those rows that have the same value in a column
23. SUM () function is used to count the total number of records in a
table
24. COUNT () function ignores null values while counting the records.
25. COUNT(*) function ignore duplicates and null values while counting
the records.
26. MAX() function returns an integer field.
27. You can combine all the records that have identical values in a
particular field on a group of fields by using ORDER BY statement.
28. To filter the conditions for groups, WHERE clause is used.
29. Group functions can be applied on any data typesi.e numeric, data,
string.
30. Any attribute which is present in the having clause without being
aggregated must not be present in the group by clause.
31. We can rename the resulting attribute after the aggregation
function has been applied.
32. To avoid a Cartesian product, always include a valid join condition
in a WHERE clause.
33. Understanding the primary and foreign key relationship is not
important to join on the correct columns.
34. COUNT(Fieldname) tallies only those rows that contain a value; it
ignores all null values.

APPAN RAJ D PGT- CS/IP 143


ASSERTION & REASONING
1. A: A Primary Key is used to uniquely identify a
record in a relation.
R: A Primary Key cannot have duplicate value.
2. A: Single row functions work with a single row.
R: A single row function returns aggregated value.
3. A: All the candidate keys are Primary Key.
R: Primary Key is used to uniquely identify a record in a
relation.
4. A: Foreign Key is not used to uniquely identify a record in
relation.
R: Foreign key can take NULL values
5. A: NULL is Special value that is stored when actual data
value is unknown for an attribute.
R: Foreign key can take NULL values
6. A: Each attribute in a relation has a unique name.
R: Sequence of attributes in a relation is immaterial.
7.

A: Select Avg(charges) from Hospital; Output: 166.666667


R: Avg() includes NULL values.
8. A: A unique key cannot serve the purpose of a
Primary Key
R: A unique key attribute can hold null value
9. A: Update is a DDL command.
R: DDL commands are used for defining the schema of the
database.
10. A: Create cs database;
R: Create database database_name help us to create
database.
11. A: Delete is DML command
R: Delete command deletes the table from a database
12. A: Float datatype cannot be used for storing names
R: Char(n) datatype can be used for storing names
13. A: Drop is not a DML command
R: Drop is a TCL command

APPAN RAJ D PGT- CS/IP 144


14. A: Data definition language. Consists of commands used to modify
the metadata of a table. For Example- create table, alter table,
drop table.
R: Data manipulation language. Consist of commands used to
modify the data of a table.
15. A: Suppose there are suppliers from 30 different cities.
A person wants to list only those records of supplier
table who belongs to 'Goa', 'Chennai'
R: IN operator used in SQL queries to specify the list of |
values for searching.
16. A: DELETE is a DML command and used when we want
to remove some or all the tuples from a relation.
R: DROP is a DDL command which removes the
named elements of the schema like relations,
domains or constraints and you can also remove
an entire schema using DROP command.
17. A: ALTER TABLE table_name ADD column_name datatype.
R: Alter table help us to modify the data values of a
given table.
18. A: DELETE FROM relation_name WHERE condition.
R: DELETE is a DML command and used when we want to
remove some or all the tuples from a relation.
19. A: Between operators produces a result set based on
expression within a range.
R: An expression can be written using >= and <= operators
equivalent to Between Operator
20. A: All candidate keys can be used as a primary
key.
R: We can use more than one candidate key as
a primary key.
21. A: Delete, Drop and Truncate are examples of DDL
Commands.
R: DELETE operations can be rolled back (undone), While
DROP and TRUNCATE operations cannot be rolled
back.
22. A: The keyword DISTINCT is used with SELECT command.
R: DISTINCT keyword eliminates duplicate rows
23. A: The LIKE is a Logical operator in SQL is used to search
for character string with the specified pattern using

APPAN RAJ D PGT- CS/IP 145


wildcards in a column.
R: There are three wildcards (%), (_) and (#) used in SQL.
24. A: Cardinality of the resultant table of Cartesian Product of
two tables will be the product of the cardinalities of
these two tables.
R: Cartesian product generates all possible combination of
two tables
25. A: Count(*) and Count(Column Name) returns same
outputs.
R: Null values are not counted by Count()
26. A: Select Dept, count (*) from hospital group by Dept where
count (*)>1; Output: Error
R: Exactly one patient admitted in each Dept.
27. A: Select Max (Name) from hospital; Output: Error
R: Max( ) can only be used with numeric columns
28. A: SQL does not permit distinct with count(*)
R: SQL does not permit distinct with count(*) but the use
of distinct is allowed with max and min
29. A: GROUP BY clause and ORDER BY clause are different.
R: GROUP BY clause used for grouping of data and
ORDER BY clause used for sorting of data.
30. A: Distinct Clause is used to eliminate duplicate values
from a result set based on a SQL Query.
R: The SQL ORDER BY clause can be used with the
DISTINCT clause for sorting the results after removing
duplicate values.
31. A: Delete command is used to remove rows or records from
table.
R: This command is used to remove records along with
structure of the table from database.
32. A: In SQL, the aggregate function Avg() calculates the
average value on a set of values and produce a single
result.
R: The aggregate functions are used to perform some
fundamental arithmetic tasks such as Min(),Max(),
Sum() etc…

APPAN RAJ D PGT- CS/IP 146


OBJECTIVE TYPE QUESTIONS (MCQ)
1. A relational database consists of a collection of
(a) Tables (b) Fields (c) Records (d) Keys
2. Which one of the following is commonly used to define the overall
design of the database?
(a) Application program (b) Data definition language
(c) Schema (d) Source code
3. What is the degree and cardinality of a SQL table?
(a)Number of columns and Number of rows
(b) Number of rows and Number of columns
(c) Number of keys and Number of constraints
(d)None
4. _____key is used to join two relations in RDBMS?
(a)Primary Key (b) Candidate Key
(c) Foreign Key (d)Unique Key
5. 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
6. The term _________ is used to refer to a record in a table.
(a) Attribute (b) Tuple (c) Field (d) Instance
7. Which of the following will remove the primary key from MySQL
table?
(a) remove (b) alter (c) drop (d) update
8. A/An ____________ in a table represents a logical relationship
among a set ofvalues.
(A) Attribute (B) Key (C) Tuple (D) Entry
9. The term _________ is used to refer to a record in a table.
(A) Attribute(B) Tuple(C) Field(D) Instance
10. Which of the following attributes cannot be considered as a choice
for primarykey?
(a) Id(b) License Number(c) Dept_Id(d) Street
11. Consider the table with structure as :
Student (ID, name, dept_name, tot_cred)
In the above table, which attribute will form the primary key?
(a) Name (b) Dept(c) Total_credits(d) ID
12. The term ____________ is used to refer to a field in a table.
(a)Attribute (b) Tuple (c) Row (d)Instance
13. For what purpose the DML is provided?
(a) Addition of new structure in the database
(b) Manipulation & processing of the database
(c) Definition of the physical structure of the database system.
(d) All of the above

APPAN RAJ D PGT- CS/IP 147


14. Which of the following data type will be suitable for storing the
name of students?
(a) int (b) varchar(n) (c) char(d) None of the above
15. Consider the
following table
description of a
table study.

Which of the following is false based on this description?


(a) The values of the roll column will never be repeated.
(b) The mark column will always take a value equal to 10.
(c) Name column may take NULL values.
(d) The roll column will never take NULL values.
16. What is the format used for storing date using date datatype?
(a) dd-mm-yy (b) dd-mm-yyyy
(c) mm-dd-yyyy (d) yyyy-mm-dd
17. .............. Command helps to fetch data from relation.
(a)Use (b) Show (c) Fetch (d)Select
18. .................. Command helps to open the database for use.
(a)Use (b) Open (c) Distinct (d)Select
19. Consider the following tables and their respective degree and
cardinalities in a
database called
SCHOOL:

Select the degree and cardinality of the Cartesian product of the


tables STUDENT X TEACHER from the following options:
(a) 30 7500 (b) 200 325 (c) 30 325 (d) 200 7500
20. Which of the following constraints can be used if we don’t want
user to leave the field blank while inserting data?
(a) “NULL” (b)not null (c) “Unassigned” (d) unique key
21. Which of the following data type will be the best choice for storing
price of anytime?
(a) string (b) int (c) date (d) float

APPAN RAJ D PGT- CS/IP 148


22. Which is not a constraint in SQL?
(a)Unique (b) Distinct (c) Primary key (d) Check
23. The term "SQL" stands for
(a) Standard query language
(b) Sequential query language
(c) Structured query language
(d) Server-side query language
24. Which is the subset of SQL commands used to manipulate
database structure including tables?
(a) DDL (b) DML (c) Both (a) and (b) (d) None
25. Which of the following is NOT a DML command?
(a) SELECT (b) DELETE (c) UPDATE (d) DROP
26. Which of the following sublanguages of SQL is used to define the
structure of the relation, deleting relations and relating schemas?
(a) DDL (b) DML (c) Query (d) Relational Databases
27. Which of the following is/are the DDL statements?
(a) Create (b) Drop (c) Alter (d) All of these
28. Which command we use to create a database in MySQL.
(a) Select database from MySQL;
(b) Create database databasename;
(c) Use databasename;
(d) Update database;
29. Sonia wants to see all the databases are available in her MySQL
software. Which command is useful for her?
(a) Show databases; (b) Show database;
(c) Show tables (d) Show database_name;
30. Goni wants to do some work with her database. She is confused
about how to write commands to use the required database.
Choose correct option
(a) Required database; (b) Use database;
(c) Use <databasename>; (d) Required <databasename>
31. To show all the tables of a given database what will be the
command? (a) Use database_name; shows tables;
(b) Use database_name; show tables;
(c) Required database; show tables;
(d) Required database; shows tables;
32. Consider the following SQL statement. What type of statement is
this?
CREATE TABLE employee (name VARCHAR, id INTEGER)
(a) DML (b) DDL (c) DCL (d) Integrity constraint
33. In the given query which keyword has to be inserted?
INSERT INTO employee______(1002, “Kausar”, 2000);
(a) Table (b) Values (c) Relation (d) Field

APPAN RAJ D PGT- CS/IP 149


34. Which command shows the table structure of table emp?
(a) Select * from emp; (b) Show all from emp;
(c) Desc emp; (d) Des emp;
35. An attribute A of datatype varchar (20) has the value "Keshav".
The attribute of B data type char (20) has value "Monisha". How
many characters are occupied in attribute A and attribute B?
(a) 20,7 (b) 6,20 (c) 9,6 (d) 6,9
36. The SQL keyword(s) ________ is used with wildcards.
(a) LIKE only (b) IN only
(c) NOT IN only (d) IN and NOT IN
37. If column “Marks” contains the data set {25, 35, 25, 35, 38}, what
will be the output after the execution of the given query?
SELECT DISTINCT(MARKS) FROM STUDENTS;
(a) 25, 35, 25, 35, 38 (b) 25, 25, 35, 35
(c) 25, 35, 38 (d) 25, 25, 35, 35
38. Which of the following is true about the SQL AS clause?
(a) The AS clause in SQL is used to change the column
name in the output or assign a name to a derived
column.
(b) The SQL AS clause can only be used with the JOIN
clause.
(c) The AS clause in SQL is used to defines a search
condition.
(d) All of the mentioned
39. The __________clause of SELECT query allows us to select only
those rows in the results that satisfy a specified condition.
(a)Where (b) from (c) having (d)like
40. Which of the following is not a SQL Logical Operator?
(a) = (b) and (c) or (d) not
41. This SQL query selects _______?
SELECT name FROM Emp WHERE salary IS NOT NULL;
(a) Tuple with null values (b) Tuples with no null values
(c) Tuples with any salary (d) All of the above
42. To delete a database _________________command is used
(a) Delete database database_name
(b) Delete database_name
(c) Drop database database_name
(d) Drop database_name

APPAN RAJ D PGT- CS/IP 150


43. Which of the following is using wrongsyntax for a SELECT query
in SQL?
(a) SELECT * WHERE RNO>100 FROM STU;
(b) SELECT * FROM STU WHERE RNO>100;
(c) SELECT * FROM STU WHERE RNO BETWEEN 100
AND 200;
(d) SELECT * FROM STUDENT WHERE RNO IN(100,101);
44. Which operator is used to compare a value to a specified list of
values?
(a) Between (b) All (c) In (d) None of the above
45. What will be the order of the data being sorted after the execution
of given query
SELECT * FROM STUDENT ORDER BY ROLL_NO;
(a)Custom Sort (b) Descending
(c) Ascending (d) None of the above
46. (a) In an SQL table, if the primary key is combination of
more than one field, then it is called as _____.
(b) _________ command is used to make an existing
column as a primary key.
47. Identify the correct command SQL query which is expected to
delete all rows of a table TEMP without deleting its structure?
(a) DELETE TABLE TEMP; (b) DROP TABLE TEMP;
(c) REMOVE TABLE TEMP; (d) DELETE FROM TEMP;
48. Consider the following SQL statement. What type of statement is
this? SELECT * FROM Employee ;
(a) DML (b) DDL (c) DCL (d) Integrity Constraint
49. The data types CHAR (n) and VARCHAR (n) are used to create
____and _____ length types of string/text fields in a database.
(a) Fixed, Equal (b) Equal, Variable
(c) Fixed, Variable (d) Variable, Equal
50. The pattern ‘- – – ’ matches any string of ________ three character.
‘- – – %’ matches any string of ____ three characters.
(a) Atleast, Exactly (b) Exactly, Atleast
(c) Atleast, All (d) All, Exactly
51. Which of the following will display information about all the
employee table, whose names contains second letter as "A"?
(a) SELECT * FROM EMP WHERE NAME LIKE "_A%";
(b) SELECT * FROM EMP WHERE NAME LIKE "%A_";
(c) SELECT * FROM EMP WHERE NAME LIKE "_ _A%";
(d) SELECT * FROM EMP WHERE NAME="A%"

APPAN RAJ D PGT- CS/IP 151


52. Which of the following SQL command will help in incrementing
values of FEES column in STUDENT table by 10%?
(a) UPDATE STUDENT ASSIGN FEES=FEES*0.1;
(b) UPDATE STUDENT SET FEES=FEES*0.1;
(c) UPDATE STUDENT SET FEES=FEES*10%;
(d) UPDATE STUDENT SET FEES 10%;
53. When the wildcard in a WHERE clause is useful?
(a) When an exact match is required in a SELECT
statement.
(b) When an exact match is not possible in a SELECT
statement.
(c) When an exact match is required in a CREATE
statement.
(d) When an exact match is not possible in a CREATE
statement
54. Which command is used to change the definition of a table in
SQL?
(a) create (b) update (c) alter (d) delete
ALTER, UPDATE, DELETE,DROP
55. ____command is used to add a new column in a table in SQL.
(a) update (b) remove (c) alter (d)drop
56. Which command to use in order to delete the data inside the
table, and not the table itself:
(a) DELETE (b) TRUNCATE
(c) Both TRUNCATE & DELETE (d) DROP
57. What does the following query do?
UPDATE EMPLOYEE SET SAL=SAL-(SAL * 1.10);
(a) It increases the salary of all the employees by 10%
(b) It decreases the salary of all the employees by 110%
(c) It increases the salary of all the employees by 110%
(d) It is syntactically incorrect.
58. Which of the following functions are not performed by the
“ALTER” clause?
(a) Change the name of the table
(b) Change the name of the column
(c) Drop a column
(d) All of the mentioned
59. Choose the correct command to delete an attribute A from a
relation R.
(a) ALTER TABLE R DELETE A
(b) ALTER TABLE R DROP A
(c) ALTER TABLE DROP A FROM R
(d) DELETE A FROM R
APPAN RAJ D PGT- CS/IP 152
60. In MYSQL state the commands used to delete a row and a column
respectively
(a) DELETE,DROP (b) DROP,DELETE
(c) DELETE,ALTER (d) ALTER,DROP
61. Consider the following SQL statement. What type is this ?
DROP TABLE items;
(a) DML (b) DDL (c) DCL (d) TCL
AGGREGATE FUNCTIONS
62. Aggregate functions are example of __________?
(a) Single row (b) Multi row
(c) Both (a) & (b) (d) None of these
63. How many types of Aggregate functions are available in SQL?
(a) 2 (b) 3 (c) 5 (d) 6
64. If column “AGE” of table STUDENT contains the data set (20, 50,
43, 12, 73), what will be the output after execution of the following
query.
SELECT MAX(AGE) – MIN(AGE) FROM STUDENT;
(a) 30 (b) 7 (c) 61 (d) 30
65. Select the correct statement, with reference to SQL:
(a) Aggregate functions ignore NULL
(b) Aggregate functions consider NULL as zero or False
(c) Aggregate functions treat NULL as a blank string
(d) NULL can be written as 'NULL' also.
66. Which of the following is a SQL aggregate function?
(a) LEFT (b) AVG (c) JOIN (d) LEN
67. Which of the following group functions ignore NULL values?
(a) MAX (b) COUNT (c) SUM (d) All of the above
68. Which of the following function is used to FIND the largest value
from the given data in MYSQL?
(a) MAX() (b) MAXIMUM() (c) LARGEST() (d) BIG()
69. Which type of values will not considered by SQL while executing
the following statement?
SELECT COUNT(column_name) FROM INVENTORY;
a) Numeric value b) Text value c) Null value d) Date value
70. What values does the count(*) function ignore?
(a) Repetitive values (b) Null values
(c) Characters (d) None of the above
71. In column "Margin"contains the data set
(2.00,2.00,NULL,4.00,NULL,3.00,3.00)
what will be the output of after the execution of the given query?
SELECT AVG(Margin) FROM SHOP;
(a) 2.9 (b) 2.8 (c)2.00 (d) All of these

APPAN RAJ D PGT- CS/IP 153


72. Consider the following table Cosmetics.

What will be the output after the execution of the given query?
SELECT COUNT (DISTINCT NAME) FROM COSMETICS ;
(a) 5 (b) 6 (c) 4 (d) 2
73. If column “Salary” contains the data set {1000, 15000, 25000,
10000, 15000}, what will be the output after the execution of
the given query?
SELECT SUM(DISTINCT SALARY) FROM EMPLOYEE;
(a)75000 (b) 25000 (c) 10000 (d) 51000
74. With SQL, how can you return the number of not null record in
the Project field of “Students” table?
a) SELECT COUNT (Project) FROM Students
b) SELECT COLUMNS (Project) FROM Students
c) SELECT COLUMNS (*) FROM Students
d) SELECT COUNT (*) FROM Students
75. Find the output of the MySQL query based on the given Table –
COACH:

Query:
SELECT COUNT(GAME),AVG(SALARY) FROM COACH;
(a) 3 70000 (b) 4 35000 (c) 4 70000 (d) 3 35000
76. Which of the following set of functions is a valid set of
aggregated functions in MySQL?
(a) AVG(),ROUND(),COUNT() (b) MIN(),UPPER(),AVG()
(c) COUNT(),MAX(),SUM() (d) DATE(),COUNT(),LTRIM()
77. Aggregate functions can be used in the select list or the _____
clause of a select statement. They cannot be used in a ______
clause.
(a) Where, having (b) Having, where
(c) Group by, having (d) Group by, where

APPAN RAJ D PGT- CS/IP 154


ORDER BY, GROUP BY , HAVING
78. The SELECT statement when combined with clause, returns
records in sorted order.
(a) SORT (b) ARRANGE (c) ORDER BY (d) SEQUENCE
79. Which of the following is correct sequence in a SELECT query?
(a) SELECT,FROM,WHERE,GROUP BY, HAVING, ORDER BY
(b) SELECT,WHERE,FROM,GROUP BY,HAVING,ORDER BY
(c) SELECT,FROM,WHERE,HAVING,GROUP BY, ORDER BY
(d) SELECT,FROM.WHERE,GROUP BY, ORDER BY, HAVING
80. In MYSQL _____ clause applies the condition on every ROW and
______ clause applies the condition on every GROUP.
81. If we have not specified ASC or DESC after a SQL ORDER BY
clause, the following is used by default
(a) DESC (b) ASC
(c) There is no default value (d) None of the mentioned
82. SQL applies conditions on the groups through ____ clause after
groups have been formed.
(a) Group by (b) With (c) Where (d) Having
83. For Given table "EMP" with following columns:
Eno, Ename, Sal, Dept, Designation
Select correct statement to display all records of "EMP" in
descending order of Ename and within ascending order of Dept.
(a) SELECT * FROM EMP ORDER BY ENAME,DEPT
DESC;
(b) SELECT * FROM EMP ORDER BY ENAME, ORDER
BY DEPT DESC;
(c) SELECT * FROM EMP ORDER BY ENAME
DESC,DEPT;
(d) SELECT * FROM EMP WHERE ORDER BY
NAME,DEPT DESC;
84. Consider the following query
Select * from employee order by salary ____, name _______ ;
To display the salary from greater to smaller and name in
alphabetical order which of the following option should be used?
(a) ascending, descending (b) asc,desc
(c) desc,asc (d) Descending,Ascending
85. Which of the following will be the correct SQL command to add
a new column FEES in a table TEACHER?
(a) ALTER TABLE TEACHER ADD COLUMN FEES FLOAT;
(b) ADD COLUMN FEES FLOAT INTO TEACHER;
(c) UPDATE TEACHER ADD COLUMN FEES FLOAT;
(d) INSERT INTO TEACHER ADD COLUMN FEES FLOAT;

APPAN RAJ D PGT- CS/IP 155


86. Find the output of the
MySQL query based on
the given Table –
STUDENT

SELECT
SEC,AVG(MARKS) FROM STUDENT GROUP BY SEC HAVING
MIN(MARKS)>80;
(a) B 83 (b) A 84
(c) A 84 (d) A 83
B 83 B 80
87. What is the meaning of “HAVING” clause in SELECT query?
(a) To filter out the summary groups
(b) To filter out the column groups
(c) To filter out the row and column values
(d) None of the above
88. Select correct SQL query from below to find the temperature in
increasing order of all cites.
(a) SELECT city FROM weather ORDER BY temperature;
(b) SELECT city, temperature FROM weather;
(c) SELECT city, temperature FROM weather ORDER BY
temperature;
(d) SELECT city, temperature FROM weather ORDER BY
city;
89. The HAVING clause does which of the following?
(a) Acts EXACTLY like a where clause
(b) Acts like a WHERE clause but is used for columns
rather than groups.
(c) Acts like a WHERE clause but is used for group rather
than rows.
(d) Acts like a WHERE clause but is used for rows rather
than columns.
90. Which SQL statement do we use to find out the total number of
records present in the table ORDERS?
(a) SELECT * FROM ORDERS;
(b) SELECT COUNT (*) FROM ORDERS;
(c) SELECT FIND (*) FROM ORDERS;
(d) SELECT SUM () FROM ORDERS;

APPAN RAJ D PGT- CS/IP 156


JOINS
91. Which join is equivalent to Cartesian Product?
(a) INNER JOIN (b) OUTER JOIN
(c) CROSS JOIN (d) NATURAL JOIN
92. How many tables may be included with a join?
(a) One (b) Two (c) Three (d) All of the Mentioned
93.
(a) Outer Join
(b) Inner Join
(c) Self Join
(d) Right Outer Join

94. The following SQL is which type of Join?


SELECT * FROM FACULTY,STUDENT;
(a) Equi Join (b) Natural Join
(c) Cartesian Product (d) Both (a) & (b)
95. The following SQL command is which type of join:
SELECT customer, cust_id,order,cust_id, name, order_id
FROM customer, order;
(a) Equi-join (b) Natural join
(c) Outer join (d) Cartesian product
96. Select the correct query/queries for cross join:
(a) Select * FROM Table1 T1 NATURAL JOIN Table1 T2;
(b )Select * FROM Table1 T1 ALL CROSS JOIN Table1 T2;
(c) Select * FROM Table1 T1,Table1 T2;
(d) Select * FROM Table1 T1 CROSS Table1 T2;
97. Consider the following tables in a database Called SPORTS:
Which is the best command from the following options to
display the name of the PNAME and their respective GNAME

APPAN RAJ D PGT- CS/IP 157


(a) SELECT PNAME,G1D FROM PLAYERS;
(b) SELECT PNAME,GNAME FROM GAMES,PLAYERS WHERE
GAMES.G1D=PLAYERS.G1D;
(c) SELECT PNAME,GNAME FROM GAMES,PLAYERS;
(d) SELECT PNAME,GNAME FROM GAMES,PLAYERS
WHERE P.G1D=G.G1D;
98. The following SQL is which type of join?
SELECT CUS_T. CUS_ID, ORDER_T. CUS_ID,NAME,
ORDER_ID FROM CUS_T,ORDER_T WHERE
CUS_T. CUS_ID = ORDER_T. CUS_ID;
(a) Equi-join (b) Natural join
(c) Outer join (d) Cartesian join
99. Choose the correct option regarding the query:
SELECT branch_name, COUNT (DISTINCT cust_name)
FROM deposit, account WHERE deposit.acc_no =
account.acc_no GROUP BY branch_id HAVING avg(bal) =
10000;
(a) The having clause checks whether the query result is
true or not
(b) The having clause does not check for any condition
(c) The having clause allows only those tuples that have
average balance 10000.
(d) None of the mentioned.

APPAN RAJ D PGT- CS/IP 158


3 MARKS (OR) 4 MARKS
1. Rashmi has forgotten the names of the databases, tables and the
structure of the tables that she had created in Relational Database
Management System (RDBMS) on her computer.
(a) Write the SQL statement to display the names of all the
databases present in RDBMS application on her
computer.
(b) Write the statement which she should execute to open
the database named "STOCK".
(c) Write the statement which she should execute to
display the structure of the table "ITEMS" existing in the
above opened database "STOCK".
2. Consider the table HOTEL given below and write any four SQL
commands :
Table : HOTEL

(i) Display the details of all the Hotels situated in London.


(ii) Display the details of all 'Deluxe' rooms with price
more than 6000 in ascending order of Price.
(iii) Display the Hotel names that end with ''e''.
(iv) Count different types of rooms available in the Hotels.
(v) Display the Hotel names in descending order.
3. Write SQL statements for the following queries (i) to (v) based
on the relations CUSTOMER and TRANSACTION given below :

APPAN RAJ D PGT- CS/IP 159


(a) To display all information about the CUSTOMERs
whose NAME starts with 'A'.
(b) To display the NAME and BALANCE of Female
CUSTOMERs (with GENDER as 'F') whose
TRANSACTION Date (TDATE) is in the year 2019.
(c) To display the total number of CUSTOMERs for each
GENDER.
(d) (i) To display the CUSTOMER NAME and BALANCE in
ascending order of GENDER.
(ii) To display CUSTOMER NAME and their respective
INTEREST for all CUSTOMERs where INTEREST is
calculated as 8% of BALANCE.
4. (a) Ram wants to find the sum of commission earned by
each department. He has executed the following query :
SELECT dept,sum(comm) GROUP BY dept
FROM EMP;
But, he got an error. Rewrite the correct query after
identifying the error(s).
(b) Consider the following Table : ITEM

Find the output of the following SQL queries :


(a) SELECT 10+ QTY FROM ITEM WHERE ID = "P1003";
(b) SELECT PRICE*QTY FROM ITEM WHERE QTY < 2;
5. Consider the Table FURNITURE with the following data:

Write SQL queries for the following :


(a) To Display all the records in descending order of Item.
(b) To Display the Type and total number of items of each
Type.
(c) To Display the highest Price.
(d) To Display the Item with their price rounded to 1
decimal place.

APPAN RAJ D PGT- CS/IP 160


6. Write the output of the queries (i) to (iv) based on the table,
TECH_COURSE given below:

(i) SELECT
DISTINCT TID FROM TECH_COURSE;
(ii) SELECT TID, COUNT(*), MIN(FEES) FROM
TECH_COURSE GROUP BY TID HAVING
COUNT(TID)>1;
(iii) SELECT CNAME FROM TECH_COURSE WHERE
FEES>15000 ORDER BY CNAME;
(iv) SELECT AVG(FEES) FROM TECH_COURSE WHERE
FEES BETWEEN 15000 AND 17000;
7. Write the outputs of the SQL queries (i) to (iv) based on the
relations Teacher and Placement given below:

(i) SELECT Department, avg(salary) FROM Teacher GROUP


BY Department;
(ii) SELECT MAX(Date_of_Join), MIN(Date_of_Join) FROM
TEACHER;
(iii) SELECT Name, Salary, T. Department, Place FROM
Teacher T, Placement P WHERE T.Department =
P.Department AND Salary>20000;
(iv) SELECT Name, Place FROM Teacher T, Placement P

APPAN RAJ D PGT- CS/IP 161


WHERE Gender =’F’ AND T.Department=P.Department;
8. Write the output of the queries (a) to (d) based on the table,
Furniture given below:

(a) SELECT SUM(DISCOUNT) FROM FURNITURE WHERE


COST>15000;
(b) SELECT MAX(DATEOFPURCHASE) FROM FURNITURE;
(c) SELECT * FROM FURNITURE WHERE DISCOUNT>5
AND FID LIKE "T%";

(d) SELECT DATEOFPURCHASE FROM FURNITURE;


WHERE NAME IN ("Dining Table", "Console Table");
9. Write queries (a) to (d) based on the tables EMPLOYEE and
DEPARTMENT given below:

(a) To display the average


salary of all employees,
department wise.
(b) To display name and respective department name of
each employee whose salary is more than 50000.

APPAN RAJ D PGT- CS/IP 162


(c) To display the names of employees whose salary is not
known, in alphabetical order.
(d) To display DEPTID from the table EMPLOYEE without
repetition.
10. Consider the following tables– EMPLOYEES AND DEPARTMENT:
What will be the output of the
following statement?

SELECT ENAME, DNAME


FROM EMPLOYEES E,
DEPARTMENT D WHERE
E.DNO=D.DNO;

11. Write the output of SQL queries (a) and (b) based on the follwing
two tables DOCTOR and PATIENT belonging to the same
database:

(a) SELECT DNAME,PNAME FROM DOCTOR NATURAL


JOIN PATIENT;
(b) SELECT PNAME, ADMDATE, FEES FROM PATIENT P,
DOCTOR D WHERE D.DNO=P.DNO AND FEES>1000;

APPAN RAJ D PGT- CS/IP 163


12. Consider the following two tables:

What will be the degree and


cardinality of the Cartesian
product and the Natural join
of these tables?

13. Consider the following tables FACULTY and STUDENT. Write the
output for the MYSQL statement given below and state what type
of join is implemented.
SELECT * FROM FACULTY,STUDENT

14. HARSH AGARWAL has created a table named 'Actor' which


contains a field called Aname.
Write MySQL queries for the followings:
(i) To show all the names of the actors which contain the
string 'ch' in it.
(ii) To display all the names of the actors which contain exactly 5
characters and also the second characters is 'o' (such as
Gopal or Mohan).
15. Consider the following tables –
LOAN and BORROWER:

How many rows and columns


will be there in the natural
join of these two tables?

APPAN RAJ D PGT- CS/IP 164


16. Consider the following tables MUSIC and DANCE:

Identify the degree and cardinality of:


a) Union operation on MUSIC and DANCE.
b) Intersection operation on MUSIC and DANCE.
17. Consider the SQL table "PRODUCT_SALES" with the following
data:

Predict the output of the following queries based on the table


"PRODUCT_SALES" given above:
1. SELECT (SalesQ2 - SalesQ1) / 2 AS Sale2 FROM
PRODUCT_SALES WHERE Segment = 'High';
2.SELECT SUM(SalesQ1) AS "TOTAL” FROM
PRODUCT_SALES WHERE Region = 'B';
18. (a) Consider the table, BOOK and MEMBER given below:

What will be the output of the following statement?


SELECT * FROM BOOK NATURAL JOIN MEMBER;

APPAN RAJ D PGT- CS/IP 165


(b) Write the output of the queries (i) to (iv) based on
the table.
Table: Employee

i SELECT NAME, PROJECT FROM EMPLOYEE ORDER


BY NAME DESC;
ii SELECT NAME, SALARY FROM EMPLOYEE WHERE
NAME LIKE 'A%';

iii SELECT NAME, DOJ FROM EMPLOYEE WHERE


SALARY BETWEEN 100000 AND 200000;
iv SELECT * FROM EMPLOYEE WHERE PROJECT = 'P01';
19. Write SQL Queries for (a) to (d) based on the tables
PASSENGER and FLIGHT
given below:

(a) Write a query to change the fare to 6000 of the flight whose
FNO is F104.
(b) Write a query to display the total number of MALE and
FEMALE passengers.
(c) Write a query to display the NAME, corresponding FARE and
F_DATE of all passengers who have to START from DELHI.
(d) Write a query to delete the records of flights which end at end
MUMBAI.

APPAN RAJ D PGT- CS/IP 166


20. Write the SQL Queries for the following tables:

(i) To display department name and number of employees


in each department where no of employees is greater
than one.
(ii) To display department name and sum of the salary
spent by the department, where the total amount spent
by the department as salary is more than 100000.
(iii) To display the name of the employee in descending
order of their seniority.
21. Write the outputs of the SQL queries

(i) SELECT DEPARTMENT, MAX(SALARY) FROM TEACHER


GROUP BY DEPARTMENT;
(ii) SELECT MAX(DATE_OF_JOIN),MIN(DATE_OF_JOIN)
FROM TEACHER;

APPAN RAJ D PGT- CS/IP 167


(iii) SELECT NAME, SALARY, T.DEPARTMENT, PLACE FROM
TEACHER T, PLACEMENT P WHERE T.DEPARTMENT =
P.DEPARTMENT AND P.DEPARTMENT='HISTORY';
(iv) SELECT NAME, PLACE FROM TEACHER NATURAL JOIN
PLACEMENT WHERE GENDER='F';
22. (a) Consider the following table structure:

Write a SQL query to remove unique constraints from the table.

(b) Consider the following table:

(i) SELECT SNAME, STREAM FROM XII_A HAVING STREAM


LIKE '%B%';
(ii) SELECT STREAM, COUNT (*) FROM XII_A GROUP BY
STREAM HAVING COUNT(STREAM)<=1;
(iii) SELECT AGE, STREAM FROM XII_A WHERE AGE
BETWEEN 15 AND 15 ORDER BY SNAME;
(iv) SELECT ROLLNO, STREAM FROM XII_A WHERE STREAM
LIKE "P%B" AND STREAM <>"BS";

APPAN RAJ D PGT- CS/IP 168


23. Write the output (i-iii) for the following SQL commands

(i) SELECT MAX(DOB) FROM PARTICIPANTS;


(ii) SELECT DISTINCT EVENT FROM PARTICIPANTS;
(iii) SELECT COUNT(DISTINCT(CLASS)) FROM PARTICIPANTS;
(iv) SELECT MAX(DOB), PNO FROM PARTICIPANTS GROUP BY
PNO HAVING COUNT(*)>1
24. Using the table of Q.No 25 Trainer and Course Write the output
for the following SQL Queries:
(i) SELECT TID, TNAME, FROM TRAINER WHERE CITY
NOT IN(‘DELHI’, ‘MUMBAI’);
(ii) SELECT DISTINCT TID FROM COURSE;
(iii) SELECT TID, COUNT(*), MIN(FEES) FROM COURSE
GROUP BY TID HAVING COUNT(*)>1;
(iv) SELECT COUNT(*), SUM(FEES) FROM COURSE
WHERE STARTDATE< ‘2018-09-15’;
25. Write the output of the queries (i) to (vi) based on the table given
below:

APPAN RAJ D PGT- CS/IP 169


(i) SELECT BRAND_NAME, FLAVOUR FROM CHIPS WHERE
PRICE <> 10;
(ii) SELECT * FROM CHIPS WHERE FLAVOUR="TOMATO" AND
PRICE > 20;
(iii) SELECT BRAND_NAME FROM CHIPS WHERE PRICE > 15
AND QUANTITY < 15;
(iv) SELECT COUNT( DISTINCT (BRAND_NAME)) FROM CHIPS;
(v) SELECT PRICE , PRICE *1.5 FROM CHIPS WHERE
FLAVOUR = "PUDINA";
(vi) SELECT DISTINCT (BRAND_NAME) FROM CHIPS ORDER BY
BRAND_NAME DESC;
26. Write SQL statements for the q.no (i) to (iv) and output for (v)

Write the SQL commands for the following:


(i) To show firstname, lastname, address and city of all
employees living in paris
(ii) To display the content of Employees table in descending
order of Firstname.
(iii) To display the firstname, lastname and total salary of
all managers from the tablesEmployee and empsalary,
where total salary is calculated as salary+benefits.
(iv) To display the maximum salary among managers and
clerks from the table Empsalary.
(v) To display the average salary of Clerk.

APPAN RAJ D PGT- CS/IP 170


27. (i) Write a Query to insert House_Name=Tulip,
House_Captain= Rajesh andHouse_Point=278 into
table House(House_Name, House_Captain,
House_Points)
(ii) Write the output for SQL queries (i) to (iv), which are
based on the table: STUDENTgiven below:

(i) SELECT COUNT(*), City FROM STUDENT GROUP BY


CITY HAVING COUNT(*)>1;
(ii) SELECT MAX(DOB),MIN(DOB) FROM STUDENT;
(iii) SELECT NAME,GENDER FROM STUDENT WHERE
CITY="Delhi";
(iv) SELECT DISTINCT Class FROM STUDENT;
28. Write the outputs of the
SQL queries (i) to (iv)
based on the
relations student and
sports given below:

(i) SELECT ROLL_NO,AGE,GNAME FROM STUDENT ST,SPORTS


SP WHERE ST.ROLL_NO=SP.ROLL_NO AND GNAME
LIKE ‘_R%’;

APPAN RAJ D PGT- CS/IP 171


(ii) SELECT AGE,GENDER FROM STUDENT WHERE DOB
IS NOT NULL AND AGE>15;
(iii) SELECT SNAME,GENDER FROM STUDENT WHERE AGE
NOT IN(12,22);
(iv) SELECT GENDER,AVG(TOTAL) FROM STUDENT WHERE
GENDER IN(‘M’,’F’) GROUP BY GENDER;
29.

(i) Display the SurNames, FirstNames and Cities of people


residing in Udhamwara city.
(ii) Display the Person Ids (PID), cities and Pincodes of
persons in descending order of Pincodes.
(iii) Display the First Names and cities of all the females getting
Basic salaries above 40000.
(iv) Display First Names and Basic Salaries of all the persons
whose firstnames starts with "G".
30. Write the output for the
queries (i) to (iv) based on the
table given below:

(i) SELECT MAX(FEES),MIN(FEES) FROM SPORTS;


(ii) SELECT COUNT(DISTINCT SNAME) FROM SPORTS;
(iii) SELECT SNAME, SUM(No_of_Players) FROM SPORTS
GROUP BY SNAME;
(iv) SELECT AVG(FEES*No_of_Players) FROM SPORTS WHERE
SNAME=”Basket Ball”;

APPAN RAJ D PGT- CS/IP 172


31. Consider the following tables Write SQL commands for the
following statements.

(i) Display NAME of all doctors who are in "ORTHOPEDIC"


having more than 10 years experience from the table
DOCTOR.
(ii) Display the average salary of all doctors working in
"ENT" department using the DOCTOR and SALARY.
(Salary= Basic + Allowance)
(iii) Display the minimum ALLOWANCE of female doctors.
(iv) Display the highest consultation fee amount for all
male doctors.

**********************************************************

APPAN RAJ D PGT- CS/IP 173


CHAPTER – 8
(INTERFACING PYTHON WITH MYSQL)
PRACTICE QUESTIONS

THEORY QUESTIONS

1. Write the command to install MySQL connector?


2. Which package do we import in Python to establish my SQL
python connectivity?
3. What is the significance of using connect () function and
write its syntax.
4. What are the steps for creating database connectivity
applications?
5. What is a result set?
6. What is a database cursor?
7. Differentiate between the following and write its return
type:
(i) fetchone() and fetchall() (ii) fetchmay() and fetchall()
(iii) fetchone() and fetchmany()
8. What is the role of cursor.rowcount?

STATE TRUE OR FALSE


1. fetchone() return None when no more data is available.
2. We always get same result from the methods fetch() and
fetchall().
3. rowcount is not a read-only attribute.
4. close() method is used to disconnect database connection.
5. Once a database connection is established, we are ready to
create tablesusing execute method of the created cursor.
6. rowcount is a read-only attribute.
7. The next row of resultset is fetched via fetchone().
8. We cannot create a new database using python MySql interface.
9. When we execute a MySql insert query in python, The new row
gets saved in thedatabase.
10. We cannot delete a mysql row using python program

APPAN RAJ D PGT- CS/IP 174


ASSERTION & REASONING
1. A: Mr.Raj had taken a variable as a connection
object and used connect() function with MySQL.
database specification like hostname, username,
password or passwd and database itself. But
connection could not establish.
R: To use connect( ) function user must include or
import mysql.connector in the beginning of the
program.
2. A: mydb = mysql.connector.connect
(host="192.68.45.251",user="you",
password="y")
R: host variable should be initialized with value
‘localhost’
3. A:mydb = mysql.connector.connect(
host="178.23.45.262", user="you",password="y")
R: database name has not been provided in the
connect function call.
4. A:con= # Assume connection is already created
data = [('Jane', 'F'),('Joe', 'M'),('John', 'M'),]
cur=con.cursor()
stmt= "INSERT INTO employees (fname, hire_date)
VALUES (%s, %s)"
cur.execute(stmt, data)
mydb.commit()
R: execute function can’t be used to insert multiple
rows.
5. A: An user run the following command to input a new
record in the table cur.execute("insert into students
values(1,'Anu',78.50,'B1'") but he found that record
cannot be inserted in the table .
R: Commit() function must used to save the changes
and reflect the data in the table.
6. A: To retrieve Three(3) students details we use
cursor.fetchmany(3) function.
R: The number of rows is a compulsory parameter for
cursor.fetchmany( 3)
7. A: To create a table in MySQL, use the "CREATE
TABLE"statement.
R: We can use cursor.run() to create the table.

APPAN RAJ D PGT- CS/IP 175


8. A:mydb = mysql.connector.connect( host="localhost",
user="you",password="you")
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")
R: We can create a new database using execute
function.
9. A: cur.execute("DELETE FROM customers WHERE
address = "M")
R: Commit function should be called to save the
changes
10. A: The resultset refers to a logical set of records
that are fetched from the database by executing
an SQL query.
R: Result set stored in a cursor object can be
extracted by using fetch(…) functions
OBJECTIVE TYPE QUESTIONS (MCQ)
1. Which of the following is the correct set of commands for installing
and importing mysql connector, respectively?
(a) pip install mysql.connector import mysql.connector
(b) pip install mysql-connector import mysql.connector
(c) pip install mysql-connector import mysql-connector
(d) pip install mysql.connector import mysql-connector
2. Which my sql driver you need to install for connection of Python
With MYSQL
(a) mysql-connector (b) mysql.connector
(c) mysql-connect (d) All of the above
3. Mandatory arguments required to connect any database from
Python are:
(a) Username, Password, Hostname, Database name, Port
(b) Username, Password, Hostname
(c) Username, Password, Hostname, Database Name
(d) Username, Password, Hostname, Port
4. What is the maximum number of parameters that can be accepted
by connect method.
(a) 2 (b) 3 (c) 4 (d) 0
5. The ………. creates a connection to the MySQL server and returns a
Connection object.
(a) connect() (b) connection() (c) connector() (d) None above

APPAN RAJ D PGT- CS/IP 176


6. Python enables Python programs to access MySQL databases
(a) import mysql.connect (b) import mysql.connector
(c) import mysql.connection (d) None of the above
7. The -------------------- constructor creates a connection to the
MySQL server andreturns a MySQL Connection object.
(a) connect() (b) connection()
(c) mysqlconnect() (d) None of the above
8. Maximum how many parameters can be accepted by cursor()
method.
(a) 2 (b) 3 (c) 4 (d) 0
9. To establish the Python-MySQL connection, connect() method is
used with certain parameters or arguments. Which of the following
is not a parameter/argument used with connect () method?
(a) user (b) password (c) database (d) table
10. Choose the correct statement to connect database from Python
code, is host is "localhost", user= "root" the database is “School”
with no password .
(a) connect(host="localhost",user= "root",database =
"School")
(b) connect(host= "localhost",user= "sql",password=NAN,
database = "root")
(c) connect(host= "host",user= "root",password=np.nan,
database = "School")
(d) connect(host= "loca",user="School",password="",
database = "root")
11. It acts as middleware between MYDSQL database connection and
SQL query. (a) cursor (b) Table (c) Query (d) row
12. commit() is required to be used after the execution of certain
queries in Python-MySQL connectivity applications. Identify one
such MySQL command out of the following options:
(a) CREATE (b) INSERT (c) SELECT (d) DROP
13. While working on Python-MySQL connectivity, fetchall() method is
used to get data from table. The method fetchall() returns ______?
(a) A list (b) A tuple (c) Tuple of Lists (d) List of Tuples

APPAN RAJ D PGT- CS/IP 177


14. The method cursor() is used in Python-MySQL connectivity
applications. This method is a member of:
(a) sql module (b) pickle module
(c) csv module (d) database-connectivity module
15. To establish a connection between Python and SQL database,
connect () is used. Which of the following arguments may not
necessarily be given while calling
connect() ?
(a) host (b) database (c) user (d) password
16. Ramesh is trying to fetch only one record from result set at a time.
Which method should be used by him?
(a) fetchmany(b) fetchno(c) fetchone(d) fetchall
17. This is the Property of cursor object that returns the number of
rows fetched
a) fetchall() b) resultsetc) rowcountd) none of the above
18. Fill in the blank
data = [('Jane', 'F'),('Joe', 'M'),('John', 'M'),]
stmt = "INSERT INTO employees (first_name, hire_date)
VALUES (%s, %s)"
cursor.___________(stmt, data)

(a)execute (b)executemany (c) executeall (d)execute Q


19. If cur is a valid cursor what will be the output of the following
cur.execute("select * from student") #student table has
5 rows
print(mycursor.rowcount)
(a) 5 (b)0 (c) -1 (d) None
20. If "my" is a valid cursor what will be the output of the following
my.execute("select * from student") #student table has
5 rows
myresult = my.fetchmany(3)
print(my.rowcount)
(a) 5 (b)3 (c) -1 (d)None
21. SQL command is passed to which function to run after
establishment of the connection between python and database:
(a) cursor() (b) execute() (c) connection() (d) fetchall()
22. Which of the following function is used to close the connection
between python and database?
(a) cursor.close() (b) is.close()
(c) connection.close() (d) execute.close()

APPAN RAJ D PGT- CS/IP 178


23. Read the following code and assume that all necessary files are
alreadyimported
con = sql.connect(host='localhost',user='root',
password='in',database = 'com')
Cursor = con.cursor()
Query = “Select * from empl”
Which will be the next statement to execute query?
(a) Cursor.query.excute() (b) Cursor.execute(Query)
(c) Query.execute() (d) execute(Query)
24. When we run <connection>.__________ method, it reflect the
changes made in the database permanently.
(a) done() (b) commit() (c) reflect() (d) final()
25. Which function retrieve all (remaining) rows of a query result an
return them in a list of tuples
(a) fetchone() (b) fetchall()(c) fetchmany ()(d) All the above
26. Which is the correct statement about fetchone()
(a) Fetch the next row of a query result set, returning a
single tuple, or None when no more data is available
(b) Fetch the First row of a query result set, returning a
single tuple, or None when no more data is available
(c) Fetch the current row of a query result set, returning a
single tuple, or None when no more data is available
(d) None of the above
27. What is the datatype of the row returned from a resultset using
fetchone() function?
(a) Tuple (b) List (c) String (d) Dictionary
28. What is the datatype of the row returned from a resultset using
fetchmany() function?
(a) Tuple (b) List (c) String (d) Dictionary
29. What is returned when we execute the function fetchone() but no
rows are available tofetch ?
(a) None (b) Empty Tuple (c) Empty List (d) Error
30. What is returned when we execute the function fetchall() but no
rows are available tofetch ?
(a) None (b) Empty Tuple (c) Empty List (d) Error
31. What is returned when we execute the function fetchmany() but no
rows are availableto fetch ?
(a) None (b) Empty Tuple (c) Empty List (d) Error
32. In order to open a connection with MySQL database from within
Python using mysql.connector package, ________ function is used.
(a) open( ) (b) database( ) (c) connect( ) (d) connected( )

APPAN RAJ D PGT- CS/IP 179


3- MARKS (MISSING STATEMTS)
1. Write the following missing statements to complete the code:
Statement 1 – To import the required modules and give
alias as "ms"
Statement 2 – To execute the query that extracts records
of those teachers whose year of retirement
is 2022.
Statement 3- To fetch all the data from the cursor
instance
import ______ as ______ #Statement 1
con1=ms.connect(host="localhost",user="root",
password="ks",database="sch")
mycursor= con1.cursor()
print("Teachers about to retire in 2022 are: ")
_________________________ # Statement 2
data=__________________ # Statement 3
for i in data:
print(i)
print()
2. K.B. public school is managing student data in ‘student’ table in
‘school’ database. Write python code that connects to database
school and retrieve all the records and display total number of
students.
import mysql.connector
con=mysql.connector.connect(___) # write code to
#connect with mysqldatabase
cur=con.__________ # write code to create a cursor
cur.execute(“Select * from student”)
records=______ # write code to fetch records from
cursor
count=_______ #write code to count total number of
students record
print("Total number of records :", count)
con.close()

APPAN RAJ D PGT- CS/IP 180


3. Write the following missing statements to complete the code:
import mysql.connector as mysql
def sql_data():
con1=mysql.connect(host="localhost",user="root",
password="abc",database='MY')
mycursor= con1.cursor()
____________________ #Statement 1
rno=int(input("Enter Roll Number :: "))
name=input("Enter name: ")
Q="update student set marks=marks+5 where
RollNo={}".format(rno)
___________ #Statement 2
____________# Statement 3
print("Data updated successfully")
Statement 1 – To open/activate the school database.
Statement 2 – To execute the command that updates the
record in the table Student.
Statement 3- To make the updation in the database
permanently.
4. import mysql.connector
connection = mysql.connector.connect(host='localhost',
database='Employee',
user='root',
password='tiger')
cursor=_______________________ #STATEMENT 1
empid=int(input("enter Empid"))
name=input("enter name")
salary=float(input("ENTER SALARY"))
result = __________________________ #STATEMENT 2
___________________________________#STATEMENT 3
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 Employee.
Statement 3- To add the record permanently in the
database.

APPAN RAJ D PGT- CS/IP 181


5. The code given below reads the following record from the table
named Employee and displays only those records who have Salary
greater than 25000:
import mysql.connector as my
con = mysql.connect(host='localhost',
database='Emp',user='root',password='tiger')
cursor=________ #STATEMENT 1
_______________ #STATEMENT 2
records = _____ #STATEMENT 3
for row in records:
print("Empid",row[0], "name",row[1],end=" ")
print("salary",row[2],end=" ")
print()
Write the following missing statements to complete the code:
Statement 1 – To form the cursor object Statement
Statement 2 – To execute the query that extracts records
of those Employees who have salary
greater than 25000.
Statement 3- To read the complete result of the query
(records whose salary greater than 25000)
into the object named records, from the
table Employee in the database.
6. A table named ITEM is created in a database STORE. It contains
the following columns:
- integer,Iname– string , Price – float, Discount – float
______ #Line 1
con1= mysql.connect(host='localhost', user = 'root', password
='tiger', database='STORE')
mycursor = con1.____ #Line 2
q = 'SELECT * FROM ITEM where Price > { }'.format(___) #Line3
mycursor.execute(q)
data = mycursor.___ #Line 4
for rec in data:
print(rec)
con1.close()
i. Complete line 1 to import the appropriate module.
ii. Complete Line 2 to create the cursor object
iii. Complete the query given in Line 3 to display details of
all such items from the table ITEMS whose price is
More than 5000.
iv. Complete Line 4 to extract all the records.

APPAN RAJ D PGT- CS/IP 182


4 MARKS
1. David wants to write a program in Python to insert the following
record in the table named "Student" in MYSQL database,
"SCHOOL":
Rno (Roll number )- integer Name - string
DOB (Date of birth) – Date Fee – float
Note: Username – root Password – tiger
Host – localhost
The values of fields Rno, name, DOB and Fee has to be accepted
from the user. Help David to write the program in Python.
2. Roja wants to write a program(s) in Python to perform the following
operations in the table named Books in MYSQL database,
"SHOP":
The table contains the following field/column.
Bno - integer Bname- string Price – float DOP– Date
Author - String
Note the following to establish connectivity between Python and
MySQL: Username – root Password – root
Host – 192.160.1.2
Help Roja to write the program in Python for the following:
(i) Roja, now wants to display the records of Books whose
Date of Publish is between "2000-05-09 to 2001-11-23".
Help Roja to write the program in Python.
(ii) She wants to decrease the Books price by 7% whose
book price is more than 900 and Author is "Anu".

APPAN RAJ D PGT- CS/IP 183


3. Ram wants to write a program in Python to create the following
table named “EMP” in MYSQL database, ORGANISATION:
Eno- integer , Ename - string, Edept -string,
Sal (salary)-integer
Note:
Username – root , Password – admin , Host - localhost
Help Ram to write the program in Python to Alter the above
table with new column named Bonus (int).
4. Maya has created a table named BOOK in MYSQL database,
LIBRARY
BNO - integer, B_name – string, Price –integer
Note:
Username – root, Password – writer, Host – localhost.
Maya, now wants to display the name (only name) of books whose
price is more than 250. Help Maya to write the program in Python.
CASE STUDY BASED 2 - MARKS
1. Avni is trying to connect Python with MySQL for her project. Help
her to write thepython statement on the following:-
(i) Name the library, which should be imported to connect
MySQL with Python.
(ii) Name the function, used to run SQL query in Python.
(iii) Write Python statement of connect function having
the arguments values as :
Host name :192.168.11.111
User : root
Password: Admin
Database : MYPROJECT

APPAN RAJ D PGT- CS/IP 184


2. Rearrange the following steps in connecting SQL with python:
1. Create a database object, say mydb, using connect()
function by passing username and password.
2. Execute SQL statement using the created cursor objects
(mycur).
3. Import the library mysql.connector
4. Create a cursor object, mycur, for the created database
object(mydb) for reserving a temporary work area in the
system memory for storing the part of the active
database.
3. For the following SQL table named PASSENGERS in a database
TRAVEL.

import mysql.connecotor as c
s=c.connect(host='localhost',user='a',password='a')
cur=c.cursor()
cur.execute('USE TRAVEL')
cur.execute("SELECT * FROM PASSENGERS")
Res=cur.fetchall()
for R in Res:
print(R[1])
s.close()

APPAN RAJ D PGT- CS/IP 185


4. The books table of test database contains the records shown below
and Predict the output of the following code:

import mysql.connector as sqltor


conn = sqltor.connect (host = "localhost", user = "learner",
passwd = "fast",database = "test")
cursor = conn.cursor()
cursor.execute("SELECT * FROM books")
row = cursor.fetchone()
while row is not None:
print (row)
row = cursor.fetchone()
5.

Consider the
ENO ENAME DEPT SALARY following
1 ALEX MUSIC 60000 information stored
2 PETER ART 67000 in the table: EMP
3 JOHNY MUSIC 65000
4 USHA ART 85000

#Assume all basic setup related to


connection and cursor creation is already
done.
Q="SELECT * FROM EMP"
mycurosr.execute(Q)
res=mycursor.fetchone()
res=mycursor.fetchone()
res=mycursor.fetchone()
d=int(res[3])
print(d*3)

**********************************************************

APPAN RAJ D PGT- CS/IP 186


CHAPTER – 9 INTRODUCTION TO COMPUTER NETWORKS
PRACTICE QUESTIONS

THEORY QUESTIONS [2- MARKS]


1. Define Computer Network?
2. Write the advantages of Computer Network?
3. What is meant by interspace?
4. Write the difference between Client and Server.
5. List out the various types of Servers in Computer Network.
6. What is the Name of the first computer Network? Expand it.
7. What is 80-20 rule in computer Network?
8. (i) Rearrange the following terms in increasing order of
data transfer rates: Gbps, Kbps, Mbps, Tbps, bps.
(ii) Out of the following, which is the fastest: (i) wired and
(ii) wireless medium of Communication:
Infrared, Coaxial Cable, Ethernet Cable, Microwave, OFC
(iii) Arrange the following in the increasing order of their size :
LAN, WAN, MAN, PAN
9. What is Baud and Bandwidth in Network? What is the
approximate bandwidth of a typical voice signal?
10. Write the difference between Client and Server.
11. What is switching in Network? List out the various types of
switching techniques.
12. What is meant by Transmission media? List out the types
of transmission media available in Network.
13. List out various types of networks.
14. Illustrate the layout for connecting 5 computers in a Bus
and a Star topology of Networks.

APPAN RAJ D PGT- CS/IP 187


15. Write the difference between the following:
(i) Circuit Switching vs Packet Switching.
(ii) Twisted Pair/Ethernet Cable vs Co-axial Cable.
(iii) Fibre Optical Cable vs Twister pair Cable.
(iv) Radio waves vs Microwaves.
(v) LAN vs MAN / WAN vs LAN/ MAN vs WAN / PAN vs LAN
(vi) MAC vs IP Address (vii) WiFi vs Wimax
16. Write the Advantages and disadvantages of the following:
(i) Circuit Switching (ii) Packet Switching (iii) Twister Pair
(iv) Coaxial- Cable (v) Fibre Optical
17. "With message switching, there is no limit on block size, in
contrast, packet switching places a tight upper limit on
block size". – Is this feature of packet switching
advantageous?
18. What type of wave is used by satellite?
19. Which Transmission medium is suitable for hilly areas and
Desrt area.
20. What are network devices? List out its types.
21. What is meant by NIC/ Ether net Card?
22. Write the difference between the following:
(i) HUB vs SWITCH (ii) BRIDGE vs ROUTER
(iii) SWITCH vs BRIDGE (iv) GATEWAY vs ROUTER.
(v) MODEM vs GATEWAY
23. Write the Purpose of Repeater.
24. What is meant by network topologies? List out its types.
25. Write the difference between the following:
(i) Star topology vs Bus topology (ii) Bus vs Tree Topology

APPAN RAJ D PGT- CS/IP 188


26. Write the Advantages and Disadvantages of the following:
(i) Star topology (ii) Bus topology (iii) Tree topology
27. A school has 4 branches located in the same city. Each
branch has its own LAN. The schools share the e-learning
material housed in branch A.
i. The terminals in Branch A are connected to a common
cable. Identify the Topology used here?
ii. During data transfer, the communicating nodes in a
LAN should establish dedicated link. Name the device
that meets the above requirement.
iii. Name the type of network used by the branches to share
the e-learning Material.
iv. What should be the transmission medium between the
branches, if the School insists on data security?
28. Identify the type of topology on the basis of the following:
(i) Since every node is directly connected to the server, a
large amount of cable is needed which increases the
installation cost of the network.
(ii) It has a single common data path connecting all the
nodes.
29. Define Network Protocol. List out its types.
30. Differentiate between the following:
(i) HTTP vs HTTPS (ii) HTTPS VS FTP
(iii) SMTP vs POP3 (iv) POP3 vs IMAP
31. What is TCP/IP?
32. Write the purpose of Telnet.
33. Name the standard for each of the following:
(i) Wireless LANs based ob IEEE 802.11
(ii) Broadband wireless – access solution based on IEEE 802.16
34. Which protocol is responsible for doing audio and video calls
over internet?
35. What is Chat and video conferencing?

APPAN RAJ D PGT- CS/IP 189


36. (i) Write the name of the chatting protocol?
(ii) Write the name of the protocol which is responsible for
video conferencing.
(iii) Which protocol is used to creating a connection with a
remote machine?
37. The following is a 32 bit binary number usually represented as 4
decimal values, each representing 8 bits, in the range 0 to 255
(known as octets) separated by decimal points. 140.179.220.200
what is it? What is its importance?
38. (i) Name the device which is used to regenerate data and
voice signals.
(ii) Name any two private Internet Service Providers
(company) in India.
39. Define Browser. Name any two internet browsers.
40. What is meant by Web service / Webhosting?
41. What are Cookies in Browser? How to enable or disable it.
42. Define and explain all parts of a URL of a website. i.e.
https://www.google.co.in/images/Sun.jpg.
43. Differentiate between the following:
(i) WWW vs Website. (ii) Website vs Webpage
(iii) Webpage vs Homepage (iv) Static vs Dynamic Webpage
(v) URL vs DNS(Domain Name) (vi) HTML vs XML
44. A teacher provides: "http://www.abcschool.com/default.aspx" to
his/her Students to identify the URL & domain name.
45. Identify the following devices :
(i) I am a networking device used to connect multiple computers.
I send data to intended node only.
(ii) If a node from one network wants to connect to another (foreign)
network it will pass the data packet through me
(iii) I am a wireless device which provide Wi- Fi access to smart
phones and other devices.
************************************************************************

APPAN RAJ D PGT- CS/IP 190


OBJECTIVE TYPE QUESTIONS
1. What is a standalone computer?
(a)A computer that is not connected to a network.
(b)A computer that is being used as a server.
(c)A computer that does not have any peripherals
attached to it.
(d)A computer that is used by only one person.
2. Two devices are in network if
(a) A process in one device is able to exchange information
with a process in another device.
(b) A process is running on both the devices.
(c) The processes running on different devices are of same
type.
(d) none of these.
3. Network in which every computer is capable of playing the role
of a client, or a server or both at same time is called
(A)peer-to-peer network (B)Local Area network
(C)dedicated server network (D)wide area network
4. Which of the following is not required for a computer network?
(A)host (B)server (C)communication channel (D)plotter
5. Which of this component is internal to a computer and is
required to connect the computer to a network?
(A)Wireless Access Point (B)Network Interface card
(C)Switch (D)Hub
6. Central computer which is more powerful than other computers
in the network is called as__________.
(A)Client (B)Server (C)Hub (D)Switch
7. First computer network was ______________.
(a)NSFNet (b)FirstNet (c)ARPANet (d)Internet
8. Your school has four branches spread across the city.
A computer network created by connecting the computers of all
the school branches, is a____________.
(A)LAN (B)WAN (C)MAN (D)PAN

APPAN RAJ D PGT- CS/IP 191


9. Mid 80’s commercial public internet was _________.
(A)ARPANET (B)CNNET
(C)NSFNET (D)Internet
10. Advantages of the Network?
(A)Expensive Hardware (B)Specialist staff required
(C)Communication (D)Hacking
11. Two or more computers connected together over a wide
Geographical area (e.g. county, country, globe). What
type of network is this?
(A)LAN (B)School Network (C)WAN (D)The Internet
12. Internet was created in 1969 by US Defence through?
(A)SARPA (B)DARPA (C)MARPA (D) ARPA
13. It transmits data in the form of light signals rather than electrical
signals.
(A) Coaxial Cable (B) Twisted Pair Cable
(C) Fibre Optics Cable (D) None
14. Name the network which was only used for academic purpose.
(A) NSFNET (B) ARPANET (C) INTRANET (D)INTERNE
15. Choose odd one out:
(A) Satellite (B) Radio wave (C)Twisted Pair (D) Laser
16. Which is not a component of data communicationsystem?
a) Protocol b) Message c) Media d) Diode
17. Protocols are set of rules to govern
a) Communication b) Standards
c) Metropolitan communication
d) Wireless communication
18. Transmission media are usually categorized as
a) Fixed and Unfixed b) Guided and Unguided
c)Determinate and Indeterminate d) Metallic and Nonmetallic
19. Which of the following primarily uses guided media?
a) Cellular telephone system b) Local telephone system
c) Satellite communications d) Radio broadcasting
20. Which of the following cables carry data signals in theform of
light?
a) Coaxial b) Fiber-optic c) twisted pair d) All of the these

APPAN RAJ D PGT- CS/IP 192


21. In a fiber-optic cable, the signal is propagated along theinner core
by
a) Reflection b) Refraction c) modulation d) Interference
22. To send data/message to and from computer, thenetwork
software puts the message information in a
………….?
a) Header b) Tailor c) NIC d) Packet
23. …………… is the transmission of data between two ormore
computer over communication links?
a) Data Communication b) Data Networking
c) Networking d) Communication
24. Which cable is used for voice and data communications?
a) Coaxial b) Fiber-optic c) Twisted Pair d) None of the these
25. Which of the following is not a guided medium?
a) Twisted Pair b) Coaxial Cable
c) Fiber-optic d) Atmosphere
26. What does HTTPS stand for?
a) Hyper Text Protocol Secure
b) Hypertext Transfer Protocol Secure
c) Hidden Text Transfer Protocol Station
d) Hypertext Transfer Protocol Station
27. What are the key elements of a protocol?
a) Syntax b) Semantics c) Timing d) All of these
28. Which of the following transmission directions listed is not a
legitimate channel?
a) Simplex b) Double Duplex c) Half Duplex d) Full Duplex
29. What is the full form of TCP/IP?
a) Transfer Control Protocol/ Internet Protocol
b) Transfer Communication Protocol/Internet Protocol
c) Transmission Control Protocol/Internet Protocol
d) Transmission Communication Protocol/Internet Protocol
30. A set of rules that need to be followed by the communicating
parties in order to have successful and reliable data
communication is called___
A. Syntax B. Protocols C. Medium D. Semantics

APPAN RAJ D PGT- CS/IP 193


31. Which of the following are components of Data
Communication?
A. Sender B. Receiver C. Protocol D. All the above
32. Which of the following are components of Data
Communication?
A. Sender B. Receiver C. Protocol D. All the above
33. The data or information that needs to be exchanged
between the sender and the receiver is called___
A. Protocol B. Message C. Medium D. Sender
34. Transmission of digital data between two or more
computers/nodes is called?
A.Network B. Internet C. Ethernet D. Data Communication
35. What is a network?
(a) Group of interconnected people or things
(b) Two or more computers connected together and sharing
information
(c) Both of the above (d) None of the above
36. The physical path between sender and receiver through which the
message or data travels.
A. Hub/switch B. transmission medium C. client
D. server
37. What is a protocol?
A. Keynotes and information about the internet.
B. set of rules and regulation that governs proper data
communication amongst users.
C. methodologies to send and receive data amongst users.
D. set of instructions for the prevention of outsourcing hackers.
38. A_____is set of devices/nodes/computers connected by media
links.
A. Server B. Message C. Network D. Protocol
39. Twisted-pair, co-axial cable and optical fibre are types of____.
A. Media B. Protocols C. Data D. Messages
40. A Channel is defines as a path between___
A. Media and Receiver B. Transmitter and Media
C. Tansmitter and Receiver D. None of these

APPAN RAJ D PGT- CS/IP 194


41. ____is the device that has the data and needs to send the data to
other device connected to the network.
A. Receiver B. Media C. Sender D. Messages
42. Various types of senders on network are__
A. mobile phone B. smart watch C. walkie-talkie D. all the
above
43. Which of the following are communication media?
A. Telephone Cable B. Ethernet Cable C. Satellite Link
D. All the above
44. Various types of receivers on network are__
A. Printer B. Computer C. Mobile phone D. All the above
45. In which of the following switching methods, the message is
divided into small packets?
A. Message switching B. Packet switching
C. Circuit switching D. None of these
46. The term "TCP/IP" stands for_____
A. Transmission Contribution protocol/ internet protocol
B. Transmission Control Protocol/ internet protocol
C. Transaction Control protocol/ internet protocol
D. Transmission Control Protocol/ internet protocol
47. ___________ Address is assigned to network cards by
manufacturer.
a. IP b.MAC c.unique d.domain
48. The IP(Internet protocol) of TCP/IP transmits packets over the
internet using ______
A. Circuit B. Message C. Packet D. All of these
49. Which of the following unit measures the speed with which data
can be transmitted from one node to another node of a network
?Also give the expansion of the suggested unit:
(A)Mbps (B)KMph (C)MGps
50. What is the meaning of Bandwidth in Network?
A. Transmission capacity of a communication channels
B. Connected Computers in the Network
C. Class of IP used in Network D. None of Above

APPAN RAJ D PGT- CS/IP 195


51. Which of the following is not correct about the switch
(a) It is an intelligent HUB
(b) It send signal only to the intended node
(c) It cannot forward multiple packets at the same time
(d) It help to connect multiple computers
52. Each IP packet must contain:
A. Only Source address
B. Only Destination address
C. Source and Destination address
D. Source or Destination address
53. The next generation IP addressing system to succeed IPv4 is __
A)IPv4.1 B)IPv5 C)IPv6 D)IPv5.1
54. _________ cable consists of an inner copper core and a second
conducting outer sheath.
A) Twisted-pair B) Shielded twisted-pair
C) Coaxial D) Fiber-optic
55. __________ consists of a central conductor and a shield.
A) Twisted-pair B) Coaxial
C) Fiber-optic D) None of the above
56. _______ cable can carry signals of higher frequency ranges
than _______ cable.
A) Coaxial; twisted-pair B) Twisted-pair; fiber-optic
C) Coaxial; fiber-optic D) none of the above
57. _________ are used for cellular phone, satellite, and wireless LAN
communications.
A) Radio waves B) Infrared waves
C) Microwaves D) none of the above
58. The inner core of an optical fibre is _________ in composition.
A) copper B) glass or plastic C) bimetallic D) liquid
59. ________ cable consists of two insulated copper wires twisted
together.
A) Twisted-pair B) Coaxial
C) Fiber-optic D) none of the above

APPAN RAJ D PGT- CS/IP 196


60. A(n) _______ medium provides a physical conduit from one
device to another.
A) unguided B) guided
C) either (a) or (b) D) none of the above
61. Which type of network is formed, when you connect two mobiles
using Bluetooth to transfer a picture file?
(a) PAN (b) LAN (b) MAN (c) WAN
62. Which transmission media is capable of having a much higher
bandwidth (data capacity)?
A. Coaxial B. Twisted pair cable
C. Untwisted cable D. Fiber optic
63. Which type of transmission media is the least expensive to
manufacture?
A. Coaxial B. Twisted pair cable C. CAT cable D. Fiber optic
64. In computer, converting a digital signal in to an analogue signal
is called
A. modulation B. demodulation
C. conversion D .transformation
65. Which of these is not an example of unguided media?
A. Optical Fibre Cable B. Radio wave C. Bluetooth D. Satellite
66. Which of the following is not a type of guided or wired
Communication channel?
A. Twisted Pair B. Coaxial C.Fibre Optic D. WiMax
67. Which of the following is not a type of unguided or wireless
communications channel?
A. Microwave B. Radio wave C. Ethernet D. Sattelite
68. Which of the following wireless medium consists of a
Parabolic antenna mounted on towers?
A. Satellite B. Radiowave C. Microwave D. Infrared
69. Which of the following cable consist of a solid wire core
Surrounded by one or more foil or wire shields?
A. Ethernet Cables B. Coaxial Cables
C. Fibre Optic Cables D. Power Cable
70. Which of the following is domain in http://www.google.com
(A) http (B) www (C) google (D) com
71. Which of the following is transmission medium for TV remotes?
(a) Infrared (b) Coaxial cable (c) Bluetooth (d)Microwave
72. Protocol required for sending mails
(A) SMTP (B) PPP (C) POP (D) UDP

APPAN RAJ D PGT- CS/IP 197


73. The technique in which a message is converted to small
A) Circuit switching (B) Message switching
(C) Packet switching (D) None of these
74. Which of the following is not a web browser:
(A)Mozilla Firefox (B) Google (C) Internet Explorer
(D)Netscape Navigator
75. An introductory web page that appears when you first
open your browser.
A. Web site B. Web Page C. Home Page D. Web Browser
76. Rohan wants to establish computer network in his office, which
of the following device will be suggested by you to connect each
computer in the cafe?
A. Switch B. Modem C. Gateway D. Repeater
77. Google Chrome is example of :
A. Programming Language B. Web Server
C. Protocol D. Web Browser
8. An internet is a __________
A. Collection of WANS B. Network of networks
C. Collection of LANS D. Collection of identical LANS and
WANS
79. Which of the following is transmission medium for TV remotes?
(a) Infrared (b) Coaxial cable (c) Bluetooth (d)Microwave
80. Which of the following devices will connect both source and
destination computer.
(a) HUB (b) SWITCH (c) MODEM (d) ROUTER
81. Which of the following is not correct about the switch
(a) It is an intelligent HUB
(b) It send signal only to the intended node
(c) It cannot forward multiple packets at the same time
(d) It help to connect multiple computers
82. _______ is a device that forwards data packets along networks.
(a) Gateway (b) Modem (c) Router (d) Switch

APPAN RAJ D PGT- CS/IP 198


ABBREVATIONS [2 MARKS]

1. Expand the following terms:


(i) HTML (ii) ARPANET (iii) WAN (iv) MAN (v) ISP
2. Expand the following terms:
(i) XML (ii) WWW (iii) SMTP (iv) TCP/IP (v) FTP
3. Expand the following terms:
(i) LAN (ii) SSH (iii) HTTP (iv) NIC (v) SSL
4. Expand the following terms:
(i) ISP (ii) HTTPS (iii) PPP (iv) DNS (v) WAP
5. Expand the following terms:
(i) NSFnet (ii) VoIP (iii) URL (iv) HTTP (v) TbPs
6. Expand the following terms:
(i) NIC (ii) IMAP (iii) Wi-Max (iv) Wi-Fi. (v) MAC
7. Expand the following terms:
(i) CHAP (ii) AJAX (iii) IRC (iv) POP3 (v) PHP
8. Expand the following terms:
(i) PHP (ii) SSH (iii) XML (iv) SIM (v) GSM
9. Expand the following terms:
(i) IMAP (ii) VPN (iii) PAN (iv) DHTML (v) RJ-45
10. Expand the following terms:
(i) STP (ii) UTP (iii) IRC (iv) SIP (v) bps
11. Expand the following terms:
(i) GBPS (ii) TelNet (iii) GPS (iv) GSM (v) E-Mail
12. Expand the following terms:
(i) MODEM (ii) IR (iii) WLL (iv) GPRS (v) SLIP

APPAN RAJ D PGT- CS/IP 199


LAN DESIGN BASIC QUESTIONS
[5 MARKS QUESTIONS]
1. Be-Happy Corporation has set up its new centre at Noida, Uttar
Pradesh for its office and web-based activities. It has 4 blocks of
buildings.

(a) Suggest and draw the cable layout to efficiently connect various
blocks of buildings within the Noida centre for connecting the
digital devices.
(b) Suggest the placement of the following device with
justification: i. Repeater ii. Hub/Switch
(c) Which kind of network (PAN/LAN/WAN) will be formed if
the Noida office is connected to its head office in Mumbai?
(d) Which fast and very effective wireless transmission medium
should preferably be used to connect the head office at Mumbai
with the centre at Noida?
(e) Suggest a protocol that shall be needed to provide Video
Conferencing solution between Block A to C.

APPAN RAJ D PGT- CS/IP 200


2. INDIAN PUBLIC SCHOOL in
Darjeeling is setting up the network
between its Different wings. There
are 4 wings named as SENIOR(S),
JUNIOR (J), ADMIN (A) and HOSTEL
(CH).

(i) Suggest a suitable Topology for networking the computer of all


wings.
(ii) Name the wing where the Server is to be installed. Justify your
answer.
(iii) Suggest the placement of Hub/Switch in the network.
(iv) Mention an economic technology to provide internet accessibility
to all wings.
(v) Suggest the wired Transmission Media used to connect all buildings
efficiently.

3. Quick Learn University is setting up its academic blocks at Prayag


Nagar and planning to set up a network. The university has 3
academic blocks and one Human resource Centre as shown in the
diagram given below:

APPAN RAJ D PGT- CS/IP 201


(a) Suggest a cable layout of connection between the blocks.
(b) Suggest the most suitable place to house the server of the
organization with Suitable reason.
(c) Which device should be placed/installed in each of these blocks to
efficiently? Connect all the computers within these blocks?
(d) The university is planning to link its sales counters situated in
various parts of the other cities. Which type of network out of
LAN, MAN or WAN will be formed?
(e) Which network topology may be preferred in each of these blocks?

3. ABC company has planned


to set up their head office
in New Delhi in three
locations and have named
their New Delhi offices as
“Sales Office”, ”Head Office”
and “Tech Office”. The
company’s regional offices
are located at ”Coimbatore”,
“Kolkata” and
“Ahmedabad”.:

APPAN RAJ D PGT- CS/IP 202


(i) Suggest network type (out of LAN, MAN, WAN) for connecting
each of the following set of their offices:
(a) Head Office and Tech Office
(b) Head Office and Coimbatore Office

(ii) Which device will you suggest to be procured by the company for
connecting all the computers within each of, their offices out of
the following devices? • Modem • Telephone • Switch/Hub

(iii) Which of the following communication media, will you suggest to


be procured by the company for connecting their local offices in
New Delhi for very effective and fast communication?
• Ethernet Cable • Optical Fiber • Telephone Cable
(iv) Suggest a cable/wiring layout for connecting the company’s local
offices located in New Delhi. Also, suggest an effective technology
for connecting the company’s regional offices at “Kolkata”,
“Coimbatore” and “Ahmedabad”.
4. Knowledge Supplement Organisation has 4 blocks of buildings as
shown in the diagram below:

(i) Suggest a cable layout


of connections between the blocks.
(ii) Suggest the most suitable place (i.e. block) to house the server of
this organisation with a suitable reason.
(iii) Suggest the placement of the following devices with justification:
(a) Repeater (b) Hub/Switch.

APPAN RAJ D PGT- CS/IP 203


(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?
(v) Suggest a system (hardware/software) to prevent unauthorized
access to or from the network.
5. ABC University has 3 academic blocks

a) Suggest the most suitable place (i.e., Block/Centre) to install


the server of this University with a suitable reason.
b) Suggest an ideal layout for connecting these blocks/centres
for a wired connectivity.
c) Which device will you suggest to be placed/installed in each
of these blocks/centres to efficiently connect all the
computers within these blocks/centres?
d) Suggest the placement of a Repeater in the network with
justification.
e) The university is planning to connect its admission office in
Delhi, which is more than 1250 km from university. Which
type of network out of LAN, MAN, or WAN will be formed?
Justify your answer.

APPAN RAJ D PGT- CS/IP 204


6. Eduminds University of India is starting its first campus in a small
town Parampur of Central India with its centre admission office in
Delhi. The university has 3 major buildings comprising of Admin
Building, Academic Building and Research Building in the 5 KM area
Campus. As a network expert, you need to suggest the network
plan as per (a) to (b) to the authorities keeping in mind the distances
and other given parameters.

(a) Suggest to the authorities, the cable layout amongst various


buildings inside the university campus for connecting the buildings.
(b) Suggest the most suitable place (i.e., building) to house the server of
this Organisation, with a suitable reason.
(c) Suggest an efficient device from the following to be installed in each
of the building to connect all the computers:
(i) GATEWAY (ii) MODEM (iii) SWITCH
(d) Suggest the most suitable (very high speed) service to provide data
connectivity between Admission Building located in Delhi and the
campus located in Parampur from the following options :
● Telephone line ● Fixed–Line Dial–up connection ● Co–axial Cable
● Network GSM ● Leased line ● Satellite Connection.

APPAN RAJ D PGT- CS/IP 205


(e) What type of network would this connection result into?
7. Rehaana Medicos Centre has set up its new center in Dubai. It has
four buildings as shown in the diagram given below:

As a network expert, provide the best possible answer for the following
queries:

(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) Suggest the placement of the Hub/ Switch with justification.

APPAN RAJ D PGT- CS/IP 206


12. Fun Services Ltd is an event
planning organization. You as a
network expert need to suggest the
best network-related solutions for
them.

i. Suggest the most appropriate location of the server inside the


MUMBAI campus (out of the 4 buildings). Justify your answer.
ii. Draw the cable layout to efficiently connect various buildings within
the MUMBAI campus.
iii. Which hardware device will you suggest to connect all the
computers within each building?
iv. Which of the following will you suggest to establish online face-to-
face communication between the people in the Admin Office of the
MUMBAI campus and the DELHI Head Office?
a. Cable TV b. Email c. Video Conferencing d. Text Chat
v. What type of network (out of PAN, LAN, MAN, WAN) will be set up
in each of the following cases?
a. The Mumbai campus gets connected with the Head Quarter in
Delhi.
b. The computers connected in the MUMBAI campus.

******************************************************************************

APPAN RAJ D PGT- CS/IP 207


CHAPTER 10 – EXCEPTION HANDLING
PRACTICE QUESTIONS

THEORY QUESTIONS
1. Define the following: (i) Module (ii) Package
2. What is meant by Library in Python?
3. Define Exception Handling in Python and explain its importance in
programming.
4. What is the Problem in the following code:
from import factorial
print(math.factorial(5))
5. Discuss common built-in exception types in Python and when they
might occur during program execution
6. How to handle the exceptions in Python?
7. Explain the purpose of the try, except, and finally blocks in Python's
exception handling mechanism.
8. Write the difference between IndexError and ValueError.
9. Consider the code given below and fill in the blanks:

11. Every
syntax error is an exception but every exception is
cannot be a syntax error. Justify your answer.
12. Describe the role of the raise statement in Python's
exception handling. Provide an example.

APPAN RAJ D PGT- CS/IP 208


STATE TRUE OR FALSE
1. An exception may be raised even if the program is syntactically
correct
2. In Python, the except block is mandatory whenever a try block is
used
3. An exception may be raised even if the program is syntactically
correct.
4. It's good practice to have a bare except: block in Python exception
handling.
5. The else block in exception handling is executed if no exception
occurs in the try block.
6. The except block in Python can catch multiple types of exceptions
by specifying them within a single block.
7. The finally block in Python can modify the exception before it is
re-raised.
8. The finally block in Python always executes, regardless of
whether an exception is raised or not.
9. The finally block in Python is executed before the try block.
10. Python's exception hierarchy allows catching multiple exceptions
with a single except block by specifying a tuple of exception
types.
11. It is possible to nest multiple try-except blocks within each other
in Python.
12. The following code will print "This line won't be executed":
try:
num = 5 / 0
except ValueError:
print("Value Error")
else:
print("This line won't be executed")
finally:
print("Finally block executed")
13. The following code will print "Exception caught":
try:
raise Exception("An Exception occurred")
except Exception as e:
print("Exception caught")

APPAN RAJ D PGT- CS/IP 209


14. The following code will print "10", "No error occurred", and
"Finally block executed":
try:
num = int('10')
print(num)
except ValueError:
print("Value Error")
else:
print("No error occurred")
finally:
print("Finally block executed")
15. The following code will print "Zero Division Error":
try:
num = 5 / 0
except ValueError:
print("Value Error")
finally:
print("Zero Division Error")
ASSERTION & REASONING
1. A: SyntaxError: Missing parentheses in call to ‘print’.
R: SyntaxError: It is raised when there is an error in the
Syntax of the Python code.
2. A: NameError: name 'X' is not defined
R:NameError: It is raised when the requested module
Definition is not found.
3. A: TypeError: can only concatenate str (not "int") to str
R: TypeError: It is raised when an operator is supplied
with a value of incorrect data type.
4. A: The try-except block in Python is used to
handle exceptions that may occur during the
execution of a program.
R: The try-except block allows a program to attempt
executing code that may raise an exception, and
provides a mechanism to catch and handle the
exception if it occurs.

APPAN RAJ D PGT- CS/IP 210


5. A: It's recommended to use a bare except: block in Python
exception handling to catch all possible exceptions.
R: A bare except: block catches all exceptions, including
those that the programmer may not have anticipated,
making it convenient but potentially risky.
6. A: The finally block in Python's exception handling
mechanism is always executed regardless of whether
an exception occurs or not.
R: The finally block provides a way to execute cleanup
code, ensuring that certain actions are performed
whether or not an exception is raised.
7. A: Python's exception handling mechanism is limited to
only runtime errors.
R: Python's exception handling can handle both runtime
errors and compile-time errors, providing a robust way
to deal with unexpected issues during program
execution.
8. Consider the following code:
try:
num = 5 / '0'
except TypeError:
print("TypeError occurred")

A: The try-except block in Python is used to handle specific


types of exceptions that may occur during the execution
of a program.

R: In the given code, the try block attempts to convert the


string 'ten' to an integer using the int() function. If the
conversion fails due to the string not being a valid
integer representation, a ValueError exception is raised.
The except block catches this specific ValueError and
prints a message indicating that a ValueError occurred.

APPAN RAJ D PGT- CS/IP 211


OBJECTIVE TYPE MCQ
1. What is an exception in Python?
a) An error that occurs during the execution of a program
b) A predefined function in Python
c) A variable with a special name
d) A loop construct in Python
2. Which of the following statements about exception handling in
Python is FALSE?
a) A single try block can have multiple except blocks to
handle different types of exceptions
b) An except block without any specified exception type
catches all exceptions
c) The finally block is executed only if an exception occurs
d) It's considered good practice to have a bare except: block
without specifying the exception type
3. Which keyword is used to handle exceptions in Python?
a) try b) catch c) except d) handle
4. Which block of code is used to catch exceptions in Python?
a) try b) catch c) except d) finally
5. What happens if an exception is raised in the try block but not
handled by any except block?
a) The program terminates with an error message
b) The program continues executing normally
c) The program goes into an infinite loop
d) The program waits for user input
6. What is the purpose of the finally block in exception handling?
a) To catch exceptions
b) To execute code regardless of whether an exception
occurs or not
c) To ignore exceptions
d) To re-raise exceptions
7. What is the purpose of the else block in exception handling in
Python?
a) To catch exceptions
b) To execute code when no exception occurs in the try
block
c) To handle exceptions
d) To re-raise exceptions

APPAN RAJ D PGT- CS/IP 212


8. Which of the following is NOT a standard exception in Python?
a) StopIteration b) KeyError C) NoValueError d) ValueError
9. What type of error is returned by following statement?
print(int("a"))
(a) Syntax error (b) ValueError (c) TypeError (d) None
10. What will be the output of the following Python code?
lst = [1, 2, 3]
lst[3]
a) NameError b) ValueError
c) IndexError d) TypeError
11. It is raised when the denominator in a division operation is
zero.
(a) Index Error (b) IndentationError
(c) ZeroDivisionError (d) TypeError
12. It is raised when the index or subscript in a sequence is out of
range.
(a) IndexError (b) IndentationError
(c) ZeroDivisionError (d) TypeError
13. It is raised when a local or global variable name is not
defined.
(a) IndexError (b) IndentationError
(c) ZeroDivisionError (d) NameError
14. It is raised due to incorrect indentation in the program
code.
(a) IndexError (b) IndentationError
(c) ZeroDivisionError (d) NameError
15. It is raised when an operator is supplied with a value of incorrect
data type.
(a) IndexError (b) TypeError
(c) ZeroDivisionError (d) NameError
16. It is raised when the result of a calculation exceeds the
maximum limit for numeric data type.
(a) OverFlowError (b) TypeError
(c) ZeroDivisionError (d) NameError
17. IndentationError is a type of:
(a) SyntaxError (b) Logical Error
(c) Runtime Error (d) Other

APPAN RAJ D PGT- CS/IP 213


18. What is the purpose of the assert statement in Python?
a) To handle exceptions
b) To raise exceptions
c) To check for conditions that must be true, raising an
AssertionError if the condition is false
d) To print error messages
19. Which of the following defines ValueError?
(a) It is raised when the file specified in a program
statement cannot be opened.
(b) It is raised when there is an error in the syntax of the
Python code.
(c) It is raised when a built-in method or operation
receives an argument that has the right data type but
Mismatched or inappropriate values.
(d) It is raised due to incorrect indentation in the program
code.
20. Which of the following statements is false?
(a) A try-except block can have more than one except
statement
(b) One block of except statement cannot handle multiple
exceptions
(c) The finally block is always executed
(d) When 1 == "1" is executed, no exception is raised
21. In Python, which exception will not be caught by the following
except block?
try:
# Some code that might raise an exception
except:
print("Exception occurred")
a) ValueError b) TypeError
c) IndexError d) KeyboardInterrupt
22. What happens if an exception is raised inside the finally block in
Python?
a) The exception is suppressed
b) The program terminates with an error message
c) The program continues executing normally
d) The exception is re-raised
20. Which of the following is not a component of the math module in
Python?
(a) ceil() (b) mean() (c) fabs() (d) pi

APPAN RAJ D PGT- CS/IP 214


21. The following Python code will result in an error if the input
value is entered as -5. >>> assert False, 'Tamil'
a) True b) False
22. What will be the output of the following code?
try:
num = 5 / 0
except:
print("An error occurred")
else:
print("No error occurred")
a) An error occurred
b) No error occurred
c) This code will raise an error but won't print anything.
d) An error occurred, No error occurred
23. What will be the output of the following code?
try:
num = 5 / 0
except ZeroDivisionError:
print("Zero Division Error")
finally:
print("Finally block executed")
a) Zero Division Error, Finally block executed
b) Finally block executed
c) This code will raise an error but won't print anything.
d) Zero Division Error
24. What will be the output of the following code?
try:
num = int('10')
print(num)
except ValueError:
print("Value Error")
else:
print("No error occurred")
finally:
print("Finally block executed")
a) 10, No error occurred, Finally block executed
b) Value Error, Finally block executed
c) This code will raise an error but won't print anything.
d) 10, Finally block executed
******************************ALL THE BEST!!!************************

APPAN RAJ D PGT- CS/IP 215

n-gl.com

You might also like