Class 12 Board Revision Study Material and Worksheet With Solutions
Class 12 Board Revision Study Material and Worksheet With Solutions
VARIABLES
One of the most powerful features of a programming language is the ability to manipulate
variables. A variable is a name that refers to a value
ASSIGNMENT STATEMENTS
An assignment statement creates a new variable and gives it a value:
>>> message = 'And now for something completely different'
>>> n = 17
>>> pi = 3.141592653589793
Multiple Assignments
Python allows you to assign a single value to several variables simultaneously
a=b=c=1
a, b, c = 1, 2, "john"
VARIABLE NAMES
A variable is basically a name that represents (or refers to) some value. Variable are reserved
memory locations to store values.
KEYWORDS
Keywords are the reserved words in Python. We cannot use keywords as variable name,
function name or any other identifier. They are used to define the syntax and structure of the
Python language. In Python, keywords are case sensitive. Python 3 has these keywords:
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 1 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Q.No Questions
1 State True or False
“Python has a set of keywords that can also be used to declare variables”
2 Every variable in Python holds an instance of an object.
These Objects are of two types.
(a) Mutable (b) immutable (c) both a and b (d) instance
3 The PASS statement is an empty statement in Python
4 State whether True or False:
Variable names can begin with the _ symbol. True.
5 Which of the following is not a valid identifier in Python?
a)KV2 b) _main c) Hello_Dear1 d) 7 Sisters
6 State True or False
“Python identifiers are dynamically typed.”
7 Identify the invalid variable name from the following.
Adhar@Number, none, 70outofseventy, mutable
8 Find the invalid identifier from the following
(a) name (b) class (c) section (d) break
9 Find the invalid identifier from the following
a) sub%marks b)age c)_subname_ d)subject1
10 Which of the following is an invalid identifier?
1. CS_class_XII b. csclass12 c. _csclass12 d. 12CS
11 State True or False “Python is a case insensitive language.” False
12 Find the invalid identifier from the following
a) KVS_Jpr b) false c) 3rdPlace d) _rank
13 Find the valid identifier from the following
(a) Tot$balance (b) TRUE (c) 4thdata (d) break
14 Find the valid identifier from the following
a) My-Name b) True c) While d) S_name
15 Which of the following is not a valid identifier name in Python?
a) 5Total b) _Radius c) pie d)While
16 Which of the following is not a valid identifier name in Python?
a) 5Total b) _Radius c) pie d)While
17 Find the invalid identifier from the following
a) MyName b) True c) 2ndName d) My_Name
18 Which is a valid identifier in python?
(a) int (b) len (c) ssum1 (d) all of them
19 Python identifiers are case sensitive.
a) True b) False
20 Find the invalid identifier from the following:
a) None b) address c) Name d) Pass
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 2 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 3 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
A statement is a unit of code that has an effect, like creating a variable or displaying a value.
>>> n = 17
>>> print(n)
PYTHON OPERATORS
Operators are the constructs which can manipulate the value of operands
Types of Operators
1) Arithmetic Operators
2) Comparison (Relational) Operators
3) Assignment Operators
4) Logical Operators
5) Membership Operators
6) Identity Operators
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 4 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 5 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 6 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Q.No Questions
What will be the following expression be evaluated to in Python?
1 print(round(100.0 / 4 + (3 + 2.55),1))
a) 30.0 b) 30.55 c) 30.6 d) 31
Evaluate the following expression
2 Not 20>21 and 6>5 or 7>9
(a) True (b) False (c) 3 (d) None of these
What will the following Python statement evaluate to?
3 print (5 + 3 ** 2 / 2)
(a) 32 (b) 8.0 (c) 9.5 (d) 32.0
Consider the following expression:
not True and False or not False
4
Which of the following will be the output:
a) True b) False c) None d) NULL
How will the following expression be evaluated in Python?
5 2 + 9 * ( ( 3 * 12) – 8 ) / 10
a) 29.2 b) 25.2 c) 27.2 d) 27
Which statement will give the output as : True from the following :
a) >>>not -5
6 b) >>>not 5
c) >>>not 0
d) >>>not(5-1)
Consider the given expression:
True and False or Not True
7 Which of the following will be correct output if the given expression is
evaluated?
(a) True (b) False (c) NONE (d) NULL
What will the following expression be evaluated to in Python?
8 2**3**2+15//3
a) 69 b) 517 c) 175 d) 65
Evaluate the following expression:
9
False and bool(15/5*10/2+1)
State true or false:
10 (i) -88.0 is the output of the print(3-10**2+99/11)
(ii) Range( ) is also a module function
Evaluate the following expressions:
11 a) 6+7*4+2**3//5-8
b) 8<5 or no 19<=20 and 11<4
Evaluate the following expressions:
12
a) 16 // 3 + 3 ** 3 + 15 / 4 - 9
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 7 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 8 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 9 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 10 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
a) 2 b) 2.0 c) 4.0 d) 4
Consider the given expression:
7%5==2 and 4%2>0 or 15//2==7.5
52 Which of the following will be correct output if the given expression is
evaluated?
(a)True (b) False (c)None (d)Null
Consider the given expression:
(5<10)and(10<5)or(3<18)and not(8<18)
53 Which of the following will be correct output if the given expression is
evaluated?
(a) True (b) False (c) NONE (d) NULL
The correct output of the given expression is:
54 True and not False or False
(a) False (b) True (c) None (d) Null
Evaluate the following Python expression
55 print(12*(3%4)//2+6)
(a)12 (b)24 (c) 10 (d) 14
Predict the correct output of the following Python statement –
56 print(4 + 3**3/2)
(a) 8 (b) 9 (c) 8.0 (d) 17.5
Consider the given expression:
(not True) and False or True
57
Which of the following is the correct value of the expression?
a) True b) False c) None d) NULL
What will the following expression be evaluated to in Python?
58 15.0 // 4 * 5 / 3
a) 6.25 b) 5 c) 5.0 d) 0.25
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 11 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Errors
Python provides two very important features to handle any unexpected error in your Python
programs and to add debugging capabilities in them
Exception Handling.
Assertions.
What is Exception?
An exception is an event, which occurs during the execution of a program that disrupts the normal
flow of the program's instructions.
An exception is a Python object that represents an error.
When a Python script raises an exception, it must either handle the exception immediately
otherwise it terminates and quits
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 12 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
PYTHON – CONDITIONALS
Decision making is anticipation of conditions occurring while execution of the program and specifying
actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You need to
determine which action to take and which statements to execute if outcome is TRUE or FALSE otherwise
conditional (if)
alternative (if…else)
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 13 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 14 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
REASSIGNMENT
As you may have discovered, it is legal to make more than one assignment to the same variable. A new
assignment makes an existing variable refer to a new value (and stop referring to the old value)
UPDATING VARIABLES
A common kind of reassignment is an update, where the new value of the variable depends on the old.
>>> x = x + 1
While Loop - A while loop statement in Python programming language repeatedly executes a target statement
as long as a given condition is true
Syntax
while(test-condition):
body of the loop;
statement-x;
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 15 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
THE for STATEMENT - A for statement is also called a loop because the flow of execution runs through the
body and then loops back to the top
Syntax
for variable in sequence:
body of the loop;
statement-x;
break STATEMENT
Sometimes you don’t know it’s time to end a loop until you get halfway through the body. In that case
you can use the break statement to jump out of the loop. break is used to break out of the innermost loop.
For example, suppose you want to take input from the user until they type done. You could write:
continue STATEMENT - continue is used to skip execution of the rest of the loop on this iteration and continue
to the end of this iteration
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 16 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
pass STATEMENT - ‚pass‛ statement acts as a place holder for the block of code. It is equivalent to a null
operation. It literally does nothing.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 17 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Q.No Questions
1 What will be the output of the following Python code snippet?
X=11
If X<=10:
X+=10
if X<=20 :
X+=10
If X<=30:
X+=30
a.21 b. 31 c.61 d. None of these
2 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
3 Predict the Output:
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)
4 Give output
RS=’’
S=”important”
for i in S:
RS=i+RS
print(RS)
5 Find and write the output of the following Python code:
data=["P",20,"R",10,"S",30]
times=0
alpha=" "
add=0
for c in range(1,6,2):
times = times + c
alpha = alpha + data [c-1] + "$"
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 18 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
elif s[i].isalpha( ):
m=m+s[i].upper( )
else:
m=m+'bb'
print(m)
16 Predict the Output
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)
17 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)
18 Find and write the output of the following Python code:
str1 = 'Pre-Board Exam@2023'
str2=""
for i in range(0,len(str1)-1):
if(str1[i].islower()):
str2=str2+str1[i].upper()
elif str1[i].isupper():
str2=str2+str1[i].lower()
elif str1[i].isdigit():
str2=str2+'d'
else:
str2=str2+(str1[1-i])
print(str2)
19 Predict the output of below given Python code
s="Abc2@xYz"
m=""
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 21 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
for i in range(len(s)):
if s[i].isupper():
m+=s[i].lower()
elif s[i].islower():
m+=s[i].upper()
elif s[i].isdigit():
m+=s[i-1]
else:
m = m +'#'
print(m)
20 Predict the Output
TXT = ["20","50","30","40"]
CNT = 3
TOTAL = 0
for C in [7,5,4,6]:
T = TXT[CNT]
TOTAL = float(T) + C
print(TOTAL)
CNT -= 1
21 Find the output of the following code:
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®
elif s[i].isalpha():
m=m+s[i].upper()
else:
m=m+'bb'
print(m)
23 Write the output of following python code
T="Happy New Year 2023"
L=len(T)
ntext=""
for i in range (0,L):
if T[i].isupper():
ntext=ntext+T[i].lower()
elif T[i].isalpha():
ntext=ntext+T[i].upper()
else:
ntext=ntext+"*"
print (ntext)
24 Write the output of following python code
s = "Cricket"
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)
25 Predict the Output
Msg1="WeLcOME"
Msg2="GUeSTs"
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]
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 23 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
else:
Msg3=Msg3+"*"
print(Msg3)
26 Predict the Output
str = '[email protected]'
m=""
for i in range(0,len(str)):
if(str[i].isupper()):
m=m+str[i].lower()
elif str[i].islower():
m=m+str[i].upper()
else:
if i%2==0:
m=m+str[i-1]
else:
m=m+"#"
print(m)
27 Predict the Output
S = "Python 3.9"
k=len(S)
m=''
for i in range(0,k):
if S[i].isalpha( ):
m=m+S[i].upper( )
elif S[i].isdigit( ):
m=m+'0'
else:
m=m+'#'
print(m)
28 T1 = (12, 22, 33, 55 ,66)
list1 =list(T1)
new_list = []
for i in list1:
if i%3==0:
new_list.append(i)
new_T = tuple(new_list)
print(new_T)
29 s = 'KVS@Jammu'
k=len(s)
m=""
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 24 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
for i in range(0,k):
if(s[i].isupper()):
m=m+str(i)
elif s[i].islower():
m=m+s[i].upper()
else:
m=m+'*'
print(m)
30 s ="Back2Basic"
n = len(s)
NS =""
for i in range(0, n):
if (s[i] in 'aeiou'):
NS = NS + s[i].upper()
elif (s[i] >= 'a' and s[i] <= 'z'):
NS = NS +s[i].lower()
else:
NS = NS + '#'
print(NS)
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 25 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
PYTHON STRINGS - A string is a sequence, which means it is an ordered collection of other values.
Strings in Python are identified as a contiguous set of characters represented in the quotation
marks.
Python allows for either pairs of single or double quotes.
Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in
the beginning of the string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator
Strings are immutable
Example:
str = 'Hello World!'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string
Output:
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 26 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
String Methods
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 27 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 28 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 29 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
str.strip(characters) removes any leading, and trailing straight =" banana "
whitespaces. Leading means at the change = straight.strip()
beginning of the string, trailing print("of all fruits", change, "is my
means at the end favorite")
of all fruits banana is my favorite
str.rstrip(characters) method removes any trailing straight =" banana "
characters (characters at the end a change = straight.rstrip()
string), space is the default trailing print("of all fruits", change, "is my
character to remove favorite")
of all fruits banana is my favorite
str.lstrip(characters) removes any leading characters straight =" banana "
(space is the default leading change = straight.lstrip()
character to remove) print("of all fruits", change, "is my
favorite")
of all fruits banana is my favorite
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 30 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Q.No Questions
Select the correct output of the code:
>>> s='[email protected]'
>>> s=s.split('kv')
>>> op = s[0] + "@kv" + s[2]
1 >>> print(op)
(A) mail2@kvsangathan
(B) mail2@sangathan.
(C) mail2@kvsangathan.
(D) mail2kvsangathan
What will be the output of the following statement given:
txt="cbse. sample paper 2022"
print(txt.capitalize())
2 a) CBSE. sample paper 2022
b) CBSE. SAMPLE SAPER 2022
c) cbse. sample paper 2022
d) Cbse. Sample Paper 2022
Select the correct output of the following code:
>>>str1 = ‘India is a Great Country’
>>>str1.split(‘a’)
3 a) [‘India’,’is’,’a’,’Great’,’Country’]
b) [‘India’, ’is’, ’Great’, ’Country’]
c) [‘Indi’, ’is’, ’Gre’, ’t Country’]
d) [‘Indi’, ’is’, ’Gre’, ’t’, ‘Country’]
Identify the output of the following Python statement:
s=”Good Morning”
print(s.capitalise( ),s.title( ), end=”!”)
4 (a) GOOD MORNING!Good Morning
(b) Good Morning! Good Morning
(c) Good morning! Good Morning!
(d) Good morning Good Morning!
What is the output of the following code?
S1=”Computer2023”
5 S2=”2023”
print(S1.isdigit(), S2.isdigit())
a)False True b) False False c) True False d) True True
Select the correct output of the following code :
6
s=“I#N#F#O#R#M#A#T#I#C#S”
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 31 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
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’]
Select the correct output of the code:
Str = "KENDRIYA VIDYALAYA SANGATHAN JAMMU REGION"
Str = Str.split()
NewStr = Str[0] + "#" + Str[1] + "#" + Str[4]
7 print (NewStr)
a) KENDRIYA#VIDYALAYA#SANGATHAN# JAMMU
b) KENDRIYA#VIDYALAYA#SANGATHAN
c) KENDRIYA#VIDYALAYA# REGION
d) None of these
What is the output of the following?
print('KV Sangathan'.split('an'))
(a) ['KV S', 'gath', ' ']
8
(b) [‘KV Sangathan’,’an’]
(c) [‘KV’,’Sang’,’athan’]
(d) All of them
What is the output of the following code.
Str1=”Hello World”
9 str1.replace('o','*')
str.replace('o','*')
(a) Hello World (b) Hell* W*rld (c) Hello W*rld (d) Error
Select the correct output of the code:
mystr = ‘Python programming is fun!’
mystr = mystr.partition(‘pro’)
mystr=’$’.join(mystr)
10
(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!
Select the correct output of the following string operations
mystring = “Pynative”
stringList = [ “abc”, “Pynative”,”xyz”]
11
print(stringList[1] == mystring)
print(stringList[1] is mystring)
a) True b) False c) False d) True
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 32 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 33 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Q.No Questions
Suppose str1= ‘welcome’. All the following expression produce the same
1 result except one. Which one?
(a) str[ : : -6] (b) str[ : : -1][ : : -6] (c) str[ : :6] (d) str[0] + str[-1]
Which of the following will be the output of the code:
mySubject = “Computer Science”
2
print(mySubject[:3] + mySubject[3:])
a) Com b) puter Science c) Computer Science d) Science Computer
What will be the output of following code snippet:
msg = “Hello Friends”
3
msg [ : : -1]
a)Hello b) Hello Friend c) 'sdneirF olleH' d) Friend
Give the output:
my_data = (1, 2, "Kevin", 8.9)
4
print (my_data[-3])
1. 8.9 2. “Kevin”. 3. 1 4. 2
If S=”Pythonlanguage”
5
Predict the output of print(S[:-6:-2])
Given is a Python string declaration:
6 myexam="@@CBSE Examination 2023@@"
Write the output of: print(myexam[::-3])
Given a string S = “ComPUterSciEnce”,
7
write the output of print(S[3:10:2])
If the following code is executed, what will be the output of the following
code?
8
n="Trust yourself that you can do it and get it"
print(n[2:-4:2])
Select the correct output of the code:
Str=“Computer”
9 Str=Str[-4:]
print(Str*2)
a. uter b. uterretu c. uteruter d. None of these
Find output generated by the following code:
10 mystr = “Hello I am a Human.”
print(mystr[::-3])
Given is a Python string declaration:
11 Word = "Connect Python”
Write the output of: print(Word[: : 3])
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 34 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 35 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 36 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Python Lists
Example:
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists
Output:
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 37 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
List Methods
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 38 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 39 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Q.No Questions
1 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
2 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
3 Consider the following code:
dict1 = {‘Mohan’: 95, ‘Ram’: 89, ‘Suhel’: 92, ‘Saritha’: 85}
What suitable code should be written to return a list of values in dict1 ?
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 40 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
a[i-1]=a[i]
for i in range(0,5):
print(a[i],end=" ")
(a) 5 5 1 2 3 (b) 5 1 2 3 4 (c) 2 3 4 5 1 (d) 2 3 4 5 5
9 Which one is the correct output for the following code?
a=[1,2,3,4]
b=[sum(a[0:x+1]) for x in range(0,len(a))]
print (b)
(a) 10 (b) [1,3,5,7] (c) 4 (d) [1,3,6,10]
10 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]
11 Given the list L=[“A”, “E”, “I”, “O”, “U”] , write the output of
print(L[2:5])
12 A List is declared as
List1=[2,3,5,7,9,11,13]
What will be the value of len(List1)
13 Identify the data type of INFO:
INFO = ['hello',203,'9',[5,6]]
a. Dictionary b. String c. Tuple d. List
14 Given the list L=[-1,4,6,-5] ,write the output of print(L[-1:-3])
a)[4,6,-5] b)[] c)[6,-5] d)error
15 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
16 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]
17 Identify the output of the following Python statements, where L1 is a List
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’]
18 Which of the following statements create a dictionary?
a) d = {}
b) d = {“john”:40, “peter”:45}
c) d = {40:”john”, 45:”peter”}
d) All of the mentioned above
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 41 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
(d) dict.merge(result)
25 Which is the correct form of declaration of dictionary?
a) Day={1:’Monday’,2:’Tuesday’,3:’Wednesday’}
b) Day={‘1:Monday’,’2:Tuesday’,’3:Wednesday’}
c) Day=(1:’Monday’,2:’Tuesday’,3:’Wednesday’)
d) Day=[1:’Monday’,2:’Tuesday’,3:’Wednesday’]
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 43 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Python Tuples
Example:
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuple) # Prints complete list
print (tuple[0]) # Prints first element of the list
print (tuple[1:3]) # Prints elements starting from 2nd till 3rd
print (tuple[2:]) # Prints elements starting from 3rd element
print (tinytuple * 2) # Prints list two times
print (tuple + tinytuple) # Prints concatenated lists
Output:
('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 44 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Tuple Methods
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 45 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Q.No Questions
1 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
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 Suppose a tuple T1 is declared as T1 = (10, 20, 30, 40, 50) which of the
following is incorrect?
a)print(T1[1]) b) T1[2] = -29 c) print(max(T)) d) print(len(T))
4 Suppose a tuple K is declared as K = (100, 102, 143, 309), which of the
following is incorrect?
a)print(K[-1]) b) K[3] =405 c) print(min(K)) d) print(max(K))
5 Identify valid declaration of tuple
a)T={‘a’,’b’,’c’,’d’} b) T=‘a’,’b’,’c’,’d’ c)D=(‘a’,’b’,’c’,’d’) d) both b and c
6 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
7 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)
8 Write the output of following code:
Tup1=(10,15,20,25,30)
print(Tup1[-1:0:-2])
The output is : (30, 20)
9 Suppose a tuple T is declare as:
T=(10,12,43,39)
Which of the following is in correct?
(a) print(t[1]) (b) T[2]=-29 (c) print(max(T) (d) print(len(T))
10 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)
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 46 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
b) (10,20,[30,100,50],60,70)
c) (10,20,[100,40,50],60,70)
d) None of these
11 Which of the following options will not result in an error when
performed on types in
python where tp = (5,2,7,0,3) ?
(a) tp[1] = 22
(b) tp.append(23)
(c) tp1 = tp+tp*2
(d) tp.sum()
12 Given tp = (1,2,3,4,5,6). Which of the following two statements will give
the same output?
1. print(tp[:-1])
2. print(tp[0:5])
3. print(tp[0:4])
4. print(tp[-4:])
(a) Statement 1 and 2 (b) Statement 2 and 4 (c) Statement 1 and 4 (d)
Statement 1 and 3
13 Write the output of the code given below:
a,b,c,d = (1,2,3,4)
mytuple = (a,b,c,d)*2+(5**2,) - 9
print(len(mytuple)+2) = 11
The output is 11
14 What will be the output of the following code snippet?
init_tuple_a =( 'a', '3’)
init_tuple_b = ('sum', '4')
print (init_tuple_a + init_tuple_b)
The output is : (‘a’,’3’,’sum’,’4’)
15 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
16 Choose the correct output of following code:
Tup=(100)
print(Tup*3)
(A) (300,) (B) (100,100,100) (C) Syntax Error (D) 300
17 Find the output:
tuple1 = (10,12,14,16,18,20,22,24,30)
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 47 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 48 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Python Dictionary
Example:
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values
Output:
This is one
This is two
{'name': 'john', 'code': 6734, 'dept': 'sales'}
dict_keys(['name', 'code', 'dept'])
dict_values(['john', 6734, 'sales'])
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 49 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Dictionary Methods
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 50 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 51 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
print(bike)
{'brand': 'Yamaha', 'model': 'Aerox', 'year': 2021}
{'brand': 'Yamaha', 'model': 'Aerox'}
popitem() Removes the last bike =
inserted key- {"brand":"Yamaha","model":"Aerox","year":2021}
value pair print(bike)
vehicle = bike.popitem()
print(bike)
{'brand': 'Yamaha', 'model': 'Aerox', 'year': 2021}
{'brand': 'Yamaha', 'model': 'Aerox'}
setdefault() returns the value of bike =
the item with the {"brand":"Yamaha","model":"Aerox","year":2021}
specified key print(bike)
vehicle = bike.setdefault("color","Blue")
print(vehicle)
print(bike)
{'brand': 'Yamaha', 'model': 'Aerox', 'year': 2021}
Blue
{'brand': 'Yamaha', 'model': 'Aerox', 'year': 2021,
'color': 'Blue'}
max() get the dictionary key fruitscolor = {"Banana" : "Yellow",
with the max values "Mango" : "Green",
"Apple" : "Red",
"Grapefruit" : "Pink",
"Blackberry" : "Purple",
"Sapodilla" : "Brown"}
maximum = max(fruitscolor,key =
fruitscolor.get)
print(maximum)
Banana
min() get the dictionary fruitscolor = {"Banana" : "Yellow",
key "Mango" : "Green",
with the min values "Apple" : "Red",
"Grapefruit" : "Pink",
"Blackberry" : "Purple",
"Sapodilla" : "Brown"}
minimum = min(fruitscolor,key =
fruitscolor.get)
print(minimum)
Sapodilla
Sorted() sort the items of the fruitscolor = {"Banana" : "Yellow",
dictionary. This "Mango" : "Green",
method returns a "Apple" : "Red",
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 52 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 53 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Python Modules
A Python module can be defined as a Python program file which contains a Python code
including Python functions,class or variables.
To make use of the function in a module, you will need to import the module with an ‘import’
statement.
To import entire module, import statement is used. Import statement is also used to import
selecting modules.
you can refer to the functions by name rather than through dot notation.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 54 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 55 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
>>>print(math.floor(b))
−75
>>>x = math.pi
>>>print(math.floor(x))
3
pow() pow(x,y) >>>import math
This method offers to >>>x = 3
compute the power of a >>>y = 4
number and >>>print(pow(y, x))
hence can make task of 64
calculating power of a >>>print(pow(7, 2))
number easier. In this, two 49
types to calculate power. >>>print(pow(–3, 2))
● 9
pow (x, y) converts its >>>print(pow(–4, 3))
arguments into float and then –64
computes the power >>>print(pow(5, –2))
0.04
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 56 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
>>>print(math.fabs(–4.3))
4.3
sin() math.sin(x) >>>import math
This method returns the sine >>>x = 65
of value passed as argument. >>>math.sin(x)
The value passed in this 0.8268286794901034
function should be in radians. >>>print(math.sin(5.3245521))
–0.8184069203707078
>>>a = math.pi
>>>x = a/4
>>>math.sin(x)
0.7071067811865475
cos() math.cos(x) >>>import math
This method returns the >>>x=9
cosine of value passed as >>>math.cos(x)
argument. –0.9111302618846769
The value passed in this >>>math.cos(0)
function should be in radians 1.0
>>>print(math.cos(30))
0.15425144988758405
>>>math.cos(–4)
–0.6536436208636119
>>>a = math.pi
>>>math.cos(a)/2
–0.5
tan() math.tan(x) >>>import math
This method returns the >>>x=30
tangent of value passed as >>>math.tan(x)
argument. –6.405331196646276
The value passed in this >>>math.tan(0)
function should be in radians. 0.0
>>>math.tan(90)
–1.995200412208242
>>>print(math.tan(–5))
3.380515006246586
pi math.pi >>>import math
It is a mathematical constant, >>>math.pi
the ratio of circumference of a 3.1415926.....
circle to its diameter.
e math.e >>>import math
It is a mathematical constant >>>math.e
2.71828182846
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 57 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Random Module/Functions
Python offers random module that can generate random numbers. These random modules
depend on a pseudo random number that generate function random() and this number
generates a random float number between 0.0 and 1.0.
Statistics Module
Python is a very popular language when it comes to data analysis and statistics. Python has
ability to solve the mathematical expression, statistical data by importing statistics keyword.
Statistics module was added in Python 3.4 version. Earlier version of Python cannot access this
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 58 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
module. To access Python’s statistics functions, we need to import the functions from the
statistics module.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 59 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 60 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Q.No Questions
1 Study the following program and select the possible output(s) and
write maximum and minimum value assigned to the variable y
import random
x=random.random( )
y=random.ranint(0,4)
print(int(x),”:”,y+int(x))
(i) 0:0 (ii) 1: 6 (iii) 2:4 (iv) 0:3
2 What possible output(s) are expected to be displayed on screen at the
time of execution of the following code? Also specify the maximum and
minimum value that can be assigned to variable X.
import random
L=[10,7,21]
X=random.randint(1,2)
for i in range(X):
Y=random.randint(1,X)
print(L[Y],”$”,end=” ”)
(a) 10 $ 7 $ (b) 21 $ 7 $ (c) 21 $ 10 $ (d) 7 $
3 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 @
4 Which of the following is not a function/method of the random module
in python?
(a) randfloat( ) (b) randint( ) (c) random( ) (d) randrange( )
5 To include the use of functions which are present in the random
library, we must use the option:
a) import random b) random.h c) import.random d) random.random
6 What are the incorrect output(s) from the given options when the
following code is executed? Also specify the minimum and maximum
values that can be assigned to the variable VALUE.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 61 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
import random
VALUE = random.randint (0,3)
SUBJECT=[“PHY”,”CHEM”,”MATHS”,”COMP”];
for I in SUBJECT:
for J in range(1, VALUE):
print(I, end=””)
print()
Options:
i) PHYPHY
CHEMCHEM
MATHSMATHS
COMPCOMP
ii) PHY
PHYCHEM
PHYCHEMMATHS
iii) PHY
CHEMCHEM
COMPCOMPCOMP
iv) PHY
CHEM
MATHS
COMP
7 Go through the python code shown below and find out the possible
output(s) from the suggested options i to iv. Also specify maximum and
minimum value that can be assigned to the variable j.
import random
i=random.random()
j=random.randint(0,6)
print(int(i),”:”,j+int(i))
(i)0:0 (ii)0:6 (iii)1:7 (iv)1:6
8 What possible output(s) are expected to be displayed on screen at the
time of execution of the program from the following code? Also write
the value assigned to variable first and second.
import random
from random import randint
LST=[5,10,15,20,25,30,35,40,45,50,60,70]
first = random.randint(3,8) – 1
second = random.randint(4,9) – 2
third = random.randint(6,11) – 3
print(LST[first],"#", LST[second],"#", LST[third],"#")
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 62 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
begin=random.randint(1,3)
last=random.randint(2,4)
for c in range(begin,last+1):
print(points[c],"#")
(a) 20#50#30# (b) 20#40#45 (c) 50#20#40# (d) both (b) and (c)
15 .Identify the output of the following python statements
import random
for n in range(2,5,2):
print(random.randrange(1,n),end=‟*‟)
(a)1*3 (b) 2*3 (c) 1*3*4 (d)1*4
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 64 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Python Functions
A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing
Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
functionname( parameters )
You can define functions to provide the required functionality. Here are simple rules to define a
function in Python.
Function blocks begin with the keyword def followed by the function name and parentheses (( )).
Any input parameters or arguments should be placed within these parentheses. You can also
define parameters inside these parentheses.
The first statement of a function can be an optional statement - the documentation string of the
function or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an expression to the
caller. A return statement with no arguments is the same as return none.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 65 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
SCOPE OF VARIABLES
All variables in a program may not be accessible at all locations in that program. This depends on where
you have declared a variable. The scope of a variable determines the portion of the program where you
can access a particular identifier. There are two basic scopes of variables in Python:
Global variables
Local variables
Example 1
Output:
Inside the function local total : 30
Outside the function global total : 0
Example 2
Output:
Inside the function local total : 30
Outside the function global total : 30
Required Arguments
Required arguments are the arguments passed to a function in correct positional order.
Here, the number of arguments in the function call should match exactly with the function
definition.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 66 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Example 1
def add(fn,sn):
print("sum of 2 number is",fn+sn)
fn = int(input("Enter First Number: "))
sn = int(input("Enter Second Number: "))
add(fn,sn)
Output:
Enter First Number: 25
Enter Second Number: 35
sum of 2 number is 60
Example 2
def add(fn,sn):
print("sum of 2 number is",fn+sn)
fn = int(input("Enter First Number: "))
sn = int(input("Enter Second Number: "))
add()
Output:
Enter First Number: 10
Enter Second Number: 20
TypeError: add() missing 2 required positional arguments: 'fn' and 'sn'
Keyword Arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is
able to use the keywords provided to match the values with parameters.
Example 1
Output:
Department : EEE
Section : A
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 67 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Example 2
def IYear(Dept, Sec):
print ("Department :", Dept)
print ("Section :", Sec)
IYear(Dept = "EEE", Name = "A")
Output:
TypeError: IYear() got an unexpected keyword argument 'Name
Default Arguments
A default argument is an argument that assumes a default value if a value is not provided
in the function call for that argument.
Example 1
Output:
First Number : 25
Second Number : 35
First Number : 35
Second Number : 35
Note that when defining a function all the argument with default values should come at the end
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 68 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Q.No Questions
1 Write a function INDEX_LIST(L), where L is the list of elements passed as
argument to the function. The function returns another list named
‘indexList’ that stores the indices of all Non-Zero Elements of L. For
example: If L contains [12,4,0,11,0,56] The
indexList will have - [0,1,3,5]
2 Write a function LShift(arr,n) in python, which accepts a list of numbers
and 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] and n=2
Output
Arr :[30,40,50,12,11,10,20]
3 Write a python program using function to find the largest element in a list
and then reverse the list contents and display it. Don’t use in-built
functions for the program
4 Write a function sumcube(L) to test if an element from list L is equal to
the sum of the cubes of its digits ie 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
5 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]
6 Write a function SUMNOS() that accept a list L of numbers and find sum
of all even numbers and sum of all odd numbers.
If L=[1,2,3,4],
Output :
sum of even nos:6
Sum of odd numbers:4
7 Write a function GENERATE_INDEX(L), where L is the list of elements
passed as argument to the function. The function returns another list
named ‘NewIndex’ that stores the indices of all even Elements of L.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 69 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 70 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 71 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
a list Array of numbers and swaps the elements of 1st Half of the list
with the 2nd Half of the list, ONLY if the sum of 1st Half is greater
than 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 Write a function INDEX_LIST(S), where S is a string. The function returns
a 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]
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 72 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Q.No Questions
1
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 73 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
NUM=1
OUTER(NUM,1)
OUTER(NUM,2)
print(NUM,"@",X)
7 Predict the Output:
a=10
b=20
def change( ):
global b
a=45
b=56
change( )
print(a)
print(b)
8 Predict the Output:
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)
9 Predict the Output:
def f():
global s
s += ' Is Great'
print(s)
s = "Python is funny"
s = "Python"
f()
print(s)
10 Predict the Output:
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])
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 75 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
r = change (r,s)
print(r,"#",s)
s = change(s)
15 Predict the Output:
x=1
def fun1():
x=3
x=x+1
print(x)
def fun2():
global x
x=x+2
print(x)
fun1()
fun2()
16 Predict the Output
x = 20
def myfunc():
global x
x = 10
print(x)
myfunc()
print(x,end=" ")
17 Predict the Output:
def fun(x):
x[0] = 5
return x
g = [10,11,12]
print(fun(g),g)
18 Predict the Output:
L1 =[]
def display(N):
for K in N:
if K % 2 ==0:
L1.append(K//2)
else:
L1.append(K*2)
L = [11,22,33,45,55,66]
print(L)
display(L)
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 77 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
print(L1)
19 Predict the Output:
p=5
def sum(q,r=2):
global p
p=r+q**2
print(p, end= '#')
a=10
b=5
sum(a,b)
sum(r=5,q=1)
20 Predict the Output:
Value = 100
def funvalue():
global Value
Value//=9
print(Value,end=" ")
Value-=10
print(Value,end=" ")
funvalue()
21 Predict the Output:
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)
22 Predict the Output:
def Change(P ,Q=40):
P=P+Q
Q=P-Q
print( P,"#",Q)
return (P)
R=100
S=200
R=Change(R,S)
print(R,"#",S)
S=Change(S)
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 78 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 80 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Q.No Questions
1 Identify the errors in the program segment given below. 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])
print(Tot[6])
2 Observe the following Python code very carefully and rewrite it after
removing all syntactical errors with each correction underlined.
DEF result_even( ):
x = input(“Enter a number”)
if (x % 2 = 0) :
print (“You entered an even number”)
else:
print(“Number is odd”)
even ( )
3 Ramu wrote a code function to display Fibonacci series. Correct the errors and
rewrite it.
def Fibonacci()
nterms = int(input("How many terms? "))# first two terms
n1, n2 = 0, 1
count = 0
if nterms<= 0:# check if the number of terms is valid
Print("Please enter a positive integer");
elifnterms == 1:# if there is only one term, return n1
print("Fibonacci sequence upto",nterms,":")
print(n1);
else:# generate fibonacci sequence
print("Fibonacci sequence:")
while count >nterms:
print(n1)
nth = n1 + n2
n1 = n2# update values
n2 = nth
count -= 1
4 Rewrite the following code after removing the syntactical error(if
any).Underline each correction:
X=input("Enter a Number")
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 81 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
If x % 2 =0:
for i range (2*x):
print i
loop else:
print "#"
5 Shraddha 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.
6 Mr. Gupta 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”)
7 Rewrite the following Python program after removing all the syntactical
errors (if any), underlining each correction:
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”
x=int(input(“Enter a number”)
8 Reena has written a code to check the maximum of given numbers. Her code
is having errors. Rewrite the correct code with output and underline the
correction made.
def printMax(a, b)
if a> b:
print(a, 'is maximum')
elif a = b:
print(a, 'is equal to', b)
else;
print(b, 'is maximum')
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 82 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
printMax(33,94):
9 Rewrite the following code in Python after removing all syntax error(s).
Underline each correction done in the code.
for Name in [Aakash, Sathya, Tarushi]
IF Name[0]= 'S':
print(Name)
for Name in[“Aakash”, “Sathya”, “Tarushi”]:
if Name[0]== 'S':
print(Name)
10 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
11 Find the error(s) in the following code snippet and write the corrected code.
Def check():
N=25
for i in range(0,N):
if N%2=0:
print(N*2)
elif N%3==0
print(N*3)
Else:
print(N)
check()
12 Rewrite the following code in Python after removing all syntax error(s).
Underline each correction done in the code.
STRING=""WELCOME
NOTE = " "
for S in range(0,8):
if STRING[S]= ’E’:
print(STRING(S))
Else:
print “NO”
13 Rajat has written the following Python code. There are some errors in it.
Rewrite the
correct code and underline the corrections made.
DEF execmain():
x = input("Enter a number:")
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 83 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
if (abs(x)=x):
print ("You entered a positive number")
else:
x=*-1
print "Number made positive:"x
execmain()
14 Raman has written a code to find its sum of digits of a given number passed as
parameter to
function sumdigits(n). His code is having errors. Rewrite the correct code and
underline the
corrections made.
def sumdigits(n):
d=0
for x in str(n):
d=d+x
return d
n=int(input(‘Enter any number”))
s=sumdigits(n)
print(“Sum of digits”,s)
15 Aman has write the code to find factorial of an integer number as follow. But he
got some error while running this program. Kindly help him to correct the
errors.
num=int(input("Enter any integer number"))
fact=1
for x of range(num,1,-1)
if num=1 or num=0
print ("Fact=1")
break
else
fact=fact*x
print(fact)
16 Correct Code is
def DigitSum():
n = int( input("Enter number :: ")
dsum = 0
while n > 0
d = n % 10
dsum =dsum + d
n = n //10
RETURN dsum
17 Mr. Ram has written a code to input two numbers and swap the number using
function but he has some error in his coding, so help him to rectify the errors
and rewrite the correct code.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 84 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Def swap(a,b)
c=a
a=b
b=c
print("a is",a,"b is",b )
#main()
a=int(input("enter in a "))
b=int(input("enter in b"))
Swap(a,b)#calling a function
18 Rewrite the following code in python after removing all errors. Underline each
correction done in the code:
num=int(“Enter any value”)
for in range(0,11):
if num==i
print num+i
else:
Print num-i
19 function and he has written the following code but it’s not working and
producing
errors. Help Sumit to correct this and rewrite the corrected code. Also underline
the
corrections made.
Def prime (num):
factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
else num == 0
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
20 Consider the following code written by a programming student. The student is
a beginner and has made few errors in the code. You are required to 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
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 85 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
return n
result = swap({‘a’:1,’b’:2,’c’:3})
print(result)
21 Mr. Akash has written a code , His code is having errors , Rewrite the correct
code and underline the correction s made.
5x=input(“Enter a number”)
If(abs(x)=x):
Print(“You Entered a positive number..”)
Else:
x=x-1
print(“Number made positive:”x)
22 Anshika has written a code to calculate the factorial value of a number, but her
code is having some errors. Rewrite the correct code and underline the
corrections made.
def Factorial(Num)
1=fact
While num=>0:
fact=fact*num
num=-1
print(“Factorial value is =”,fact)
23 A student has written a code to print a pattern of even numbers with equal
intervals. His code is having errors. Rewrite the correct code and underline the
corrections made.
def pattern(start=0, end, interval):
for n in range(start: end, interval):
if(n%2==1):
print(n)
else
pass
x=int(input("Enter Start Number: "))
y=int(input("Enter End Number: "))
z=int(input("Enter Interval: "))
pattern(x,y,z)
24 Yuvika has to complete her computer science assignment of demonstrating the
use of if-else statement. The code has some error(s). Rewrite the correct code
underlining all the corrections made.
marks = int(“enter marks”)
temperature = input(“enter temperature”)
if marks < 80 and temperature >= 40
print(“Not Good”)
else
print(“OK”)
25 Rewrite the following code in python after removing all syntax errors.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 86 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Underline each
correction done in the code:
Def func(a):
for i in (0,a):
if i%2 =0:
s=s+1
else if i%5= =0
m=m+2
else:
n=n+i
print(s,m,n)
func(15)
26 Vivek has written a code to input a number and check whether it is even or odd
number. His code is having errors. Rewrite the correct code and underline the
corrections made.
Def checkNumber(N):
status = N%2
return
#main-code
num=int( input(“ Enter a number to check :))
k=checkNumber(num)
if k = 0:
print(“This is EVEN number”)
else:
print(“This is ODD number”)
27 Sameer has written a python function to compute the reverse of a number.
He has however committed a few errors in his code. Rewrite the code after
removing errors also underline the corrections made.
define reverse(num):
rev = 0
While num > 0:
rem == num %10
rev = rev*10 + rem
num = num//10
return rev
print(reverse(1234))
28 Preety has written a code to add two numbers .Her code is having errors.
Rewrite the correct
code and underline the corrections made.
def sum(arg1,arg2):
total=arg1+arg2;
print(”Total:”,total)
return total;
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 87 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
sum(10,20)
print(”Total:”,total)
29 Rewrite the following code in python after removing all the syntax
errors. Underline each correction done in the code.
num1, num2 = 10
While num1 % num2 = 0
num1+= 20
num2+= 30
Else:
print(„hello‟)
30 Rewrite the following code in python after removing all syntax error(s).
Underline each correction done in the code.
30=Value
for VAL in range(0,Value)
If val%4==0:
print (VAL*4)
Elseif val%5==0:
print (VAL+3)
else
print(VAL+10)
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 88 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
What is Stack?
Operations on Stack
There are mainly two types of Operation that can be done with stack.
i) Push
ii) Pop
Pop : Removal of an element from the top of the stack is called Pop.
Push and Pop Operations are done from single end called TOP
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 89 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Underflow : It refers to a situation when one tries to pop/delete an item from an empty
stack or queue. That is stack or queue is currently having no element and still one tried
to pop an element.
1. Creating a stack
2. Push/Adding elements to the stack
3. Checking for empty stack
4. Pop/Deleting elements from a stack
5. Traversal/Displaying a stack
Stack Implementation
Write a python program to maintain book details like book code, book title and price
using stack.
#(implement push(), pop() and traverse() functions)
book=[]
def push():
bcode=input("Enter bcode ")
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 90 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
def pop():
if(book==[]):
print("Underflow / Book Stack in empty")
else:
bcode,btitle,price=book.pop()
print("poped element is ")
print("bcode ",bcode," btitle ",btitle," price ",price)
def traverse():
if not (book==[]):
n=len(book)
for i in range(n-1,-1,-1):
print(book[i])
else:
print("Empty , No book to display")
while True:
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")
ch=int(input("Enter your choice "))
if(ch==1):
push()
elif(ch==2):
pop()
elif(ch==3):
traverse()
elif(ch==4):
print("End")
break
else:
print("Invalid choice")
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 91 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
20
10
5
STACK EMPTY
3 Write a Python function CREATESTACK(L), which should create two lists
SO and SE from the list L containing integers. The stack SO should contain
all the odd elements of the list L, and the stack SE should contain all the
even elements of the list L. Also, write a function POPSTACK( ) which
should pop and print all the elements of the stack SE, and print stack empty
at the end.
For example, if the list L is [2,7,9,15,14]
Then SO should be [7,9,15]
SE should be [2,14]
Output of POPSTACK( ) function should be 14 2 Stack Empty
4 Write a Python function MYSTACK(d), which should accept a dictionary d
of the form roll : name as argument. The function should create a stack
MYNAME having all the names containing ‘s’ or ‘S’. Also, write a function
POPSTACK( ) which should pop and print all the elements of the stack
MYNAME, and print stack empty at the end.
For example, if the dictionary d is {1: ‘Sunil’, 2:’Naman’, 3:’Anish’}
Then MYNAME should be [‘Sunil’, ‘Anish’]
Output of POPSTACK( ) function should be Anish Sunil Stack Empty
5 A list contains following record of a student:
[student_name, marks, subject]
Write the following user defined functions to perform given operations on
the stack named ‘status’:
(i) Push_element() - To Push an object containing name and marks of a
student who scored more than 75 marks in ‘CS’ to the stack
(ii) Pop_element() - To Pop the objects from the stack and display them.
Also, display
“Stack Empty” when there are no elements in the stack.
For example:
If the lists of customer details are:
[“Danish”,80,”Maths”]
[“Hazik”,79,”CS”]
[“Parnik”,95,”Bio”]
[“Danish”,70,”CS”]
[“Sidhi”,99,”CS”]
The stack should contain
[“Hazik”,”79”]
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 93 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
[“Sidhi”,”99”]
The output should be:
[“Hazik”,”79”]
[“Sidhi”,”99”]
Stack Empty
6 (i)Write the definition of a user defined function PushNV(N) which accepts
a list of strings in the parameters N and pushes all strings which have no
vowels present in it, into a list named NoVowel.
(ii)Write a program in python to input 5 words and push them one by one
into a list named All.
The program should then use the function PushNV() to create a stack of
words in the list NoVowel so that it stores only those words which do not
have any vowels in it, from the list All. Thereafter , pop each word from
the list NoVowel and display the message
“EmptyStack”
For example:
If the words accepted and pushed into the list All are
[‘DRY’,’LIKE’,’RHYTHM’,’WORK’,’GYM’]
Then the stack NoVowel should store
[‘DRY’,’RHYTHM’,’GYM’]
And the output should be displayed as
GYM RHYTHM DRY EmptyStack
7 Write the definition of a user defined function Push3_5(N) which accepts a
list of integers in a parameter N and pushes all those integers which are
divisible by 3 or divisible by 5 from the list N into a list named Only3_5.
Write a program in Python to input 5 integers into a list named NUM.
The program should then use the function Push 3_5() to create the stack of
the list Only3_5. Thereafter pop each integer from the list Only3_ 5 and
display the popped value. When the list is empty, display the message
"StackEmpty".
For example:
If the integers input into the list NUM are:
[10, 6, 14, 18, 30]
Then the stack Only3 5 should store
[10, 6, 18, 30]
And the output should be displayed as
30 18 6 10 StackEmpty
8 A list contains following record of a student:
[StudentName, Class, Section, MobileNumber]
Write the following user defined functions to perform given operations on
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 94 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Computer Networks
Types of Networks
There are various types of computer networks ranging from network of handheld devices
(like mobile phones or tablets) connected through Wi-Fi or Bluetooth within a single room to
the millions of computers spread across the globe. Some are connected wireless while others
are connected through wires. Based on the geographical area covered and data transfer rate,
computer networks are broadly categorised as:
PAN ( Personal Area Network)
LAN (Local Area Network)
MAN (Metropolitan Area Network)
WAN (Wide Area Network)
It is a network formed by connecting a few personal devices like computers, laptops, mobile
phones, smart phones, printers etc.,
All these devices lie within an approximate range of 10 metres.
A personal area network may be wired or wireless.
For example, a mobile phone connected to the laptop through USB forms a wired PAN while
two smartphones communicating with each other through Bluetooth technology form a
wireless PAN or WPAN.
It is a network that connects computers, mobile phones, tablet, mouse, printer, etc., placed
at a limited distance.
The geographical area covered by a LAN can range from a single room, a floor, an office
having one or more buildings in the same premise, laboratory, a school, college, or
university campus.
The connectivity is done by means of wires, Ethernet cables, fibre optics, or Wi-Fi.
LAN is comparatively secure as only authentic users in the network can access other
computers or shared resources.
Users can print documents using a connected printer, upload/download documents and
software to and from the local server.
Such LANs provide the short range communication with the high speed data transfer rates.
These types of networks can be extended up to 1 km.
Data transfer in LAN is quite high, and usually varies from 10 Mbps (called Ethernet) to
1000 Mbps (called Gigabit Ethernet), where Mbps stands for Megabits per second.
Ethernet is a set of rules that decides how computers and other devices connect with each
other through cables in a local area network or LAN
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 96 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Network Devices
To communicate data through different transmission media and to configure networks with
different functionality, we require different devices like Modem,Hub, Switch, Repeater, Router,
Gateway, etc.
Modem
Modem stands for ‘MOdulator DEModulator’.
It refers to a device used for conversion between analog signals and digital bits.
We know computers store and process data in terms of 0s and 1s.
However, to transmit data from a sender to a receiver, or while browsing the internet,
digital data are converted to an analog signal and the medium (be it free-space or a physical
media) carries the signal to the receiver.
There are modems connected to both the source and destination nodes.
The modem at the sender’s end acts as a modulator that converts the digital data into
analog signals.
The modem at the receiver’s end acts as a demodulator that converts the analog signals into
digital data for the destination node to understand.
Ethernet Card
Ethernet card, also known as Network Interface Card (NIC card in short) is a network
adapter used to set up a wired network.
It acts as an interface between computer and the network.
It is a circuit board mounted on the motherboard of a computer
The Ethernet cable connects the computer to the network through NIC.
Ethernet cards can support data transfer between 10 Mbps and 1 Gbps (1000 Mbps).
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 97 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Each NIC has a MAC address, which helps in uniquely identifying the computer on the
network.
RJ45
RJ 45 or Registered Jack-45 is an eight-pin connector that is used exclusively with Ethernet
cables for networking.
It is a standard networking interface that can be seen at the end of all network cables.
Basically, it is a small plastic plug that fits into RJ-45 jacks of the
Ethernet cards present in various computing devices.
Repeater
Data are carried in the form of signals over the cable.
These signals can travel a specified distance (usually about 100 m).
Signals lose their strength beyond this limit and become weak.
In such conditions, original signals need to be regenerated.
A repeater is an analog device that works with signals on the cables to which it is connected.
The weakened signal appearing on the cable is regenerated and put back on the cable by a
repeater.
Hub
An Ethernet hub is a network device used to connect different devices through wires.
Data arriving on any of the lines are sent out on all the others.
The limitation of Hub is that if data from two devices come at the same time, they will
collide
Switch
A switch is a networking device that plays a central role in a Local Area Network (LAN).
Like a hub, a network switch is used to connect multiple computers or communicating
devices.
When data arrives, the switch extracts the destination address from the data packet and
looks it up in a table to see where to send the packet.
Thus, it sends signals to only selected devices instead of sending to all.
It can forward multiple packets at the same time.
A switch does not forward the signals which are noisy or corrupted.
It drops such signals Cables connected to a network switch and asks the sender to resend it.
Ethernet switches are common in homes/offices to connect multiple devices thus creating
LANs or to access the Internet
Router
A router is a network device that can receive the data, analyse it and transmit it to other
networks.
A router connects a local area network to the internet.
Compared to a hub or a switch, a router has advanced capabilities as it can analyse the data
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 98 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
being carried over a network, decide/alter how it is packaged, and send it to another
network of a different type.
For example, data has been divided into packets of a certain size. Suppose these packets are
to be carried over a different type of network which cannot handle bigger packets. In such a
case, the data is to be repackaged as smaller packets and then sent over the network
by a router.
A router can be wired or wireless.
A wireless router can provide Wi-Fi access to smartphones and other devices.
Usually, such routers also contain some ports to provide wired Internet access. These days,
home Wi-Fi routers perform the dual task of a router and a modem / switch.
These routers connect to incoming broadband lines, from ISP (Internet Service Provider),
and convert them to digital data for computing devices to process
Gateway
As the term “Gateway” suggests, it is a key access point that acts as a “gate” between an
organisation's network and the outside world of the Internet.
Gateway serves as the entry and exit point of a network, as all data coming in or going out
of a network must first pass through the gateway in order to use routing paths.
Besides routing data packets, gateways also maintain information about the host network's
internal connection paths and the identified paths of other remote networks.
If a node from one network wants to communicate with a node of a foreign network, it will
pass the data packet to the gateway, which then routes it to the destination using the best
possible route
For simple Internet connectivity at homes, the gateway is usually the Internet Service
Provider that provides access to the entire Internet.
Generally, a router is configured to work as a gateway device in computer networks.
But a gateway can be implemented completely in software, hardware, or a combination of
both.
Because a network gateway is placed at the edge of a network, the firewall is usually
integrated with it
Switching Techniques
In a network having multiple devices, we are interested to know how to connect the sender
and receiver so that one-to-one communication is possible.
One solution is to make a dedicated connection between each pair of devices (mesh
topology) or between a central device and every other device (a star topology).
However, we know that such methods are costly in case of large networks.
An alternative to this is switching whereby data is routed through various nodes in a
network.
This switching process forms a temporary route for the data to be transmitted. Two
commonly used switching techniques are — Circuit Switching and Packet Switching.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 99 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Circuit Switching
In circuit switching, before a communication starts, a dedicated path is identified between
the sender and the receiver.
This path is a connected sequence of links between network nodes.
All packets follow the same path established during the connection.
In earlier days, when we placed a telephone call, the switching equipment within the
telephone system finds out a physical path or channel all the way from our telephone at
home to the receiver’s telephone.
This is an example of circuit switching.
Packet Switching
In packet switching, each information or message to be transmitted between sender and
receiver is broken down into smaller pieces, called packets.
These packets are then transmitted independently through the network. Different packets
of the same message may take different routes depending on availability.
Each packet has two parts — a header containing the address of the destination and other
information, and the main message part.
When all the packets reach the destination, they are reassembled and the complete message
is received by the receiver.
Unlike circuit switching, a channel is occupied in packet switching only during the
transmission of the packet.
On completion of the transmission, the channel is available for transfer of packets from
other communicating parties.
Tips to solve technical questions based on Networking Where Server should be placed:
Server should be placed in the building where the number of computers is maximum.
1. Suggest a suitable cable layout of connection: A suitable cable layout can be suggested
in the following two ways:
(a) On the basis of Server: First, the location of the Server is found out. Server should be placed
in that building where the number of computers is maximum (according to the 80:20 rule).
After finding the server position, each building distance is compared with the Server building
directly or indirectly (taking other building(s) in between). The shortest distance is counted,
whether it is directly or indirectly calculated.
(b) On the basis of distance from each building: The distance between each building is
compared to all other buildings, either directly or indirectly. The shortest distance is calculated,
whether it is direct or through some other building.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 100 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 101 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Q.No Questions
1 Fill in the Blank:
______________ is a communication methodology designed to deliver
both voice and multimedia communications over internet protocol
(a) SMTP (b) VoIP (c) HTTP (d) PPP
2 Which of the following is transmission medium for TV remotes?
(a) Infrared (b) Coaxial cable (c) Bluetooth (d)Microwave
3 Which of the following devices will connect both source and destination
computer.
(a) HUB (b) SWITCH (c) MODEM (d) ROUTER
4 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
5 Fill in the blank:
________ is the protocol used for transferring files from one machine to
another.
a) HTTP b) FTP c) SMTP d) VOIP
6 MAC address is of ___________
a) 24 bits b) 36 bits c) 42 bits d) 48 bits
7 TCP/IP stands for
a) Transmission Communication Protocol / Internet Protocol
b) Transmission Control Protocol / Internet Protocol
c) Transport Control Protocol / Interwork Protocol
d) Transport Control Protocol / Internet Protocol
8 ______is a standard network protocol used to transfer files from one host
to another host over a TCP- based network, such as the Internet.
a) TCP b) IP c) FTP d) SMTP
9 ___________ is a protocol that allows to send/upload email message from
local computer to an email server
10 Which of the following is /are email protocols?
(a) TCP (b) IP (c) SMTP (d) POP
11 A network device used to divide a single computer network into various
subnetworks .
i)router ii)switch iii)hub
12 Ms. Priya is an IT expert. She recently used her skills to access the Admin
password for the network server of Happiest Minds Technology Ltd. and
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 102 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 103 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 104 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Q.No Questions
Write the full form of the following:
1 ARPANET
2 WWW
3 PAN
4 LAN
5 MAN
6 WAN
7 WLAN
8 USB
9 WPAN
10 WI-FI
11 MBPS
12 HTTP
13 IETF
14 W3C
15 TCP
16 HTML
17 XML
18 FTP
19 PPP
20 ISP
21 SMTP
22 POP3
23 IMAP
24 IP
25 HTTPS
26 TELNET
27 VOIP
28 MODEM
29 NIC
30 MAC
31 RJ 45
32 OUI
33 URI
34 URL
35 DNS
36 UTP
37 STP
38 VPN
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 105 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 106 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Q.No Questions
1 MyPace University is setting up its academic blocks at Naya Raipur and is
planning to set up a network. The University has 3 academic blocks and
one Human Resource Center as shown in the diagram
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 107 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
i)Suggest the most suitable block to place the server with a suitable
reason.
ii) Suggest the cable layout for connections between the various blocks.
iii) Suggest the placement of following devices with justification:
(a) Switch/Hub (b) Repeater
iv)The organization is planning to link its front office situated in the city
in a hilly region where cable connection is not possible. Suggest an
economic way to connect with reasonably high speed.
v) Out of following which type of Network it is LAN,MAN,WAN .
3 Python University is setting up its academic blocks at Chennai and is
planning to set up a network. The University has 3 academic blocks and
one Human Resource Center as shown in the diagram below:
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 108 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
which are given below : The given building blocks are named as Green,
Blue and Red
i. Suggest the most suitable place (i.e., building) to house the server of this
organization. Also give a reason to justify your suggested location.
ii. Suggest the placement of the following devices with justification:
a. Repeater - b. Switch -.
iii. Suggest a cable layout of connections between the buildings inside the
campus.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 110 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
iv. The organization is planning to provide a high speed link with its head
office situated in Mumbai using a wired connection. Which of the
following cables will be most suitable for this job.
• Optical Fiber
• Co-axial Cable
• Ethernet Cable
v. While connecting the devices two modems are found to be defected.
What is the function of modem?
5 Uplifting Skills Hub India is a knowledge and skill community which has
an aim to uplift the standard of knowledge and skills in the society. It is
planning to setup its training centers in multiple towns and villages pan
India with its head offices in the nearest cities. They have created a model
of their network with a city, a town and 3 villages as follows. As a
network consultant, you have to suggest the best network related
solutions for their issues/ problems raised in (a) to (d) keeping in mind
the distances between various locations and other given parameters.
Shortest distances between various locations:
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 111 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Note:
In Villages, there are community centers, in which one room has been
given as training center to this organization to install computers. The
organization has got financial support from the government and top IT
companies.
(a) Suggest the most appropriate location of the SERVER in the B_HUB
(out of the 4 locations), to get the best and effective connectivity. Justify
your answer.
(b) Suggest the best wired medium and draw the cable layout (location to
location) to efficiently connect various locations within the B_HUB.
(c) Which hardware device will you suggest to connect all the computers
within each location of B_HUB?
(d) Which service/protocol will be most helpful to conduct live
interactions of Experts from Head Office and people at all locations of
B_HUB.
(e) Which type of network would be formed if B_HUB is connected to
their A_city.
6 University of Correspondence in Allahabad is setting up the network
between its different wings (units). There are four wings named as
Science(S), Journalism(J), Arts(A) and Home Science(H).
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 112 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
(a) Suggest the suitable topology and draw the cable layout to efficiently
connect various blocks / wings of network.
(b) Where should the server be housed ? justify your answer.
(c) What kind of network (LAN/MAN/WAN) will be formed?
(d) Suggest the fast and very effective wired communication medium to
connect another sub office at Kanpur, 670 km far apart from above
network.
(e) Suggest the placement of the following devices in the network.
i. Hub/ Switch
ii. Repeater
7 A professional consultancy company is planning to set up new offices in
India with its hub at Chennai. As a network adviser, you have to
understand their requirements and suggest to them the best available
solutions.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 113 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
(a) Suggest the most appropriate block where the organization should
plan to install their server?
(b) Draw a block-to-block cable layout to connect all the buildings in the
most appropriate manner for efficient communication.
(c) What will be the best possible connectivity out of the following to
connect the new set-up of offices in Chennai with its London base office?
(i) Infrared (ii) Satellite Link (iii) Ethernet Cable
(d) Which of the following devices will you suggest to connect each
computer in each of the above buildings?
(i) Gateway (ii) Switch (iii) Modem
(e ) Suggest a device/software to be installed for data security in the
campus. Firewall
8 Learn Together is an educational NGO. It is setting up its new campus at
Jabalpur for its web-based activities. The campus has four compounds as
shown in the diagram below:
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 114 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 115 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
(i) Suggest the type of network required (out of LAN, MAN, WAN) for
connecting each of the following office units.
Research Lab and Back Office
Research Lab and Development Unit.
(ii) Which one of the following device, will you suggest for connecting all
the computers with in each of their office units?
Switch/Hub
Modem
Telephone
(iii) (a) Which of the following communication medium will you suggest
to be procured by the company for connecting their local office units in
Pondicherry for very effective (high speed) communication?
Telephone cable
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 116 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Ethernet cable
Optical fibre
(iv) Which building is suitable to install the server with suitable reason?
Research Lab
(v) Suggest a cable/wiring layout for connecting the company’s local
office units located in Pondicherry. Also, suggest an effective
method/technology for connecting the company’s office unit located in
Mumbai.
10 Indian School, in Mumbai is starting up the network between its different
wings. There are four Buildings named as SENIOR, JUNIOR, ADMIN
and HOSTEL as shown below:
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 117 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
(i) Suggest the most appropriate location of the server inside the
CHENNAI campus (out of the 4 buildings), to get the best connectivity
for maximum no. of computers. Justify your answer.
(ii) Suggest the topology and draw the cable layout to efficiently connect
various buildings within the CHENNAI campus.
(iii) Which hardware device will you suggest to be procured by the
company to minimize the transmission loss?
(iv) Which will be the most suitable wireless communication medium to
connect Chennai campus with its Delhi head office?
(v) Which of the following will you suggest to establish the online face-
toface communication between the people in the Admin Office of
CHENNAI Campus and DELHI Head Office?
(a) Cable TV
(b) Email
(c) Video Conferencing
(d) Text Chat
12 Ionex Private Ltd. Patna has different divisions Marketing (A1), Sales
(A2), Finance (A3) and Production (A4). The company has another branch
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 118 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
in New Delhi. The management wants to connect all the divisions as well
as all the computers of each division (A1, A2, A3, A4) of Patna branch.
Distance between the divisions are as follows :
A3 to A1: 20 m
A1 to A2: 35 m
A2 to A4: 20 m
A4 to A3: 130 m
A3 to A2: 1000 m
A1 to A4: 190 m
The number of computers in each division is as follows :
A1: 50
A2: 40
A3: 110
A4: 60
Based on the above configurations, answer the following questions :
(i) Suggest the type of network (PAN, LAN, MAN, WAN) required to
connect the Finance (A3) division with the New Delhi branch by giving
suitable reasons.
(ii) Suggest the placement of following devices (a) Switch (b) Repeater
(iii) Suggest the division which should be made server by quoting
suitable reasons.
(iv) The company wants to conduct an online video conference between
employees of the Patna and New Delhi branches. Name the protocol
which will be used to send voice signals in this conference.
(v) Suggest the topology and draw the most suitable cable layout for
connecting all the divisions of the Patna branch.
13 G. R.K International Inc. is planning to connect its Bengaluru Office Setup
with its Head Office in Delhi. The Bengaluru Office G.R.K. International
Inc. is spread across an area of approx. 1 square kilometres consisting of 3
blocks. Human Resources, Academics and Administration. You as a
network expert have to suggest answers to the four queries (i) to (v)
raised by them.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 119 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
(i) Suggest the most suitable block in the Bengaluru Office Setup to host
the server. Give a suitable reason with your suggestion.
(ii) Suggest the cable layout among the various blocks within the
Bengaluru Office Setup for connecting the blocks.
(iii) Suggest a suitable networking device to be installed in each of the
blocks essentially required for connecting computers inside the blocks
with fast and efficient connectivity.
(iv) Suggest the most suitable media to provide secure, fast and reliable
data connectivity between Delhi Head Office and the Bengaluru Office
Setup.
(v)Which type of network id formed between blocks of Bengaluru Office.
14 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 three 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 (e) to
the authorities keeping in mind the distance and other given parameters.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 120 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
a. Suggest the authorities, the cable layout amongst various blocks inside
university campus for connecting the buildings
b. Suggest the most suitable place (i.e. block) to house the server of this
university with a suitable reason.
c. Suggest an efficient device from the following to be installed in each of
the blocks to connect all the computers
d. Suggest the placement of a Repeater (if any) in the network with
justification.
e. Suggest the most suitable (very high speed) service to provide data
connectivity between Admission Building located in Delhi and the
campus located in Parampur.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 121 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
File handling
A file is a named location on a secondary storage media where data are permanently stored for later
access.
TYPES OF FILES
Computers store every file as a collection of 0s and 1s i.e., in binary form
There are mainly two types of data files — text file and binary file.
A text file consists of human readable characters, which can be opened by any text editor.
A Binary files are made up of non-human readable characters and symbols, which require specific
programs to access its contents.
Text file
A text file can be understood as a sequence of characters consisting of alphabets, numbers and other
special symbols.
Files with extensions like .txt, .py, .csv, etc. are some examples of text files.
Each line of a text file is terminated by a special character, called the End of Line (EOL).
Contents in a text file are usually separated by whitespace, but comma (,) and tab (\t) are also
commonly used to separate values in a text file.
In real world applications, computer programs deal with data coming from different sources like
databases, CSV files, HTML, XML, JSON, etc. We broadly access files either to write or read data from
it. But operations on files include creating and opening a file, writing data in a file, traversing a file,
reading data from a file and so on. Python has the io module that contains different functions for
handling files.
Opening a file
To open a file in Python, we use the open() function. The syntax of open() is as follows:
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 122 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Closing a file
Once we are done with the read/write operations on a file, it is a good practice to close the file. Python
provides a close() method to do so. While closing a file, the system frees the memory allocated to it.
file_object.close()
Opening a file using with clause
The advantage of using with clause is that any file that is opened using this clause is closed
automatically
Modes Description
r Opens a file for reading only. The file pointer is placed at the beginning
of the file. This is the default mode
rb Opens a file for reading only in binary format. The file pointer is placed
at the beginning of the file. This is the default mode
r+ Opens a file for both reading and writing. The file pointer is placed at
the beginning of the file
rb+ Opens a file for both reading and writing in binary format. The file
pointer is placed at the beginning of the file
w Opens a file for writing only. Overwrites the file if the file exists. If the
file does not exist, creates a new file for writing
wb Opens a file for writing only in binary format. Overwrites the file if the
file exists. If the file does not exist, creates a new file for writing
w+ Opens a file for both writing and reading. Overwrites the existing file if
the file exists. If the file does not exist, creates a new file for reading and
writing
wb+ Opens a file for both writing and reading in binary format. Overwrites
the existing file if the file exists. If the file does not exist, creates a new
file for reading and writing
a Opens a file for appending. The file pointer is at the end of the file if the
file exists. That is, the file is in the append mode. If the file does not
exist, it creates a new file for writing
ab Opens a file for appending in binary format. The file pointer is at the
end of the file if the file exists. That is, the file is in the append mode. If
the file does not exist, it creates a new file for writing
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 123 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
a+ Opens a file for both appending and reading. The file pointer is at the
end of the file if the file exists. The file opens in the append mode. If the
file does not exist, it creates a new file for reading and writing
ab+ Opens a file for both appending and reading in binary format. The file
pointer is at the end of the file if the file exists. The file opens in the
append mode. If the file does not exist, it creates a new file for reading
and writing.
file_object.read(n)
To read the entire file line by line using the readline(), we can use a loop.
This process is known as looping/ iterating over a file object.
It returns an empty string when EOF is reached.
For writing to a file, we first need to open it in write or append mode. If we open an existing file in
write mode, the previous data will be erased, and the file object will
be positioned at the beginning of the file. On the other hand, in append mode, new data will be added
at the end of the previous data as the file object is at the end of the file. After opening the file, we can
use the following methods to write data in the file.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 124 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
write() method takes a string as an argument and writes it to the text file. It returns the number of
characters being written on single execution of the write() method.
Also, we need to add a newline character (\n) at the end of every sentence to mark the end of line.
fileObject.write(string)
to write multiple strings to a file. We need to pass an iterable object like lists, tuple, etc.
containing strings to the writelines() method.
The functions that we have learnt till now are used to access the data sequentially from a file.
But if we want to access data in a random fashion, then Python gives us seek() and tell() functions to do
so
File_object.tell()
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 125 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
offset is the number of bytes by which the file object is to be moved. reference_point
indicates the starting position of the file object
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 126 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
first.close()
lines()
#To read the contents of a file and display the Coming
word charcater is more than 5 Kovilpatti
def bigwords(): studying
first = open("mydetails.txt") school
big = first.readlines() roaming
count = 0 streets
for lines in big: Count of Big Words are: 6
check = lines.split()
for word in check:
if len(word) > 5:
print(word)
count = count + 1
print("Count of Big Words are: ",count)
first.close()
bigwords()
#To read the contents of a file and display the My
word charcater is less than 5 name
def shortwords(): is
first = open("mydetails.txt") Ramu
short = first.readlines() I
count = 0 am
for lines in short: from
check = lines.split() i
for word in check: am
if len(word) < 5: in
print(word) 11
count = count + 1 at
print("Count ofSshort Words are: ",count) CBSE
first.close() my
shortwords() is
in
the
Count of Sshort Words are: 17
#To read the contents of a file and display the i am studying in class 11 at CBSE school
line whose charcaters are more than 20 my hobby is roaming in the streets
def morechar():
first = open("mydetails.txt")
char = first.readlines()
for line in char:
if len(line) > 30:
print(line,end='')
first.close()
morechar()
#To Count and display the specific characters Count of Letter E or e in a File is: 5
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 127 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 128 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
#To read the contents of a file and replace the My name at RAMU
specific word I am Coming from KOVILPATTI
def replace(): i am studying in CLASS 11 at CBSE school
first = open("mydetails.txt") my hobby at ROAMING in the streets
text = first.read()
print(text.replace('is','at'))
first.close()
replace()
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 129 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
6
7
6
9
7 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 sun will slowly rise
and the moon will follow too.
The content of “output.txt” should be:
tfihs llits lliw setalp ehT
.weps llits lliw sduolc eht dna
esir ylwols lliw nus ehT
.oot wollof lliw noom eht dna
8 Write a function countmy( ) in python to read the text file “DATA.TXT”
and count the number of times “my” occurs in the file.
For example if the file “DATA.TXT” contains:
“This is my website. I have displayed my preferences in the CHOICE
section”
The countmy( ) function should display the output as : “my occurs 2 times”
9 Write a method/function DISPLAYWORDS() in python to read lines
from a text file STORY.TXT,and display those words, which are less than 4
Characters.
10 Write a method/function BIGWORDS() in Python to read contents from a text
file CODE.TXT, to count and display the occurrence of those words, which
are having 7 or more alphabets.
For example :
If the content of the file is
ME AND MY FRIENDS
ENSURE SAFETY AND SECURITY OF EVERYONE
The output of the function should be: 3
Solution :
11 Write a function in Python to read from a text file “INDIA.TXT”, to find and
display those words of file which have 3 characters. For example, If the
“INDIA.TXT” contents are as follows:
“India is the fastest growing economy.
India is looking for more investments around the globe.”
The output of the function should be: the for the
12 Write a function in python to count the number of lowercase and uppercase
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 131 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 132 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
CSV Files
1. writer( )
2. reader( )
Both the methods return an Object of writer or reader class. Writer Object again have two methods
1. writerow( )
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 133 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
2. writerows( )
reader( ) Methods
This function returns a reader object which will be used to iterate over lines of a given CSV file.
r_obj = csv.reader(csvfile_obj)
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 134 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Write a Program to add / Insert records in a file ‘insert.csv”. Structure of a record is roll_number,
name and class.
Program Code Output
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 135 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 136 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
else:
d1.writerow(i)
f.close()
f1.close()
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 137 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
7 Write a program in Python that defines and calls the following user defined
functions:
i. Add(): to add the record of a student to a csv file “record.csv”. Each record
should be with field elements [admno,sname,class]
ii. Count(): to count the number of students studying in class 12
8 Write a program in Python that defines and calls the following user defined
functions:
i. Add(): to add the record of an animal to a csv file “animal.csv”. Each record
should be with field elements [animalname, animaltype, animalfood]
ii. Search(): to print all the animal names who eat grass as their food
9 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
customername, mobileno, dateofPurchase, itempurchased.
(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.
10 Rohan is making a software on “Countries & their Capitals” in which various
records are to be stored/retrieved in CAPITAL.CSV data file. It consists some
records(Country & Capital). Help him to define and call the following user
defined functions:
(i) AddNewRec(Country,Capital) – To accept and add the records to a CSV
file “CAPITAL.CSV”. Each record consists of a list with field elements as
Country and Capital to store country name and capital name respectively.
(ii) ShowRec() – To display all the records present in the CSV file named
„CAPITAL.CSV‟
11 Write a Program in Python that defines and calls the following user defined
functions:
(i) ADDPROD() – To accept and add data of a product to a CSV file
‗product.csv‘. Each record consists of a list with field elements as prodid,
name and price to store product id, employee name and product price
respectively.
(ii) COUNTPROD() – To count the number of records present in the CSV file
named ‗product.csv‘.
12 Write a Program in Python that defines and calls the following user defined
functions:
(i) add() – To accept and add data of a to a CSV file ‗stud.csv‘. Each record
consists of a list with field elements as admno, sname and per to store
admission number, student name and percentage marks respectively.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 139 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
(ii) search()- To display the records of the students whose percentage is more
than 75.
13 Write a Program in Python that defines and calls the following user
definedfunctions:
(i) ADD() – To accept and add data of an item to a csv file „events.csv‟. Each
record of the file is a list [Event_id, Description, Venue, Guests, Cost].
Event_Id, Description, and venue are of str type, Guests and Cost are of int
type.
(ii) COUNTR() – To read the data from the file events.csv, calculate and
display the average number of guests and average cost.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 140 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Binary File
A binary file contains arbitrary binary data i.e. numbers stored in the file, can be used for
numerical operation(s).
Binary Files are used to store binary data such as image, video, audio, text There is no delimiter
Binary files are difficult to understand
Binary files are having .dat extension
The key function for working with files in Python is the open() function
The open() function takes two parameters; filename, and mode
There are different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist "a" - Append -
Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
In addition you can specify if the file should be handled as binary or text mode
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)
Use the python module pickle for structured data such as list or directory to a file.
PICKLING refers to the process of converting the structure to a byte stream before writing to a file.
while reading the contents of the file, a reverse process called UNPICKLING is used to convert
the byte stream back to the original structure.
Use pickle.dump() method to write the object in file which is opened in binary access mode.
Syntax of dump method is:
dump(object,fileobject)
Example: A program to write list sequence in a binary file using pickle.dump() method
import pickle
def bin_create():
list1 = [40,50,60,70,80,90]
f = open("list.dat","wb")
pickle.dump(list1,f)
print("Information added to Binary File")
f.close()
bin_create()
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 141 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Output:
Information added to Binary File
def bin_create():
list1 = [40,50,60,70,80,90]
f = open("list.dat","wb")
pickle.dump(list1,f)
print("Information added to Binary File")
f.close()
bin_create()
def bin_read():
f = open("list.dat","rb")
list1 = pickle.load(f)
print("The Content of Binary File is: ",list1)
f.close()
bin_read()
Output
Information added to Binary File
The Content of Binary File is: [40, 50, 60, 70, 80, 90]
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 142 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 143 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 144 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 145 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 146 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 147 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 148 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Keys
Keys play an important role in the relational database.
It is used to uniquely identify any record or row of data from the table. It is also used to
establish and identify relationships between tables.
Types of keys:
Primary key
It is the first key used to identify one and only one instance of an entity uniquely.
Candidate key
A candidate key is an attribute or set of attributes that can uniquely identify a tuple.
Except for the primary key, the remaining attributes are considered a candidate key. The
candidate keys are as strong as the primary key.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 149 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Super Key
Super key is an attribute set that can uniquely identify a tuple.
A super key is a superset of a candidate key.
Foreign key
Foreign keys are the column of the table used to point to the primary key of another
table.
Alternate key
There may be one or more attributes or a combination of attributes that uniquely
identify each tuple in a relation. These attributes or combinations of the attributes are
called the candidate keys. One key is chosen as the primary key from these candidate
keys, and the remaining candidate key, if it exists, is termed the alternate key.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 150 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Composite key
Whenever a primary key consists of more than one attribute, it is known as a composite
key. This key is also known as Concatenated Key.
Artificial key
The key created using arbitrarily assigned data are known as artificial keys. These keys
are created when a primary key is large and complex and has no relationship with many
other relations. The data values of the artificial keys are usually numbered in a serial
order
ATTRIBUTE - the columns of a relation are the attributes which are also referred as fields
TUPLE - Each row of data in a relation (table) is called a tuple.
DEGREE - The number of attributes(column) in a relation is called the Degree of the relation
CARDINALITY - The number of tuples(row) in a relation is called the Cardinality
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 151 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Constraints Description
NOT NULL Ensures that a column cannot have NULL values where NULL means
missing/unknown/not applicable value.
UNIQUE Ensures that all the values in a column are distinct/unique
DEFAULT A default value specified for the column if no value is provided
PRIMARY KEY The column which can uniquely identify each row/record in a table.
FOREIGN KEY The column which refers to value of an attribute defined as primary key in
another table
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 152 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
10 SELECT field1, field2…. FROM SELECT stno, stname, dob FROM student;
<table name>;
11 SELECT field1, field2…. FROM SELECT stno, stname, dob FROM student
<table name> WHERE WHERE feespaid > 15000;
<condition(s)>;
12 SELECT field1, field2…. FROM SELECT stno, stname, dob FROM student
<table name> ORDER BY <field ORDER BY stname DESC;
name> ASCENDING /
DESCENDING;
13 SELECT field1, field2…. FROM SELECT stno, stname, dob FROM student
<table name> WHERE field WHERE feespaid BETWEEN 10000 AND 25000;
name BETWEEN <lower limit>
and <upper limit>;
14 SELECT field1, field2…. FROM SELECT stno, stname, dob FROM student
<table name> WHERE <field WHERE stname LIKE ‘___M__%’;;
name> like <pattern matching>;
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 153 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
18 SELECT <column names> SELECT eno, ename FROM emp WHERE grade
FROM <table name> WHERE IN (‘E3’,’E5’);
<column name> IN <list of
values>;
19 SELECT <column name> FROM SELECT eno, ename FROM emp WHERE grade
<table name> WHERE IS NULL;
<condition-name> is NULL;
20 SELECT DISTINCT <column SELECT DISTINCT grade FROM emp;
name> FROM <table name>
WHERE <condition if any>;
21 ALTER TABLE <table- ALTER TABLE emp ADD (tel_no long int(10));
name>ADD <column name>
<datatype> (data size) ;
22 ALTER TABLE <table- ALTER TABLE emp MODIFY (ename
name>MODIFY <column name> VARCHAR(30));
<datatype> (data size) ;
23 ALTER TABLE <table- ALTER TABLE emp CHANGE ename empname
name>CHANGE <old-column VARCHAR(30);
name> <new-column name>
<data type> (data-size);
24 ALTER TABLE <table-name> ALTER TABLE emp DROP COLUMN tel_no;
DROP COLUMN <column-
name);
25 AGGREGATE FUNCTIONS : SELECT SUM(fees) FROM student;
SUM() - SELECT SUM(column-
name) FROM <table_name>
WHERE <condition>;
26 AVG() - SELECT AVG(column- SELECT AVG(fees) FROM student;
name) FROM <table_name>
WHERE <condition>;
27 MAX() - SELECT MAX(column- SELECT MAX(fees) FROM student;
name) FROM <table_name>
WHERE <condition>;
28 MIN() - SELECT MIN(column- SELECT MIN(fees) FROM student;
name) FROM <table_name>
WHERE <condition>;
29 COUNT() - SELECT SELECT COUNT(fees) FROM student;
COUNT(column-name) FROM
<table_name> WHERE
<condition>;
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 154 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
SQL JOIN
As the name shows, JOIN means to combine something. In case of SQL, JOIN means "to
combine two or more tables".
In SQL, JOIN clause is used to combine the records from two or more tables in a database.
INNER JOIN
In SQL, INNER JOIN selects records that have matching values in both tables as long as the
condition is satisfied. It returns the combination of all rows from both the tables where the
condition satisfies.
Syntax
Example
LEFT JOIN
The SQL left join returns all the values from left table and the matching values from the right
table. If there is no matching join value, it will return NULL.
Syntax
Example
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 155 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
RIGHT JOIN
In SQL, RIGHT JOIN returns all the values from the values from the rows of right table and the
matched values from the left table. If there is no matching in both tables, it will return NULL.
Syntax
Example
FULL JOIN
In SQL, FULL JOIN is the result of a combination of both left and right outer join. Join tables
have all the records from both tables. It puts NULL on the place of matches not found.
Syntax
Example
Database connectivity
Database connectivity refers to connection and communication between an application
and a database system.
The term “front-end” refers to the user interface, while “back-end” means the server,
application and database that work behind the scenes to deliver information to the user.
Mysql.connector- Library or package to connect from python to MySQL.
Before we connect the program with mysql , we need to install connectivity package named
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 156 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
mysql-connector- python
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 157 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Q.No Questions
1 Which of the following will remove the primary key from MySQL table.
(a) remove (b) alter (c) drop (d) update
2 Which of the following is not an integrity constraint?
(a) Not null (b) Composite key (c) Primary key (d) Check
3 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
4 In the relational model, relationships among relations/table are created by
using _______ keys.
(a) composite (b) alternate (c) candidate (d) foreign
5 Which of the following is a DML command?
(a) SELECT (b) ALTER (c) CREATE (d) DROP
6 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
7 Fill in the blanks:
ALTER command is used to add a new column in the table in SQL
8 Which of the following will display all the tables in a database:
a) SELECT * FROM <tablename>;
b) DISPLAY TABLES;
c) SHOW TABLES;
d) USE TABLES;
9 Choose the correct option:
__________ is the number of columns in a table and ________ is the
number of rows in the table.
a) Cardinality, Degree b) Degree, Cardinality
c) Domain, Range d) Attribute, Tuple
10 The ORDER BY clause is used to display result of an SQL query in
ascending or descending order with respect to specified attribute values
11 Which function is used to display the sum of values in a specified
column ?
a) COUNT(column) b) TOTAL(column)
c) SUM(column) d) ADD(column)
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 158 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 159 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 160 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 161 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 162 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 163 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 164 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
condition.
select id,name,salary*1.1 where instructor=10005;
(a) where, having (b) select, from (c) where, from (d) where,select
88 Consider the following SQL statement. What type of statement is this?
insert into instructor values(10211,'Amit','Science',6600);
(a) DDL (b) DML (c) DCL (d) TCL
89 A database______ is a special control structure that facilitates the row by
row processing of records in the result set.
(a) fetch (b) table (c) cursor (d) query
90 Which of the following attributes cannot be considered as a choice for
primary key?
(a) id (b) License number (c)Street no (d) dept_id
91 Which of the following commands will remove the entire database from
MYSQL?
(A) DELETE DATABASE (B) DROP DATABASE
(C) REMOVE DATABASE (D) ALTER DATABASE
92 Which of the following statements is True?
a) There can be only one Foreign Key in a table.
b) There can be only one Unique key is a table
c) There can be only one Primary Key in a Table
d) A table must have a Primary Key
93 _____________ Keyword is used to obtain unique values in a SELECT
query
a) UNIQUE b) DISTINCT c) SET d) HAVING
94 Which of the following is a valid sql statement?
a) ALTER TABLE student SET rollno INT(5);
b) UPDATE TABLE student MODIFY age = age + 10;
c) DROP FROM TABLE student;
d) DELETE FROM student;
95 Which of the following commands will delete the rows of table?
(a) DELETE command (b) DROP Command
(c) REMOVE Command (d) ALTER Command
96 Logical Operators used in SQL are?
(a) AND,OR,NOT (b) &&,||,! (c) $,|,! (d) None of these
97 ___________ command is used to ADD a column in a table in SQL.
(a) update (b)remove (c) alter (d)drop
98 An alternate key is a ___________ , which is not the primary key of the
table.
a) Primary Key b) Foreign Key c) Candidate Key d) Alternate Key
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 165 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 166 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Q.No Questions
1
2 Write the output for SQL queries (i) to (iv), which are based on the table:
STUDENT given below:
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 167 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
4 Write the output of the queries (i) to (iv) based on the tablegiven below:
5 As part of Fit India Campaign, Suresh has started a juice shop that serves
healthy juices. As his database administrator, answer the following
questions based on the data given in the table below.
(i) Identify the most appropriate column, which can be considered as
Primary key.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 168 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
(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 below table?
(iii) Write the statements to:
a. Insert the following record into the table
DrinkCode – 107, Dname – Santara Special, Price – 25.00, Calorie – 130
b. Increase the price of the juices by 3% whose name begins with ‘A’.
OR (Option for part iii only)
(iii) Write the statements to:
a.Delete the record of those juices having calories more than 140.
b. Add a column Vitamins in the table with datatype as varchar with 20
characters.
6 Write the queries of the i to iv based on the table: Shop given below
i) To display the details of all the item in ascending order of item names
ii)To display item name and price of all those items whose price in range
of 10000 to 30000
iii) To display max and min price of the table
iv)To display the total amount of digiclick company
7 Write the output of the queries (a) to (d) based on the table BOOK,given
below:
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 169 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
8 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”.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 170 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 171 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
11
12 Write SQL commands for(a) to (b) and write the outputs for (C) on the
basis of table GRADUATE
a) List the names of those students who obtained DIV 1 sorted by NAME .
b )Display a report, listing NAME , STIPEND , SUBJCT and amount of
stipend received in a year assuming that the STIPEND is paid every
month.
C.) Give the output of the following SQL statements based on table
GRADUATE :
13 Advaith,a manager has stored the details of departments in a table called
DEPARTMENT.
He wants to add one more record to this table and has written the
following code and unable to insert that record.
INSERT INTO DEPARTMENT VALUES(43,”HRD”);
i. Help him to correct the code for adding the record
ii. How can he restrict Null values in the table
iii. Write a commands to :
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 172 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
14 Write the output of the queries (I) to (iv) based on the table, given below:
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 173 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
17 Write the output of the SQL queries (i) to (iv) based on the table:
(i) Select sum(Salary) from staff where Gender = ‘F’ and Dept = ‘Sales’;
(ii) Select Max(DOB), Min(DOB) from staff;
(iii) Select Gender, Count(*) from staff group by Gender;
(iv) Select Name from staff where salary>25000;
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 174 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
18 ABC Gym has created a table TRAINER. Observe the table given below
and answer the following questions accordingly
a. What is Degree and Cardinality of the above table?
b. Which field should be made as the primary key? Justify your answer.
c. Write the query to:
i. Insert a record: (107,Bhoomi,Delhi,2001-12-15,90000)
ii. Increase the salary by 1% for the trainers whose salary is more than
80000
OR
i. Delete the record of Richa
ii. Add a new column remarks of VARCHAR type with 50 characters.
19 Write the output of the queries (i) to (iv) based on the table “Product”,
showing details of
products being sold in a grocery shop.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 175 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 176 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
a) Karan wants to remove all the data from table WORKER from the
database department. Write the command to delete above said
information.
b) Identify the attribute best suitable to be declared as a primary key.
c) (i) Karan wants to increase the size of the FIRST_NAME column from
10 to 20 characters. Write an appropriate query to change the size.
(ii) Write a query to display the structure of the table Worker, i.e. name of
the attribute and their respective data types
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 177 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 178 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 179 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 180 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Q.N Questions
o
1 Write SQL statements for the q.no (i) to (iv) and output for (v)
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 181 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
(i) Write any one point of difference between Equi join and Natural
join.
(ii) Find output:
(a) select *from product p, supplier s where p.supid=s.supid;
(b) select *from product natural join supplier;
OR
(i) Write a Query to insert House_Name=Tulip, House_Captain=
Rajesh and House_Point=278 into table House(House_Name,
House_Captain, House_Points)
3 Consider the following DEPT and WORKER tables. Write SQL queries
for the following
(i) To display Wno, Name, Gender from the table WORKER in
descending order of Wno.
(ii) To display the Name of all the FEMALE workers from the table
WORKER
(iii) Write statements
a) To display the Wno and Name of those workers from the table
WORKER who are born between '1987-01-01' and '1991-12-01'.
b) To count and display MALE workers who have joined after '1986-
01- 01".
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 182 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 184 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 185 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 186 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 187 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
(i)to display name and price of all the accessories in descending order
of their price.
(ii)to display id and sname of all shoppe located in nehru place.
(iii)to display minimum and maximum price of each name of
accessories.
(iv) to display name, price of all accessories and their respective sname
where they are available.
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 188 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
Q.No Questions
1 The code given below inserts the following record in the table Student:
Empno – integer
EName – string
Designation – integer
Salary – integer
Bonus - Integer
Note the following to establish connectivity between Python and MYSQL:
Username is root
Password is tiger
The table exists in a MYSQL database named Employee.
The details (Empno, EName, Designation, Salary and Bonus) are to be
accepted from the user.
2 The code given below inserts the following record in the table Student:
RollNo – integer
Name – string
Class– integer
Marks – integer
Note the following to establish connectivity between Python and MYSQL:
Username is root,Password is tiger The table exists in a MYSQL database
named school.The details (RollNo, Name, Clas and Marks) are tobe
accepted from the user
3 The code given below inserts the following record in the table Student:
Rollno - integer
Name - string
Age - integer
Note the following to establish connectivity between Python and
MYSQL:
• Usemame is root
• Password is sys
• The table exists in a MYSQL data base named school.
• The details(Roll no, Name and Age) are to be accepted from the user
4 The code given below inserts the following record in the table
Book:
B_No – integer
B_Name – string
B_Author – string
Price – Decimal
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 189 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL
b. Password is stock
12 The code given below reads the following record from the table named
student and displays only those records who have marks greater than 75:
RollNo – integer
Name – string
Clas – integer
Marks – integer
Note the following to establish connectivity between Python and MYSQL:
Username is root
Password is tiger
13 The code given below reads the following record from Table named
Employee and display
those record salary >= 30000 and <= 90000:
Empno – integer
EName – string
Desig – integer
Salary – integer
Note the following to establish connectivity between Python and MYSQL:
Username is root
Password is Password
The table exists in a MYSQL database named Bank
Prepared By Faculty Members, Dept Of Computer Science, Vel’S Vidhyalaya Kovilpatti Page 192 of 192
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Q.No Questions
1 What will be the output of the following Python code snippet?
X=11
If X<=10:
X+=10
if X<=20 :
X+=10
If X<=30:
X+=30
a.21 b. 31 c.61 d. None of these
Answer
d. None of these
2 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
Answer
(c) infinite loop
3 Predict the Output:
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)
Answer:
[2, 4, 6, 8]
4 Give output
RS=’’
S=”important”
for i in S:
RS=i+RS
print(RS)
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 1 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Answer
tnatropmi
5 Find and write the output of the following Python code:
data=["P",20,"R",10,"S",30]
times=0
alpha=" "
add=0
for c in range(1,6,2):
times = times + c
alpha = alpha + data [c-1] + "$"
add = add + data[c]
print (times, add, alpha)
Answer
1 20 P$
4 30 P$R$
9 60 P$R$S$
6 Predict the output of the following Python code:
tup1 = ("George","Anderson","Mike","Luke","Amanda")
list1 =list(tup1)
list2 = []
for i in list1:
if i[-1]=="e":
list2.append(i)
tup2 = tuple(list2)
print(tup2)
Answer
('George', 'Mike', 'Luke')
7 Predict the output of the code given below:
s = 'mAhAtMaGaNdHi'
i=0
while i<len(s):
if (s[i].islower()):
print(s[i].upper(),end=' ')
if (s[i].isupper()):
print(s[i].lower(),end=' ')
i += 1
Answer:
MaHaTmAgAnDhI
8 Write the output of the following python code:
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 2 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Numbers =[9,18,27,36]
for num in Numbers:
for N in range(1,num%8):
print(N,"$",end="")
print()
Answer
1 $1 $2 $1 $2 $3 $
9 Predict the output of the code given below:
str1=input ("Enter a string: ")
str2="aAeEiIoOuU"
v,c=0,0
for i in str1:
if i in str2:
v+=1
else:
c+=1
Answer
No Solution
10 Predict the output of the Python code given below:
l=[]
for i in range(4):
l.append(2*i+1)
print(l[::-1])
Answer
[7, 5, 3, 1]
11 Predict the Output
str = 'LION king'
m=""
for i in range(0,len(str)):
if(str[i].isupper()):
m=m+str[i]+'*'
elif str[i].islower():
m=m+'@'
elif str[i]==' ' :
m=m+'#'
print(m)
Answer
L*I*O*N*#@@@@
12 Write the output for the following python snippet.
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 3 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
LST=[1,2,3,4,5,6]
for i in range(6):
LST[i-1]=LST[i]
print(LST)
Answer:
[2, 3, 4, 5, 1, 1]
13 Predict the Output
Text="Good go Head"
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)
Answer:
ggOO OOhhAA
14 Find the output generated by the following code:
a=5
b=10
a+=a+b
b*=a+b
print(a,b)
Answer
20 300
15 Find and write the output of the following Python code:
s = 'school2@com'
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)
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 4 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Answer
SCHOOLbbbbCOM
16 Predict the Output
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)
Answer
23
17 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)
Answer
1
2
3
3
sum= 9
18 Find and write the output of the following Python code:
str1 = 'Pre-Board Exam@2023'
str2=""
for i in range(0,len(str1)-1):
if(str1[i].islower()):
str2=str2+str1[i].upper()
elif str1[i].isupper():
str2=str2+str1[i].lower()
elif str1[i].isdigit():
str2=str2+'d'
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 5 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
else:
str2=str2+(str1[1-i])
print(str2)
Answer
pRE2bOARDxeXAMaddd
19 Predict the output of below given Python code
s="Abc2@xYz"
m=""
for i in range(len(s)):
if s[i].isupper():
m+=s[i].lower()
elif s[i].islower():
m+=s[i].upper()
elif s[i].isdigit():
m+=s[i-1]
else:
m = m +'#'
print(m)
Answer
aBCc#XyZ
20 Predict the Output
TXT = ["20","50","30","40"]
CNT = 3
TOTAL = 0
for C in [7,5,4,6]:
T = TXT[CNT]
TOTAL = float(T) + C
print(TOTAL)
CNT -= 1
Answer
47.0
35.0
54.0
26.0
21 Find the output of the following code:
Name = "cBsE@2051"
R=" "
for x in range (len(Name)):
if Name[x].isupper ( ):
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 6 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
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®
Answer
CbSe#@205
22 Predict the Output
s = 'school@college'
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)
Answer
SCHOOLbbCOLLEGE
23 Write the output of following python code
T="Happy New Year 2023"
L=len(T)
ntext=""
for i in range (0,L):
if T[i].isupper():
ntext=ntext+T[i].lower()
elif T[i].isalpha():
ntext=ntext+T[i].upper()
else:
ntext=ntext+"*"
print (ntext)
Answer
hAPPY*nEW*yEAR*****
24 Write the output of following python code
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 7 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
s = "Cricket"
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)
Answer
cCICKEe
25 Predict the Output
Msg1="WeLcOME"
Msg2="GUeSTs"
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)
Answer
G*L*TME
26 Predict the Output
str = '[email protected]'
m=""
for i in range(0,len(str)):
if(str[i].isupper()):
m=m+str[i].lower()
elif str[i].islower():
m=m+str[i].upper()
else:
if i%2==0:
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 8 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
m=m+str[i-1]
else:
m=m+"#"
print(m)
Answer
fUN#pYTHONn#.
27 Predict the Output
S = "Python 3.9"
k=len(S)
m=''
for i in range(0,k):
if S[i].isalpha( ):
m=m+S[i].upper( )
elif S[i].isdigit( ):
m=m+'0'
else:
m=m+'#'
print(m)
Answer
PYTHON#0#0
28 T1 = (12, 22, 33, 55 ,66)
list1 =list(T1)
new_list = []
for i in list1:
if i%3==0:
new_list.append(i)
new_T = tuple(new_list)
print(new_T)
Answer
(12, 33, 66)
29 s = 'KVS@Jammu'
k=len(s)
m=""
for i in range(0,k):
if(s[i].isupper()):
m=m+str(i)
elif s[i].islower():
m=m+s[i].upper()
else:
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 9 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
m=m+'*'
print(m)
Answer
012*4AMMU
30 s ="Back2Basic"
n = len(s)
NS =""
for i in range(0, n):
if (s[i] in 'aeiou'):
NS = NS + s[i].upper()
elif (s[i] >= 'a' and s[i] <= 'z'):
NS = NS +s[i].lower()
else:
NS = NS + '#'
print(NS)
Answer
#Ack##AsIc
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 10 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Q.No Questions
What will be the following expression be evaluated to in Python?
1 print(round(100.0 / 4 + (3 + 2.55),1))
a) 30.0 b) 30.55 c) 30.6 d) 31
Evaluate the following expression
2 Not 20>21 and 6>5 or 7>9
(a) True (b) False (c) 3 (d) None of these
What will the following Python statement evaluate to?
3 print (5 + 3 ** 2 / 2)
(a) 32 (b) 8.0 (c) 9.5 (d) 32.0
Consider the following expression:
not True and False or not False
4
Which of the following will be the output:
a) True b) False c) None d) NULL
How will the following expression be evaluated in Python?
5 2 + 9 * ( ( 3 * 12) – 8 ) / 10
a) 29.2 b) 25.2 c) 27.2 d) 27
Which statement will give the output as : True from the following :
a) >>>not -5
6 b) >>>not 5
c) >>>not 0
d) >>>not(5-1)
Consider the given expression:
True and False or Not True
7 Which of the following will be correct output if the given expression is
evaluated?
(a) True (b) False (c) NONE (d) NULL
What will the following expression be evaluated to in Python?
8 2**3**2+15//3
a) 69 b) 517 c) 175 d) 65
Evaluate the following expression:
9
False and bool(15/5*10/2+1) ANS: False
State true or false:
10 (i) -88.0 is the output of the print(3-10**2+99/11) ANS: True
(ii) Range( ) is also a module function ANS: False
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 11 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Evaluate the following expressions:
a) 6+7*4+2**3//5-8 ANS: 27
11
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 12 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
not False or False and True
Which of the following will be correct output if the given expression is
evaluated?
(a) True b)False c)NONE d) NULL
What will the following expression be evaluated to in Python?
24 print(75.0 / 4 + (2** 3))
(a) 20.5 (b)20.05 (c) 18.25 (d) 17.75 ANS : 26.75 (Not in option)
Consider the given expression:
not True and False or True
25 Which of the following will be correct output if the given expression is
evaluated?
(a) True (b) False (c) None (d) NULL
What will the following expression be evaluated to in python?
26 print(15.0/4+(8*3.0))
(a) 14.5 (b) 14.0 (c) 27.7 (d) 15.5
What will the following expression be evaluated to in python?
27 print(15.0/4+(8+3.0))
(a) 14.5 (b) 14.0 (c) 15 (d) 15.5 ANS : 14.75
Evaluate the following expressions:
28 (a) 5 // 10 * 9 % 3 ** 8 + 8 – 4 ANS : 4
(b) 65 > 55 or not 8 < 5 and 0 != 55 ANS : True
Evaluate the following expression and identify the correct answer:
29 16 – (4 + 2) * 5 + 2**3 * 4
a) 54 b) 46 c) 18 d) 32
Consider the following expression
5+2**6<9+2-16//8
30 Which of the following will be correct output if the given expression is
evaluated?
(a) 127 (b) False (c) True (d) Invalid expression
What will be the following expression be evaluated to in Python?
31 print(5*2-5//9+2.0+bool(100))
(a) 11.0 (b) 13.0 (c) 112.0 (d) 100
State whether True or False:
32
The expression 2**2**3 is evaluated as (2**2)**3 ANS : False
Evaluate the following expression and identify the correct answer.
33 16 - (4 + 2) * 5 + 2**3 * 4
a. 54 b. 46 c. 18 d. 32
34 Evaluate the following expressions:
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 13 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
10 > 5 and 7 > 12 or not 18 > 3
a) True b) False C) 25 D) 0
State True or False
35 The value of the expression 5/(6*(4-2)) and 5/6*(4-2) is the same ANS :
True
Consider the given expression:
print(2**5+8//3*7-2)
36 Which of the following will be correct output if the given expression
evaluated?
(a) 44 (b) 34 (c) 42 (d) 36
Write the output after evaluating he following expressions:
a) k= 7 + 3 **2 * 5 // 8 – 3
37 print(k) ANS : 9
b) m= (8>9 and 12>3 or not 6>8)
print(m) ANS : True
38 What will be the output of: print (10>20)? ANS : False
Consider the given expression:
not ((True and False) or True)
39 Which of the following will be correct output if the given expression is
evaluated?
(A) True (B) False (C) NONE (D) NULL
print(True or not True and False)
Choose one option from the following that will be the correct output after
40
executing the above python expression.
a) False b) True c) or d) not
What will be the output of the following python expression?
41 print(2**3**2)
a) 64 b) 256 c) 512 d) 32
42 What will be the value of the expression :14+13%15 ANS : 27
What will be the output of the following expression?
43 24//6%3 , 24//4//2 , 48//3//4
a)(1,3,4) b)(0,3,4) c)(1,12,Error) d)(1,3,#error)
Consider the given expression:
not 5 or 4 and 10 and „bye‟
44 Which of the following will be correct output if the given expression
is evaluated?
(a) True (b) False (c) 10 (d)„bye‟
45 Consider the given expression:
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 14 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
not True and False or not True
Which of the following will be correct output if the given expression is
evaluated?
(a) True (b) False (c) NONE (d) NULL
What will the following expression be evaluated to in Python?
46 print(2**3 + (5 + 6)**(1 + 1))
(a) 129 (b)8 (c) 121 (d) None
What will the following expression be evaluated to in Python?
47 print(16-(3+2)*5+2**3*4)
(a)54 (b) 46 (c) 23 (d) 32
Add a pair of parentheses to each expression so that it evaluates to True.
48 a) 2+ 3== 4+5 ==7 ANS : (2 + (3 == 4) + 5) == 7
b) 0 ==1 == 2 ANS : ( 0 == (1==2))
What will be the output of following expressions:
49
a) 2**3**2 ANS : 512 b) (2**3)**2 ANS: 64
Consider the given expression:
8 and 13 > 10
50
Which of the following is the correct value of the expression?
a) True b) False c) None d) NULL
What will the following expression be evaluated to in Python?
51 27 % 7 // (3 / 2)
a) 2 b) 2.0 c) 4.0 d) 4
Consider the given expression:
7%5==2 and 4%2>0 or 15//2==7.5
52 Which of the following will be correct output if the given expression is
evaluated?
(a)True (b) False (c)None (d)Null
Consider the given expression:
(5<10)and(10<5)or(3<18)and not(8<18)
53 Which of the following will be correct output if the given expression is
evaluated?
(a) True (b) False (c) NONE (d) NULL
The correct output of the given expression is:
54 True and not False or False
(a) False (b) True (c) None (d) Null
Evaluate the following Python expression
55 print(12*(3%4)//2+6)
(a)12 (b)24 (c) 10 (d) 14
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 15 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Predict the correct output of the following Python statement –
56 print(4 + 3**3/2)
(a) 8 (b) 9 (c) 8.0 (d) 17.5
Consider the given expression:
(not True) and False or True
57
Which of the following is the correct value of the expression?
a) True b) False c) None d) NULL
What will the following expression be evaluated to in Python?
58 15.0 // 4 * 5 / 3
a) 6.25 b) 5 c) 5.0 d) 0.25
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 16 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Q.No Questions
1 State True or False
“Python has a set of keywords that can also be used to declare variables”
FALSE
2 Every variable in Python holds an instance of an object. These Objects are
of two types.
(a) Mutable (b) immutable (c) both a and b (d) instance
3 The PASS statement is an empty statement in Python
4 State whether True or False:
Variable names can begin with the _ symbol. True.
5 Which of the following is not a valid identifier in Python?
a)KV2 b) _main c) Hello_Dear1 d) 7 Sisters
6 State True or False
“Python identifiers are dynamically typed.” True
7 Identify the invalid variable name from the following.
Adhar@Number, none, 70outofseventy, mutable
8 Find the invalid identifier from the following
(a) name (b) class (c) section (d) break
9 Find the invalid identifier from the following
a) sub%marks b)age c)_subname_ d)subject1
10 Which of the following is an invalid identifier?
1. CS_class_XII b. csclass12 c. _csclass12 d. 12CS
11 State True or False “Python is a case insensitive language.” False
12 Find the invalid identifier from the following
a) KVS_Jpr b) false c) 3rdPlace d) _rank
13 Find the valid identifier from the following
(a) Tot$balance (b) TRUE (c) 4thdata (d) break
14 Find the valid identifier from the following
a) My-Name b) True c) While d) S_name
15 Which of the following is not a valid identifier name in Python?
a) 5Total b) _Radius c) pie d)While
16 Which of the following is not a valid identifier name in Python?
a) 5Total b) _Radius c) pie d)While
17 Find the invalid identifier from the following
a) MyName b) True c) 2ndName d) My_Name
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 17 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
18 Which is a valid identifier in python?
(a) int (b) len (c) ssum1 (d) all of them
19 Python identifiers are case sensitive.
a) True b) False
20 Find the invalid identifier from the following:
a) None b) address c) Name d) Pass
21 Which of the following is an invalid identifier?
(a) true (b) print (c) 4ever (d) While
22 Which of the following is an invalid identifier?
(a) true (b) print (c) 4ever (d) While
23 Find the invalid identifier from the following:
A. MyName B. true C. 2ndName D. My_Name
24 Which of the following is a valid identifier in Python:
(a) elseif (b) for (c) pass (d) 2count
25 Which of the following is an invalid identifier in Python?
(a) Max_marks (b) Max–marks (c) Maxmarks
(d) _Max_Marks
26 State True or False
Python language is Cross platform language. True
27 Which of the following is valid identifier?
a) Serial_no. b)totalMarks c)_Percentage d)Hundred$
28 Which of the following is an invalid identifier?
(a)_123 (b) E_e12 (c) None (d) true
29 Find the invalid identifier from the following
a) Marks@12 b) string_12 c)_bonus d)First_Name
30 Which of the following is not a Keyword?
a) eval b) assert c) nonlocal d) pass
31 Which is valid keyword?
a. Int b. WHILE c.While d.if
32 Which keyword is used for function in Python language?
(a) Function (b) def (c) Fun (d) Define
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 18 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Q.No Questions
Select the correct output of the code:
>>> s='[email protected]'
>>> s=s.split('kv')
>>> op = s[0] + "@kv" + s[2]
1 >>> print(op)
(A) mail2@kvsangathan
(B) mail2@sangathan.
(C) mail2@kvsangathan.
(D) mail2kvsangathan
What will be the output of the following statement given:
txt="cbse. sample paper 2022"
print(txt.capitalize())
2 a) CBSE. sample paper 2022
b) CBSE. SAMPLE SAPER 2022
c) cbse. sample paper 2022
d) Cbse. Sample Paper 2022
Select the correct output of the following code:
>>>str1 = ‘India is a Great Country’
>>>str1.split(‘a’)
3 a) [‘India’,’is’,’a’,’Great’,’Country’]
b) [‘India’, ’is’, ’Great’, ’Country’]
c) [‘Indi’, ’is’, ’Gre’, ’t Country’]
d) [‘Indi’, ’is’, ’Gre’, ’t’, ‘Country’]
Identify the output of the following Python statement:
s=”Good Morning”
print(s.capitalise( ),s.title( ), end=”!”)
4 (a) GOOD MORNING!Good Morning
(b) Good Morning! Good Morning
(c) Good morning! Good Morning!
(d) Good morning Good Morning!
What is the output of the following code?
S1=”Computer2023”
5 S2=”2023”
print(S1.isdigit(), S2.isdigit())
a)False True b) False False c) True False d) True True
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 19 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
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)
6
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’]
Select the correct output of the code:
Str = "KENDRIYA VIDYALAYA SANGATHAN JAMMU REGION"
Str = Str.split()
NewStr = Str[0] + "#" + Str[1] + "#" + Str[4]
7 print (NewStr)
a) KENDRIYA#VIDYALAYA#SANGATHAN# JAMMU
b) KENDRIYA#VIDYALAYA#SANGATHAN
c) KENDRIYA#VIDYALAYA# REGION
d) None of these
What is the output of the following?
print('KV Sangathan'.split('an'))
(a) ['KV S', 'gath', ' ']
8
(b) [‘KV Sangathan’,’an’]
(c) [‘KV’,’Sang’,’athan’]
(d) All of them
What is the output of the following code.
Str1=”Hello World”
9 str1.replace('o','*')
str.replace('o','*')
(a) Hello World (b) Hell* W*rld (c) Hello W*rld (d) Error
Select the correct output of the code:
mystr = ‘Python programming is fun!’
mystr = mystr.partition(‘pro’)
mystr=’$’.join(mystr)
10
(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!
Select the correct output of the following string operations
11
mystring = “Pynative”
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 20 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
stringList = [ “abc”, “Pynative”,”xyz”]
print(stringList[1] == mystring)
print(stringList[1] is mystring)
a) True b) False c) False d) True
False True False True
Select the correct output of the following python code:
str="My program is program for you"
t = str.partition("program")
print(t)
12
a) ('My ', 'program', ' is ', 'program', ' for you')
b) ('My ', 'program', ' is program for you')
c) ('My ', ' is program for you')
d) ('My ', ' is ', ' for you')
Select the correct output of the code:
a= "Year 2022 at All the best" a = a.split('2')
13 a = a[0] + ". " + a[1] + ". " + a[3] print (b)
(a) Year . 0. at All the best (b) Year 0. at All the best
(c) Year . 022. at All the best (d) Year . 0. at all the best
Select the correct output of the code:
for i in "QUITE":
print([i.lower()], end= "#")
14 (a) q#u#i#t#e#
(b) [„quite#‟]
(c) ['q']#['u']#['i']#['t']#['e']#
(d) [„quite‟] #
Select the correct output of the code:
a = "assistance"
a = a.partition('a')
b = a[0] + "-" + a[1] + "-" + a[2]
15 print (b)
a) -a-ssistance
b) -a-ssist-nce
c) a-ssist-nce
d) -a-ssist-ance
Select the correct output of the code:
s = "Question paper 2022-23"
16
s= s.split('2')
print(s)
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 21 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
(a) ['Question paper ', '0', '', '-', '3']
(b) ('Question paper ', '0', '', '-', '3')
(c) ['Question paper ', '0', '2', '', '-', '3']
(d) ('Question paper ', '0', '2', '', '-', '3')
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 22 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Q.No Questions
Suppose str1= ‘welcome’. All the following expression produce the same
1 result except one. Which one?
(a) str[ : : -6] (b) str[ : : -1][ : : -6] (c) str[ : :6] (d) str[0] + str[-1]
Which of the following will be the output of the code:
mySubject = “Computer Science”
2
print(mySubject[:3] + mySubject[3:])
a) Com b) puter Science c) Computer Science d) Science Computer
What will be the output of following code snippet:
msg = “Hello Friends”
3
msg [ : : -1]
a)Hello b) Hello Friend c) 'sdneirF olleH' d) Friend
Give the output:
my_data = (1, 2, "Kevin", 8.9)
4
print (my_data[-3])
1. 8.9 2. “Kevin”. 3. 1 4. 2
If S=”Pythonlanguage”
5 Predict the output of print(S[:-6:-2])
Output : eag
Given is a Python string declaration:
myexam="@@CBSE Examination 2023@@"
6
Write the output of: print(myexam[::-3])
Output :@2 ina B@
Given a string S = “ComPUterSciEnce”,
7 write the output of print(S[3:10:2])
Output : Ptrc
If the following code is executed, what will be the output of the following
code?
8 n="Trust yourself that you can do it and get it"
print(n[2:-4:2])
Output : utyusl htyucnd tad e
Select the correct output of the code:
Str=“Computer”
9
Str=Str[-4:]
print(Str*2)
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 23 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
a. uter b. uterretu c. uteruter d. None of these
Find output generated by the following code:
mystr = “Hello I am a Human.”
10
print(mystr[::-3])
Output : nuaa l
Given is a Python string declaration:
Word = "Connect Python”
11
Write the output of: print(Word[: : 3])
Output :Cntyo
What is the output of the following?
print('KV Sangathan'.split('an'))
(a) ['KV S', 'gath', ' ']
12
(b) [‘KV Sangathan’,’an’]
(c) [‘KV’,’Sang’,’athan’]
(d) All of them
f the following code is executed, what will be the output of the following
code?
13 name="Kendriya Vidyalaya Sangathan"
print(name[2:13:2])
(a) Kendriya (b) Vidyalaya (c) Sangathan (d) nry iy
What gets printed when the following code is executed?
names = [‘Hasan’,’Balwant’,’Sean’,’Dia’]
14
print(names[-1][-1])
(a) h (b) n (c) a (d) Dia
If the following code is executed, what will be the output of the following
code?
15 name="IlovemyCountry"
print(name[3:10])
Output : vemyCou
If the following code is executed, what will be the output of the following
code?
mystr1 = ‘Sequence with labels’
16 mystr2 = ‘$’
print(mystr2*6+mystr1+mystr2*5)
Output:
$$$$$$Sequence with labels$$$$$
Predict the output of following python code.
17
SS="PYTHON"
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 24 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
print( SS[:3:])
(A) THON (B) PYT (C) PYTH (D) HON
Given is a Python string declaration:
message='FirstPreBoardExam@2022-23'
18 Write the output of: print(message[ : : -3].upper())
Output :322ADORSF
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 25 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Write the output of print(str[ : :-1])
Output:
malayalam
Predict the output of the Python code given below:
What is the output of the following Python code
x=”hello world”
print(x[:2],x[:-2],x[-2:])
print(x[6],x[2:4])
26
print(x[2:-3],x[-4:-2])
Output :
he hello wor ld
w ll
llo wo or
Given is a Python string declaration:
str="Kendriya Vidyalaya Sangathan"
27 Write the output of: print(str[9:17])
Output :
Vidyala
Consider the string state = “Jharkhand”. Identify the appropriate
28 statement that will display the last five characters of the string state?
(a) state [-5:] (b) state [4:] (c) state [:4] (d) state [:-4]
Find output generated by the following code:
Str = "Computer"
Str = Str[-4:]
29
print(Str*2)
Output :
uu
Given is a Python string declaration:
myexam="Russia Ukrain"
30 Write the output of: print(myexam[-2:2:-2])
Output :
irUas
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 26 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Q.No Questions
1 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
2 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
3 Consider the following code:
dict1 = {‘Mohan’: 95, ‘Ram’: 89, ‘Suhel’: 92, ‘Saritha’: 85}
What suitable code should be written to return a list of values in dict1 ?
Answer
dict1.values()
dict_values([95, 89, 92, 85])
4 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]
5 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
6 Consider the coding given below and fill in the blanks:
Dict_d={‘BookName’:’Python’,’Author’:”Arundhati Roy”}
Dict_d.pop() # Statement 1 False
List_L=[“java”,”SQL”,”Python”]
List_L.pop() # Statement 2 True
In the above snippet both statement 1 and 2 deletes the last element from
the object Dict_d and List_L________(True/False).
7 Write output for the following code:
list1=[x+2 for x in range(5)]
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 27 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
print(list1)
Answer
[2, 3, 4, 5, 6]
8 What is 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=" ")
(a) 5 5 1 2 3 (b) 5 1 2 3 4 (c) 2 3 4 5 1 (d) 2 3 4 5 5
9 Which one is the correct output for the following code?
a=[1,2,3,4]
b=[sum(a[0:x+1]) for x in range(0,len(a))]
print (b)
(a) 10 (b) [1,3,5,7] (c) 4 (d) [1,3,6,10]
10 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]
11 Given the list L=[“A”, “E”, “I”, “O”, “U”] , write the output of
print(L[2:5])
Answer
['I', 'O', 'U']
12 A List is declared as
List1=[2,3,5,7,9,11,13]
What will be the value of len(List1)
Answer
7
13 Identify the data type of INFO:
INFO = ['hello',203,'9',[5,6]]
a. Dictionary b. String c. Tuple d. List
14 Given the list L=[-1,4,6,-5] ,write the output of print(L[-1:-3])
a)[4,6,-5] b)[] c)[6,-5] d)error
15 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
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 28 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
16 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]
17 Identify the output of the following Python statements, where L1 is a List
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’]
18 Which of the following statements create a dictionary?
a) d = {}
b) d = {“john”:40, “peter”:45}
c) d = {40:”john”, 45:”peter”}
d) All of the mentioned above
19 Which statement is correct for dictionary?
(i) A dictionary is a ordered set of key: value pair
(ii) each of the keys within a dictionary must be unique
(iii) each of the values in the dictionary must be unique
(iv) values in the dictionary are immutable
20 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’}
21 What will be the output of the following statements?
a = [0, 1, 2, 3]
del a[:]
print(a)
a) None
b) [ ]
c) [0, 1, 2, 3]
d) NameError
22 Given the following dictionaries
D1={"Exam":"ICSCE", "Year":2023, "Total":500}
Which statement will add a new value pair (Grade: “A++”) in dictionary
D1?
a. D1.update(“REMARK” : “EXCELLENT”)
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 29 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
b. D1 + {“REMARK” : “EXCELLENT”}
c. D1[“REMARK”] = “EXCELLENT”
d. D1.merge({“REMARK” : “EXCELLENT”})
23 Create the dictionary on data
Exam=”PB”
Year=”2013”
Where exam and year are keys
Answer
data = {'Exam':'PB','Year':2013}
data
{'Exam': 'PB', 'Year': 2013}
24 Given the following dictionaries
exam={"Exam":"AISSCE","Year":2023}
result={"Total":500,"Pass_Marks":165}
(a) dict_exam.update(result)
(b) dict_exam+result
(c) dict_exam.add(result)
(d) dict.merge(result)
25 Which is the correct form of declaration of dictionary?
a) Day={1:’Monday’,2:’Tuesday’,3:’Wednesday’}
b) Day={‘1:Monday’,’2:Tuesday’,’3:Wednesday’}
c) Day=(1:’Monday’,2:’Tuesday’,3:’Wednesday’)
d) Day=[1:’Monday’,2:’Tuesday’,3:’Wednesday’]
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 30 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Q.No Questions
1 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
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 Suppose a tuple T1 is declared as T1 = (10, 20, 30, 40, 50) which of the
following is incorrect?
a)print(T1[1]) b) T1[2] = -29 c) print(max(T)) d) print(len(T))
4 Suppose a tuple K is declared as K = (100, 102, 143, 309), which of the
following is incorrect?
a)print(K[-1]) b) K[3] =405 c) print(min(K)) d) print(max(K))
5 Identify valid declaration of tuple
a)T={‘a’,’b’,’c’,’d’} b) T=‘a’,’b’,’c’,’d’ c)D=(‘a’,’b’,’c’,’d’) d) both b and c
6 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
7 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)
8 Write the output of following code:
Tup1=(10,15,20,25,30)
print(Tup1[-1:0:-2])
The output is : (30, 20)
9 Suppose a tuple T is declare as:
T=(10,12,43,39)
Which of the following is in correct?
(a) print(t[1]) (b) T[2]=-29 (c) print(max(T) (d) print(len(T))
10 What will be the output for the following Python statement?
T=(10,20,[30,40,50],60,70)
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 31 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
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
11 Which of the following options will not result in an error when performed
on types in
python where tp = (5,2,7,0,3) ?
(a) tp[1] = 22
(b) tp.append(23)
(c) tp1 = tp+tp*2
(d) tp.sum()
12 Given tp = (1,2,3,4,5,6). Which of the following two statements will give
the same
output?
1. print(tp[:-1])
2. print(tp[0:5])
3. print(tp[0:4])
4. print(tp[-4:])
(a) Statement 1 and 2 (b) Statement 2 and 4 (c) Statement 1 and 4 (d)
Statement 1 and 3
13 Write the output of the code given below:
a,b,c,d = (1,2,3,4)
mytuple = (a,b,c,d)*2+(5**2,) - 9
print(len(mytuple)+2) = 11
The output is 11
14 What will be the output of the following code snippet?
init_tuple_a =( 'a', '3’)
init_tuple_b = ('sum', '4')
print (init_tuple_a + init_tuple_b)
The output is : (‘a’,’3’,’sum’,’4’)
15 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
16 Choose the correct output of following code:
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 32 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Tup=(100)
print(Tup*3)
(A) (300,) (B) (100,100,100) (C) Syntax Error (D) 300
17 Find the output:
tuple1 = (10,12,14,16,18,20,22,24,30)
print( tuple1[5:7] ) - [20,22]
18 Suppose a tuple T is declared as T = (10, 20, 30, 40),
what will be the output of print(T*2) - (10,20,30,40,10,20,30,40)
19 Identify the data type of X:
X = tuple(list( (1,2,3,4,5) ) )
(a) Dictionary (b) string (c) tuple (d) list
20 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)
Answer : print(a*3) - (1,2,3,1,2,3,1,2,3)
print(a,a,a) - (1,2,3)(1,2,3)(1,2,3)
21 Predict the output of the Python code given below:
T = (9,18,27,36,45,54)
L=list(T)
L1 = []
for i in L:
if i%6==0:
L1.append(i)
T1 = tuple(L1)
print(T1)
The output is (18,36,54)
22 Suppose a tuple Tup is declared as Tup = (12, 15, 63, 80) which of
the following is incorrect?
a) print(Tup[1]) b) Tup[2] = 90 c) print(min(Tup)) d) print(len(Tup))
23 t1=(2,3,4,5,6)
print(t1.index(4))
output is
(a) 4 (b) 5 (c) 6 (d) 2
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 33 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Q.No Questions
1 Study the following program and select the possible output(s) and write
maximum and minimum value assigned to the variable y
import random
x=random.random( )
y=random.ranint(0,4)
print(int(x),”:”,y+int(x))
(i) 0:0 (ii) 1: 6 (iii) 2:4 (iv) 0:3
2 What possible output(s) are expected to be displayed on screen at the time
of execution of the following code? Also specify the maximum and
minimum value that can be assigned to variable X.
import random
L=[10,7,21]
X=random.randint(1,2)
for i in range(X):
Y=random.randint(1,X)
print(L[Y],”$”,end=” ”)
(a) 10 $ 7 $ (b) 21 $ 7 $ (c) 21 $ 10 $ (d) 7 $
3 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 @
4 Which of the following is not a function/method of the random module in
python?
(a) randfloat( ) (b) randint( ) (c) random( ) (d) randrange( )
5 To include the use of functions which are present in the random library,
we must use the option:
a) import random b) random.h c) import.random d) random.random
6 What are the incorrect output(s) from the given options when the
following code is executed? Also specify the minimum and maximum
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 34 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
values that can be assigned to the variable VALUE.
import random
VALUE = random.randint (0,3)
SUBJECT=[“PHY”,”CHEM”,”MATHS”,”COMP”];
for I in SUBJECT:
for J in range(1, VALUE):
print(I, end=””)
print()
Options:
i) PHYPHY
CHEMCHEM
MATHSMATHS
COMPCOMP
ii) PHY
PHYCHEM
PHYCHEMMATHS
iii) PHY
CHEMCHEM
COMPCOMPCOMP
iv) PHY
CHEM
MATHS
COMP
7 Go through the python code shown below and find out the possible
output(s) from the suggested options i to iv. Also specify maximum and
minimum value that can be assigned to the variable j.
import random
i=random.random()
j=random.randint(0,6)
print(int(i),”:”,j+int(i))
(i)0:0 (ii)0:6 (iii)1:7 (iv)1:6
8 What possible output(s) are expected to be displayed on screen at the time
of execution of the program from the following code? Also write the value
assigned to
variable first and second.
import random
from random import randint
LST=[5,10,15,20,25,30,35,40,45,50,60,70]
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 35 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
first = random.randint(3,8) – 1
second = random.randint(4,9) – 2
third = random.randint(6,11) – 3
print(LST[first],"#", LST[second],"#", LST[third],"#")
i) 20#25#25# ii) 30#40#70# iii) 15#60#70# iv) 35#40#60#
9 Study the following program and select the possible output(s) from the
options (i) to (iv) following it.
import random
Ar=[20,30,40,50,60,70]
From = random.randint(1,3)
To = random.randint(2,4)
for K in range(From,To+1):
print(Ar[K],end="%")
(i) 10%40%70% (ii) 30%40%50% (iii) 50%60%70% (iv) 40%50%60%
10 What possible output(s) is/are expected to be displayed on the screen at
the time of execution of the program from the following code ? Also
specify the maximum and minimum value that can be assigned to the
variable R when K is assigned value as 2.
import random
Signal = [ 'Stop', 'Wait', 'Go' ]
for K in range(2, 0, -1):
R = random.randrange(K)
print (Signal[R], end = ' # ')
(a) Stop # Wait # Go # (b) Wait # Stop # (c) Go # Wait # (d) Go # Stop #
11 To use randint(a,b) which of the following module should be imported ?
a)math b)random c)CSV d)randinteger()
12 What possible outputs(s) are expected to be displayed on screen at the
time of execution of the program from the following code. Select which
option/s is/are correct import random
print(random.randint(15,25) , end=' ')
print((100) + random.randint(15,25) , end = ' ' )
print((100) -random.randint(15,25) , end = ' ' )
print((100) *random.randint(15,25) )
(i) 15 122 84 2500 (ii) 21 120 76 1500
(iii) 105 107 105 1800 (iv) 110 105 105 1900
13 Which of the following random module functions generated a floating
point number?
(a) random() (b) randint() (c) uniform() (d) all of these
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 36 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
14 What possible output(s) are expected to be displayed on screen at the time
of execution of the program from the following code?
import random
points=[20,40,10,30,15]
points=[30,50,20,40,45]
begin=random.randint(1,3)
last=random.randint(2,4)
for c in range(begin,last+1):
print(points[c],"#")
(a) 20#50#30# (b) 20#40#45 (c) 50#20#40# (d) both (b) and (c)
15 .Identify the output of the following python statements
import random
for n in range(2,5,2):
print(random.randrange(1,n),end=‟*‟)
(a)1*3 (b) 2*3 (c) 1*3*4 (d)1*4
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 37 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Q.No Questions
1 Write a function INDEX_LIST(L), where L is the list of elements passed as
argument to the function. The function returns another list named
‘indexList’ that stores the indices of all Non-Zero Elements of L. For
example: If L contains [12,4,0,11,0,56] The
indexList will have - [0,1,3,5]
SOLUTION:
def INDEX_LIST(L):
indexlist=[]
for i in range(len(L)):
if L[I] != 0:
indexlist.append(i)
return indexlist
L=[12,4,0,11,0,56]
print(INDEX_LIST(L))
2 Write a function LShift(arr,n) in python, which accepts a list of numbers
and 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] and n=2
Output
Arr :[30,40,50,12,11,10,20]
SOLUTION :
def shiftn(l,2):
ln=len(l)
for x in range(0,n):
y=l[0]
for i in range(0,ln-1):
l[i] = l[i+1]
l[ln-1]=y
print(l)
l=[10,20,30,40,12,11]
n=2
shiftn(l,n)
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 38 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
3 Write a python program using function to find the largest element in a list
and then reverse the list contents and display it. Don’t use in-built
functions for the program
Solution :
def reverse(x):
L=len(x)
max=x[0]
for i in range(0,L,1):
x[i]=x[i]*2
if x[i] >=max:
max=x[i]
for i in range(-1,-8,-1):
print(x[i],end=" ")
print("\nLargest Number is =",max)
x=[4,8,7,5,6,2,10]
reverse(x)
4 Write a function sumcube(L) to test if an element from list L is equal to
the sum of the cubes of its digits ie 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
Solution :
def armstrong(l):
ln=len(l)
for i in range(len(l)):
first=l[i]
n1=first
s1=0
while n1 > 0:
digit=n1%10
s1=s1+digit**3
n1=n1//10
if first==s1:
print(first,"It ia armstrong number")
# main program
l=[67,153,311,96,370,405,371,955,407]
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 39 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
armstrong(l)
5 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]
Solution :
def DIVI_LIST(NUM_LST):
D_2=[]
D_5=[]
for i in range(len(NUM_LST)):
if NUM_LST[i] % 2 ==0 :
D_2.append(NUM_LST[i])
if NUM_LST[i] % 5 == 0:
D_5.append(NUM_LST[i])
print(D_2)
print(D_5)
NUM_LST=[2,4,6,10,15,12,20]
DIVI_LIST(NUM_LST)
6 Write a function SUMNOS() that accept a list L of numbers and find sum
of all even numbers and sum of all odd numbers.
If L=[1,2,3,4],
Output :
sum of even nos:6
Sum of odd numbers:4
Solution :
def SUMNOS(L):
seven=0
sodd=0
for i in L:
if i % 2 ==0 :
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 40 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
seven = seven + i
else :
sodd = sodd + i
print("sum of even numbers = ",seven)
print("sum of odd numbers =",sodd)
L=[1,2,3,4]
SUMNOS(L)
7 Write a function GENERATE_INDEX(L), where L is the list of elements
passed as argument to the function. The function returns another list
named ‘NewIndex’ that stores the indices of all even Elements of L.
For example: If L contains [22,7,9,24,6,5]
The NewIndex will have - [0, 3, 4]
Solution:
def NewIndex(L):
NewIndex=[]
for i in range(len(L)):
if L[i] % 2 ==0 :
NewIndex.append(i)
return NewIndex
L=[22,7,9,24,6,5]
print(NewIndex(L))
8 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
Solution :
def convert():
for I in range(L):
if L[I] % 2 == 0:
L[I] = L[I] /2
else :
L[I] = L[I] * 2
L=[5,6,7,16,9]
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 41 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
convert(L)
9 Python funtion oddeven(L) to print positive numbers in a list L.
Example:
Input: [4, -1, 5, 9, -6, 2, -9, 8]
Output: [4, 5, 9, 2, 8]
Solution :
def NewIndex(L):
NewIndex=[]
for i in range(len(L)):
if L[i] >=0 :
NewIndex.append(L[i])
return NewIndex
L=[4,-1,5,9,-6,2,-9,8]
print(NewIndex(L))
10 Write definition of a method/function AddOddEven(VALUES) to display
sum of odd and even values separately from the list of VALUES.
For example : If the VALUES contain [15, 26, 37, 10, 22, 13]
The function should display
Even Sum: 58
Odd Sum: 65
Repeated Question - Same as Q no : 10
11 Write the definition of a function Reverse(X) in Python to display the
elements in reverse order such that each displayed element is twice of the
original element (element *2) of the List X in the following manner:
For example, if List X contains 7 integers as follows:
Solution :
def reverse(x):
L=len(x)
for i in range(0,L,1):
x[i]=x[i]*2
for i in range(-1,-8,-1):
print(x[i],end=" ")
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 42 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
x=[4,8,7,5,6,2,10]
reverse(x)
12 Write a function INDEX_LIST(L), where L is the list of elements passed as
argument to the function. The function returns sum of odd nos in list .
Repeated Question - Same as Question Number : 10
13 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
Solution :
def swap(num,n):
for i in range(0,n,2):
temp=num[i]
num[i]=num[i+1]
num[i+1]=temp
num=[]
n=int(input(“enter the number of elements”))
print(“The elements are “)
for i in range(0,n):
x=int(input())
num=append[x]
print(“original List is “,num)
print(“Swapped list :”,swap(num,n))
14 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
SOLUTION:
def zeroending(scores):
s=0
for i in scores:
if i % 10 = 0:
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 43 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
s=s+l
print(“sum = “ , s)
scores=[200.456.300.100.234.678]
zeroending(scores)
15 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]
Repeated Question - Same as Question Number 17
16 Write a python Function that accepts a string and calculates the number
of uppercase letters and lowercase letters.
Sample String : Python ProgrammiNg
Expected Output:
Original String : Python ProgrammiNg
No. of Upper case characters : 3
No. of Lower case characters :14
Solution :
def uplo():
fobj=open("refresh.txt",'r')
line=fobj.readlines()
r=0
up=0
lo=0
for l in line:
r=l.split()
for i in r:
for d in range(len(i)):
if i[d].isupper()==True:
up+=1
else:
lo+=1
fobj.close
print("no.of uppercase letters are: ",up)
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 44 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
print("no.of lowercase letters are: ",lo)
uplo()
17 Write definition of a function How_Many(List, elm) to count and display
number of times the value of elem is present in the List. (Note: don’t use
the count() function)
For example :
If the Data contains [205,240,304,205,402,205,104,102] and elem contains
205
The function should display 205 found 3 Times
Solution :
def count(data,item):
c=0
for i in data:
if i == item:
c=c+1
print(item,”found “,c,”times”)
data=[101,102,107,105,102,103,104,102]
item=102
count(data,item)
18 Write a function listchange(Arr)in Python, which accepts a list Arr of
numbers, the function will replace the even number by value 10 and
multiply odd number by 5. Sample Input Data
of the list is:
a=[10,20,23,45]
listchange(a,4)
output : [10, 10, 115, 225]
Solution :
def convert(l):
for i in range(l):
if l[I] % 2 ==0:
l[I]=10
else :
L[I] = l[I] * 5
l=[10,20,23,45]
print(convert(l))
19 Write a function that takes two numbers and return that has maximum
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 45 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
one’s digit.
(for eg if 491 and 278 are passed it will return 278 as it has got maximum
one’s digit)
Solution:
def onesdigit(n1,n2):
first =n1
s1=0
while n1 > 0:
digit=n1%10
s1=s1+digit
n1=n1//10
fsum=0
while s1>0:
d=s1%10
fsum=fsum+d
s1=s1//10
print("sum of digits =",fsum)
second=n2
s2=0
while n2 > 0:
digit=n2%10
s2=s2+digit
n2=n2//10
ssum=0
while s2>0:
d=s2%10
ssum=ssum+d
s2=s2//10
# main program
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 46 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
num1=int(input("Enter First Number"))
num2=int(input("enter second number"))
onesdigit(num1,num2)
20 Write a function lenFOURword(L), where L is the list of elements (list of
words) passed as argument to the function. The function returns another
list named „indexList‟ that stores the indices of all four lettered word of L.
For example:
If L contains [“DINESH”, “RAMESH”, “AMAN”, “SURESH”, “KARN”]
The indexList will have [2, 4]
Solution :
def lenfourword(l):
indexlist=[]
ln=len(l)
for i in range(ln):
if len(l[i])==4:
indexlist.append(l[i])
print(indexlist)
l=["dINESH", "RAMESH", "AMAN", "SURESH", "KARaN"]
lenfourword(l)
21 Write a function modilst(L) that accepts a list of numbers as argument
and increases the value of the elements by 10 if the elements are divisible
by 5. Also write a proper call statement for the function.
For example:
If list L contains [3,5,10,12,15]
Then the modilist() should make the list L as [3,15,20,12,25]
Solution :
def modilist(l):
for i in range(l):
if l[I] % 5 ==0:
l[I]= l[I] + 10
l=[3,5,10.12.15]
print(modilist(l))
22 Write a function INDEX_LIST(L), where L is the list of elements passed as
argument to the function. The function returns another list named
‗indexList‘ that stores the indices of all NonZero Elements of L.
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 47 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
For example:
If L contains [12,4,0,11,0,56]
The indexList will have - [0,1,3,5]
Repeated Question - same as question no : 1
23 Write definition of a method/function DoubletheOdd( ) to add and
display twice of odd values from the list of Nums.
For example :
If the Nums contains [25,24,35,20,32,41]
The function should display
Twice of Odd Sum: 202
Solution :
def doubletheodd(l):
for i in range(l):
if l(i) % 2 !=0:
sum = sum+l(i)
print(“Twice of odd sum = “,sum*2)
l=[25,24,35,20,32,41]
doubletheodd(l)
24 Write a function in python named SwapHalfList(Array), which accepts
a list Array of numbers and swaps the elements of 1st Half of the list
with the 2nd Half of the list, ONLY if the sum of 1st Half is greater
than 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]
Solution :
def SwapHalfList (num):
mid=len(num)//2
s1=0
s2=0
for i in range(0,mid):
s1=s1+num[i]
for i in range(mid,len(num)):
s2=s2+num[i]
if s1>s2:
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 48 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
for i in range(0,mid):
num[i],num[mid+i]=num[mid+i],num[i]
print(num)
print("Sum of first half",s1)
print("Sum of Second half", s2)
# main program
n=[ 100, 200, 300, 40, 50, 60]
SwapHalfList(n)
Solution:
def INDEX_LIST(S):
indexlist=[]
for i in range(len(S)):
if S[i] in "EIOUaeiou":
indexlist.append(i)
print(indexlist)
#main program
str=input("enter string")
INDEX_LIST(str)
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 49 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Q.No Questions
1 Identify the errors in the program segment given below. 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])
print(Tot[6])
Answer
def Tot (Number):
Sum=0
for C in range (1, Number + 1):
Sum += C
return Sum
print(Tot(3))
print(Tot(6))
2 Observe the following Python code very carefully and rewrite it after
removing all syntactical errors with each correction underlined.
DEF result_even( ):
x = input(“Enter a number”)
if (x % 2 = 0) :
print (“You entered an even number”)
else:
print(“Number is odd”)
even ( )
Answer
def result_even( ):
x = int(input("Enter a number") )
if (x % 2 == 0) :
print("even number")
else:
print("Number is odd")
result_even()
3 Ramu wrote a code function to display Fibonacci series. Correct the errors and
rewrite it.
def Fibonacci()
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 50 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
nterms = int(input("How many terms? "))# first two terms
n1, n2 = 0, 1
count = 0
if nterms<= 0:# check if the number of terms is valid
Print("Please enter a positive integer");
elifnterms == 1:# if there is only one term, return n1
print("Fibonacci sequence upto",nterms,":")
print(n1);
else:# generate fibonacci sequence
print("Fibonacci sequence:")
while count >nterms:
print(n1)
nth = n1 + n2
n1 = n2# update values
n2 = nth
count -= 1
Answer
def Fibonacci() :
nterms = int(input("How many terms? "))
n1, n2 = 0, 1
count = 0
if nterms<= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count >nterms:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
Fibonacci()
4 Rewrite the following code after removing the syntactical error(if
any).Underline each correction:
X=input("Enter a Number")
If x % 2 =0:
for i range (2*x):
print i
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 51 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
loop else:
print "#"
Answer
x=input("Enter a Number")
if (x%2 == 0):
for i in range (x*2):
print (i )
else:
print( "#")
5 Shraddha 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.
6 Mr. Gupta 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”)
7 Rewrite the following Python program after removing all the syntactical
errors (if any), underlining each correction:
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”
x=int(input(“Enter a number”)
8 Reena has written a code to check the maximum of given numbers. Her code
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 52 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
is having errors. Rewrite the correct code with output and underline the
correction made.
def printMax(a, b)
if a> b:
print(a, 'is maximum')
elif a = b:
print(a, 'is equal to', b)
else;
print(b, 'is maximum')
printMax(33,94):
9 Rewrite the following code in Python after removing all syntax error(s).
Underline each correction done in the code.
for Name in [Aakash, Sathya, Tarushi]
IF Name[0]= 'S':
print(Name)
for Name in[“Aakash”, “Sathya”, “Tarushi”]:
if Name[0]== 'S':
print(Name)
10 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
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 53 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
11 Find the error(s) in the following code snippet and write the corrected code.
Def check():
N=25
for i in range(0,N):
if N%2=0:
print(N*2)
elif N%3==0
print(N*3)
Else:
print(N)
check()
12 Rewrite the following code in Python after removing all syntax error(s).
Underline each correction done in the code.
STRING=""WELCOME
NOTE = " "
for S in range(0,8):
if STRING[S]= ’E’:
print(STRING(S))
Else:
print “NO”
13 Rajat has written the following Python code. There are some errors in it.
Rewrite the
correct code and underline the corrections made.
DEF execmain():
x = input("Enter a number:")
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 54 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
if (abs(x)=x):
print ("You entered a positive number")
else:
x=*-1
print "Number made positive:"x
execmain()
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 55 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
15 Aman has write the code to find factorial of an integer number as follow. But he
got some error while running this program. Kindly help him to correct the
errors.
num=int(input("Enter any integer number"))
fact=1
for x of range(num,1,-1)
if num=1 or num=0
print ("Fact=1")
break
else
fact=fact*x
print(fact)
16 Correct Code is
def DigitSum():
n = int( input("Enter number :: ")
dsum = 0
while n > 0
d = n % 10
dsum =dsum + d
n = n //10
RETURN dsum
17 Mr. Ram has written a code to input two numbers and swap the number using
function but he has some error in his coding, so help him to rectify the errors
and rewrite the correct code.
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 56 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Def swap(a,b)
c=a
a=b
b=c
print("a is",a,"b is",b )
#main()
a=int(input("enter in a "))
b=int(input("enter in b"))
Swap(a,b)#calling a function
18 Rewrite the following code in python after removing all errors. Underline each
correction done in the code:
num=int(“Enter any value”)
for in range(0,11):
if num==i
print num+i
else:
Print num-i
19 function and he has written the following code but it’s not working and
producing
errors. Help Sumit to correct this and rewrite the corrected code. Also underline
the
corrections made.
Def prime (num):
factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
else num == 0
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 57 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
21 Mr. Akash has written a code , His code is having errors , Rewrite the correct
code and underline the correction s made.
5x=input(“Enter a number”)
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 58 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
If(abs(x)=x):
Print(“You Entered a positive number..”)
Else:
x=x-1
print(“Number made positive:”x)
22 Anshika has written a code to calculate the factorial value of a number, but her
code is having some errors. Rewrite the correct code and underline the
corrections made.
def Factorial(Num)
1=fact
While num=>0:
fact=fact*num
num=-1
print(“Factorial value is =”,fact)
23 A student has written a code to print a pattern of even numbers with equal
intervals. His code is having errors. Rewrite the correct code and underline the
corrections made.
def pattern(start=0, end, interval):
for n in range(start: end, interval):
if(n%2==1):
print(n)
else
pass
x=int(input("Enter Start Number: "))
y=int(input("Enter End Number: "))
z=int(input("Enter Interval: "))
pattern(x,y,z)
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 59 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
25 Rewrite the following code in python after removing all syntax errors.
Underline each
correction done in the code:
Def func(a):
for i in (0,a):
if i%2 =0:
s=s+1
else if i%5= =0
m=m+2
else:
n=n+i
print(s,m,n)
func(15)
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 60 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
26 Vivek has written a code to input a number and check whether it is even or odd
number. His code is having errors. Rewrite the correct code and underline the
corrections made.
Def checkNumber(N):
status = N%2
return
#main-code
num=int( input(“ Enter a number to check :))
k=checkNumber(num)
if k = 0:
print(“This is EVEN number”)
else:
print(“This is ODD number”)
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 61 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
rev = 0
While num > 0:
rem == num %10
rev = rev*10 + rem
num = num//10
return rev
print(reverse(1234))
28 Preety has written a code to add two numbers .Her code is having errors.
Rewrite the correct
code and underline the corrections made.
def sum(arg1,arg2):
total=arg1+arg2;
print(”Total:”,total)
return total;
sum(10,20)
print(”Total:”,total)
29 Rewrite the following code in python after removing all the syntax
errors. Underline each correction done in the code.
num1, num2 = 10
While num1 % num2 = 0
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 62 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
num1+= 20
num2+= 30
Else:
print(„hello‟)
30 Rewrite the following code in python after removing all syntax error(s).
Underline each correction done in the code.
30=Value
for VAL in range(0,Value)
If val%4==0:
print (VAL*4)
Elseif val%5==0:
print (VAL+3)
else
print(VAL+10)
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 63 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Q.No Questions
1
Answer :
1005
12
2 Predict the Output:
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)
Answer:
10.0 # 10.0
10.0 $ 20
1.0 # 1.0
1.0 $ 20
3 Predict the Output:
def check(n1=1, n2=2):
n1=n1+n2
n2+=1
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 64 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
print(n1,n2)
check( )
check(3)
Answer :
33
53
4 Predict the Output:
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=5
func(10)
Answer :
Global x= 5
Local x= 7
y= 15
z= -3
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 65 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Answer :
50#5
6 Predict the Output:
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=100
NUM=1
OUTER(NUM,1)
OUTER(NUM,2)
print(NUM,"@",X)
Answer :
201 @ 101
201 @ 302
201 @ 101
403 @ 202
605 @ 403
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 66 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
403 @ 403
7 Predict the Output:
a=10
b=20
def change( ):
global b
a=45
b=56
change( )
print(a)
print(b)
Answer :
10
56
8 Predict the Output:
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)
Answer:
250 @ 150
250 @ 100
130 @ 100
9 Predict the Output:
def f():
global s
s += ' Is Great'
print(s)
s = "Python is funny"
s = "Python"
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 67 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
f()
print(s)
Answer :
Python Is Great
Python is funny
10 Predict the Output:
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])
Answer :
100 0
11 Predict the Output:
def MYFUNCTION():
a=10
global vr
vr=0
vr+=a
print(vr,end=' ')
MYFUNCTION()
vr=12
print(vr)
Answer :
10 12
12 Predict the Output:
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)
Answer :
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 68 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
3$3
3#3
6$4
6
13 Predict the Output:
value = 100
def display (N):
global value
value = 150
if N%7 == 0:
value = value + N
else:
value = value - N
print (value, end = '#')
display (50)
print (value)
Answer :
100#100
14 Predict the Output:
def change (p, q=50):
p = p+q
q = p-q
print(p, '#', q)
return (p)
r = 300
s = 150
r = change (r,s)
print(r,"#",s)
s = change(s)
Answer :
450 # 300
450 # 150
200 # 150
15 Predict the Output:
x=1
def fun1():
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 69 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
x=3
x=x+1
print(x)
def fun2():
global x
x=x+2
print(x)
fun1()
fun2()
Answer :
4
3
16 Predict the Output
x = 20
def myfunc():
global x
x = 10
print(x)
myfunc()
print(x,end=" ")
Answer :
10
20
17 Predict the Output:
def fun(x):
x[0] = 5
return x
g = [10,11,12]
print(fun(g),g)
Answer :
[5, 11, 12] [5, 11, 12]
18 Predict the Output:
L1 =[]
def display(N):
for K in N:
if K % 2 ==0:
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 70 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
L1.append(K//2)
else:
L1.append(K*2)
L = [11,22,33,45,55,66]
print(L)
display(L)
print(L1)
Answer :
[11, 22, 33, 45, 55, 66]
[22, 11, 66, 90, 110, 33]
19 Predict the Output:
p=5
def sum(q,r=2):
global p
p=r+q**2
print(p, end= '#')
a=10
b=5
sum(a,b)
sum(r=5,q=1)
Answer :
105#6#
20 Predict the Output:
Value = 100
def funvalue():
global Value
Value//=9
print(Value,end=" ")
Value-=10
print(Value,end=" ")
funvalue()
Answer :
11 1
21 Predict the Output:
def change(A):
S=0
for i in range(len(A)//2):
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 71 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
S+=(A[i]*2)
return S
B = [10,11,12,30,32,34,35,38,40,2]
C = change(B)
print('Output is',C)
Answer :
Output is 190
22 Predict the Output:
def Change(P ,Q=40):
P=P+Q
Q=P-Q
print( P,"#",Q)
return (P)
R=100
S=200
R=Change(R,S)
print(R,"#",S)
S=Change(S)
Answer:
300 # 100
300 # 200
240 # 200
23 Predict the Output:
a=10
def fun(x=10,y=5):
global a
a=y+x-3
print(a,end="@")
i=20
j=4
fun(i,j)
fun(y=10,x=5)
Answer :
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 72 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
21@12@
24 Predict the Output:
def Alter(P=15,Q=10):
P=P*Q
Q=P/Q
print(P,"#",Q)
return Q
A=100
B=200
A=Alter(A,B)
print(A,"$",B)
B=Alter(B)
print(A,"$",B)
Answer:
20000 # 100.0
100.0 $ 200
2000 # 200.0
100.0 $ 200.0
25 Predict the Output:
def swap(P ,Q):
P,Q=Q,P
print( P,"#",Q)
return (P)
R=100
S=200
R=swap(R,S)
print(R,"#",S)
Answer :
200 # 100
200 # 200
26 Predict the Output:
a=10
def call():
global a
a=15
b=20
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 73 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
print(a)
call()
print(a)
Answer :
15
15
27 Predict the Output:
p,q=8, [8]
def sum(r,s=5):
p=r+s
q=[r,s]
print(p, q, sep='@')
sum(3,4)
print(p, q, sep='@')
Answer:
8@[8]
8@[8]
28 Predict the Output:
Answer :
40#6#
29 Predict the Output:
def Change(P ,Q=10):
P=P*Q
Q=Q+P
print( P,"#",Q)
return (Q)
A=5
B=10
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 74 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
A=Change(A)
B=Change(A,B)
print(A,"#",B)
Answer :
50 # 60
600 # 610
60 # 610
30 Predict the Output:
x = 50
def func():
global x
print('x is', x)
x = 20
print('Changed global+local x to', x)
func()
Answer :
Changed global+local x to 50
x is 50
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 75 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
def POPSTACK():
for i in range(len(SE)):
print(SE.pop(),end=' ')
print("Stack Empty")
CREATESTACK([2,7,9,15,14])
print("SO is: ",SO)
print("SE is: ",SE)
POPSTACK()
4 Write a Python function MYSTACK(d), which should accept a dictionary d
of the form roll : name as argument. The function should create a stack
MYNAME having all the names containing ‘s’ or ‘S’. Also, write a function
Answer
MYNAME=[]
def MYSTACK(d):
for i in d:
if 's' in d[i].lower():
MYNAME.append(d[i])
def POPSTACK():
for i in range(len(MYNAME)):
print(MYNAME.pop(),end=' ')
print('Stack Empty')
MYSTACK({1: 'Sunil', 2:'Naman', 3:'Anish'})
POPSTACK()
5 A list contains following record of a student:
[student_name, marks, subject]
Write the following user defined functions to perform given operations on
the stack named ‘status’:
(i) Push_element() - To Push an object containing name and marks of a
student who scored more than 75 marks in ‘CS’ to the stack
(ii) Pop_element() - To Pop the objects from the stack and display them.
Also, display
“Stack Empty” when there are no elements in the stack.
For example:
If the lists of customer details are:
[“Danish”,80,”Maths”]
[“Hazik”,79,”CS”]
[“Parnik”,95,”Bio”]
[“Danish”,70,”CS”]
[“Sidhi”,99,”CS”]
The stack should contain
[“Hazik”,”79”]
[“Sidhi”,”99”]
def pop_element():
for i in range(len(status)):
print(status.pop())
if len(status) == 0:
print("Stack Empty")
push_element()
pop_element()
6 (i)Write the definition of a user defined function PushNV(N) which accepts
a list of strings in the parameters N and pushes all strings which have no
vowels present in it, into a list named NoVowel.
(ii)Write a program in python to input 5 words and push them one by one
into a list named All.
The program should then use the function PushNV() to create a stack of
words in the list NoVowel so that it stores only those words which do not
have any vowels in it, from the list All. Thereafter , pop each word from
the list NoVowel and display the message
“EmptyStack”
For example:
All=[]
for i in range(5):
w=input("Enter Words:")
All.append(w)
PushNV(All)
while True:
if len(NoVowel)==0:
print("EmptyStack")
break
else:
print(NoVowel.pop()," ",end='')
7 Write the definition of a user defined function Push3_5(N) which accepts a
list of integers in a parameter N and pushes all those integers which are
divisible by 3 or divisible by 5 from the list N into a list named Only3_5.
Write a program in Python to input 5 integers into a list named NUM.
The program should then use the function Push 3_5() to create the stack of
the list Only3_5. Thereafter pop each integer from the list Only3_ 5 and
display the popped value. When the list is empty, display the message
"StackEmpty".
For example:
If the integers input into the list NUM are:
ANSWER:
xiia=[]
student=[['Rajveer', '99999999999','XI', 'B'],
['Swatantra', '8888888888','XII', 'A'],
['Sajal','77777777777','VIII','A'],
['Yash', '1010101010','XII','A']]
def pushElement(student):
for d in student:
if d[2]=='XII' and d[3]=='A':
xiia.append([d[0],d[1]])
def popElement():
while len(xiia)!=0:
print(xiia.pop())
else:
print('Stack Empty')
pushElement(student)
print(xiia)
popElement()
9 A list contains following record of a customer:
[Customer_name, Phone_number, City]
Write the following user defined functions to perform given operations on
the stack named ‗status‘:
(i) Push_element() - To Push an object containing name and Phone number
of customers who live in Goa to the stack
(ii) Pop_element() - To Pop the objects from the stack and display them.
Also, display ―Stack Empty‖ when there are no elements in the stack.
For example:
If the lists of customer details are:
ANSWER:
cust = [
["Ashok","9999999999","Goa"],
["Avinash", "8888888888","Mumbai"],
["Mahesh","77777777777","Cochin"],
["Rakesh", "66666666666","Goa"]
]
status = []
def push_element():
for i in range(len(cust)):
if cust[i][2] == "Goa":
customer = cust[i][0],cust[i][1]
status.append(customer)
def pop_element():
for i in range(len(status)):
print(status.pop())
if len(status) == 0:
print("Stack Empty")
push_element()
pop_element()
Q.No Questions
1 Which of the following statements are True
(a) When you open a file for reading, if the file does not exist, an error occurs
(b) When you open a file for writing, if the file does not exist, a new file is created
(c) When you open a file for writing, if the file exists, the existing file is overwritten
with the new file
(d) All of the mentioned
2 Write a statement to send the file pointer position 10 bytes forward from
current location of file , consider fp as file object.
a) fp.seek(10) b) fp.seek(10,1) c) fp.tell(10) d) fp.seek(1,10)
3 Which of the following mode in the file opening statement creates a new
file if the file does not exist?
(a) r+ (b) w+ (c) a+ (d) Both (b) and (c)
4 The correct statement to place the file handle fp1 to the 10th byte from the
current position is:
(a) fp1.seek(10) (b) fp1.seek(10, 0) (c) fp1.seek(10, 1) (d) fp1.seek(10, 2)
5 The command used to skip a row in a CSV file is
A. next() B. skip() C. omit() D. bounce()
6 To read the next line from the file object fob, we can use:
a)fob.read(2) b) fob.read( ) c) fob.readline( ) d) fob.readlines( )
7 Which of the following statements is incorrect regarding the file access
modes?
a. ‘r+’ opens a file for both reading and writing. File object points to its
beginning.
b. ‘w+’ opens a file for both writing and reading. Overwrites the
existing file if it exists and creates a new one if it does not exist.
c. ‘wb’ opens a file for reading and writing in binary format. Overwrites
the file if it exists and creates a new one if it does not exist.
d. ‘a’ opens a file for appending. The file pointer is at the end of the file if
the file exists.
8 Out of the following file mode which opens the file and delete all its
contents and place the file pointer at the beginning of the file.
(a) a (b) w (c) r (d) a+
9 Which of the following statement is not correct?
(a) We can write content into a text file opened using ‘w’ mode
(b) We can write content into a text file opened using ‘w+’ mode
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 85 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
(c) We can write content into a text file opened using ‘r’ mode
(d) We can write content into a text file opened using ‘r+’ mode
10 Which of the following command is used to open a file “c:\pat.dat” for
writing as well as reading in binary format only?
(a) fout=open(“c:\pat.dat”,”w”) (b) fout=open(“c:\\pat.dat”,”wb”)
(c) fout=open(“c:\pat.dat”,”w+”) (d) fout=open(“c:\pat.dat”,”wb+”)
11 The readlines() method returns
a) str b) a list of lines c) a list of single characters d) a list of integers
12 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()
13 The default file open mode is-----------mode
a)r b)r+ c)w d)a
14 A text file “student.txt'' is stored on a computer. Identify the correct
option out of the following options to open the file for reading
i. myfile = open('student.txt','r+')
ii. myfile = open('student.txt','r')
iii. myfile = open('student.txt','rb')
iv. myfile = open('student.txt')
(a) (i), (ii) and (iv) (b) (ii) and (iv) (c) (ii),(iii) and (iv) (d) (i), (ii) and (iii)
15 Suppose the content of Python.txt file is
I am studying Python programming.
What will be the output of the following Python code?
f=open('Python.txt')
f.seek(12)
print(f.read(8))
(a) ng Python (b)g Python p (c) ng Pytho (d) g Python
16 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.
17 Which of the following is not a function/method of a file object in python?
a.read( ) b.writelines( ) c.dump( ) d.readlines( )
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 86 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
18 Which of the following options can be used to read the first line of a text
file “Myfile.txt”?
(A) myfile = open(‘Myfile.txt’); myfile.read()
(B) myfile = open(‘Myfile.txt’,’r’); myfile.read(n)
(C) myfile = open(‘Myfile.txt’); myfile.readline()
(D) myfile = open(‘Myfile.txt’); myfile.readlines()
19 Which of the following commands can be used to read “n” number of
characters from a file using the file object <file>?
a) read(n) b) n = file.read() c) file.readline(n) d) file.readlines()
20 Write the output of the following code
fout=open("story.txt","w")
fout.write("Welcome Python")
fout.seek(5)
print(fout.tell( ))
fout.close( )
Answer : 5
21 The correct syntax of read() function from text files is:
a. file_object.read() b. file_object(read) c. read(file_object) d.
file_object().read
22 Which of the following are the modes of both writing and reading in
binary format in file?
a) wb+ b) w c) w+ d) wb
23 A text file student.txt is stored in the storage device. Identify the correct
option out of the following options to open the file in read mode.
i. myfile = open('student.txt','rb')
ii. myfile = open('student.txt','w')
iii. myfile = open('student.txt','r')
iv. myfile = open('student.txt')
a) only i b) both i and iv c) both iii and iv d) both i and iii
24 Which of the following command is used to open a file “c:\temp.txt” in
read mode only?
a) infile = open(“c:\temp.txt”, “r”)
b) infile = open(“c:\\temp.txt”, “r”)
c) infile = open(file = “c:\temp.txt”, “r+”)
d) infile = open(file = “c:\\temp.txt”, “r+”)
25 To print 4th line from text file, which of the following statement is true?
a) dt = f.readlines()
print(dt[3])
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 87 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
b) dt=f.read(4)
print(dt[3])
c) dt=f.readline(4)
print(dt[3])
d) All of these
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 88 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Solution:
def display():
f=open(“quotes.txt”,”r”)
lines=f.readlines()
print(“total number of lines=”,len(lines))
f.close()
display()
3 Write a function in Python to count the number of lines in a text file
‘STORY.TXT’ which is starting with an alphabet ‘A’.
Solution :
Solution :
def reverse(0:
fobj=open(“input.txt”,”r”)
fobj1=open(“output”,”w”)
line=fobj.readlines()
for i in line:
revline=I[::-1]
fobj.write(revline)
fobj.close()
fobj1.close()
revline()
8 Write a function countmy( ) in python to read the text file “DATA.TXT”
and count the number of times “my” occurs in the file.
For example if the file “DATA.TXT” contains:
“This is my website. I have displayed my preferences in the CHOICE
section”
The countmy( ) function should display the output as : “my occurs 2 times”
Solution:
def countmy(0:
f=open(“data.txt”,”r”)
count=0
x=f.read()
word=x.split()
for i in word:
if i ==”my”:
count+=1
print(“my occurs “,count, “times”)
f.close()
countmy()
9 Write a method/function DISPLAYWORDS() in python to read lines
from a text file STORY.TXT,and display those words, which are less than 4
Characters.
Solution :
def BIGWORDS():
f=open(“INDIA.TXT”,”r”)
lines=f.readlines()
count=0
for l in lines:
line=l.split()
for word in line:
if len(word) >= 5:
count+=1
print(“Number of words= “,count)
f.close()
BIGWORDS()
16 Write a program to count the words “to” and “the” present in a text file
“python.txt”
Solution :
def counttothe(0:
f=open(“data.txt”,”r”)
count=0
x=f.read()
word=x.split()
for i in word:
if i ==”to” or i==”the”:
count+=1
print(“The words to and the occurs “,count, “times”)
f.close()
counttothe()
17 Write a method SHOWLINES() in Python to read lines from text file
‗TESTFILE.TXT‘ and display the lines which do not contain 'ke'.
Example: If the file content is as follows:
An apple a day keeps the doctor away.
Solution :
def countrec():
fobj=open(“STUDENT.DAT”,”rb”)
try:
while True:
rec=pickle.load(fobj)
if rec[3] > 75:
print(rec)
count+=1
except EOFError:
fobj.close()
print(“Number of Records = “,count)
# main program
countrec()
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 record and
add to Book.dat
(ii) Write a function Countrec(Author) in python which accepts the Author
name as parameter and count and return number of books by the given
Author are stored in the binary file “Book.dat”
Solution :
# creation program
def createfile():
fobj=open(“book.dat”,”wb”)
while True:
bno=input(“Enter book number”)
bname=input(“Enter book name”)
authorname=input(“enter Author name”)
# accessing program
def countrec(author):
fobj=open(“book.dat”,”rb”)
try:
while True:
rec=pickle.load(fobj)
if rec[2] == author:
print(rec)
count+=1
except EOFError:
fobj.close()
print(“Number of Records = “,count)
# main program
au=input(“Enter authors name to be found”)
countrec(au)
3 Considering the following definition of dictionary MULTIPLEX, 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".
MULTIPLEX = {'MNO': _____, 'MNAME": _____, 'MTYPE': _____}
Solution :
def search():
fobj=open(“CINEMA.DAT”,”rb”)
try:
while True:
MULTIPLEX=pickle.load(fobj)
if MULTIPLEX[‘MTYPE’] ==”COMEDY”:
print(MULTIPLEX)
except EOFError:
# main program
search()
4 A binary file “vehicle.dat” has structure [RegNo, Type, Make, Year].
a. Write a user defined function AddVahan() to input data for a vehicle
and add to “vehicle.dat” file.
b. Write a function CountVahan(Type) in Python which accepts the
Type of the vehicle as the parameter and count and return the
number of vehicles of the given Type.
Solution :
# creation program
def AddVahan():
fobj=open(“vehicle.dat”,”wb”)
while True:
regno=input(“Enter register number”)
type=input(“Enter type”)
make=input(“enter make”)
year=input(“Enter year”)
rec=[regno,type,make,year]
pickle.dump(rec,fobj)
ch=input(“enter choice”)
if ch in “Nn”:
break
fobj.close()
# main program
AddVahan()
# accessing program
def CountVahan():
fobj=open(“vehicle.dat”,”rb”)
try:
vt=input(“enter vehicle type”)
while True:
rec=pickle.load(fobj)
if rec[1] == vt:
Solution :
# creation program
def createfile():
fobj=open(“emp.dat”,”wb”)
while True:
ecode=input(“Enter Employee code”)
ename=input(“Enter employee name”)
salary=int(input(“Enter salary”))
rec=[ecode,ename,salary]
pickle.dump(rec,fobj)
ch=input(“enter choice”)
if ch in “Nn”:
break
fobj.close()
# main program
createfile()
# accessing program
def countrec():
fobj=open(“emp.dat”,”rb”)
try:
while True:
rec=pickle.load(fobj)
print(rec)
except EOFError:
fobj.close()
# main program
countrec()
6 A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].
a) Write a user defined function CreateFile() to input data for a record and
add to Book.dat file.
b) 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 are stored in the binary file “Book.dat”
Solution :
[Repeated question ]
7 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.
Solution :
# creation program
def createfile():
fobj=open(“toy.dat”,”wb”)
while True:
tid=input(“Enter toy number”)
tname=input(“Enter toy name”)
status=input(“enter status”)
price=int(input(“Enter price”))
rec=[tid,tname,status,price]
pickle.dump(rec,fobj)
ch=input(“enter choice”)
if ch in “Nn”:
break
fobj.close()
# main program
createfile()
# accessing program
def OnOffer():
except EOFError:
fobj.close()
# main program
countrec()
8 i. A binary file “ITEMS.DAT” has structure (ID, GIFT, Cost). Write a function
to write more items in ITEMS.DAT
ii. Write a function Economic() in Python that would read contents of the file
“ITEMS.DAT” and display the details of those ITEMS whose cost is greater
then 2500.
Solution :
# creation program
def createfile():
fobj=open(“ITEMS.DAT”,”wb”)
while True:
id=input(“Enter id number”)
gift=input(“Enter gift”)
cost=int(input(“enter cost”))
rec=[id,gift,cost]
pickle.dump(rec,fobj)
ch=input(“enter choice”)
if ch in “Nn”:
break
fobj.close()
# main program
createfile()
# accessing program
except EOFError:
fobj.close()
# main program
economic()
9 Tarun is a student, who wants to make a python program for Sports
Department . He is using binary
file operations with the help of two user defined functions/modules.
(A) New_Entry() to create a binary file called SPORTS.DAT containing sports
related material information- item_id, item_name and item_qty.
(B) Show_Item() to display the item _name and item_qty of items which
item_qty less than 5. In case there is no item available that which quantity is
less than 5 the function displays message.
Solution :
# creation program
def New_Entry():
fobj=open(“SPORTS.DAT”,”wb”)
while True:
itemid=input(“Enter Item Id”)
itemname=input(“Enter item name”)
itemqty=input(“enter quantity”)
rec=[itemid,itemname,itemqty]
pickle.dump(rec,fobj)
ch=input(“enter choice”)
if ch in “Nn”:
break
fobj.close()
# main program
New_Entry()
# accessing program
def Show_item():
fobj=open(“SPORTS.DAT”,”rb”)
try:
while True:
rec=pickle.load(fobj)
if rec[2] < 5:
print(rec[1],rec[2])
except EOFError:
fobj.close()
# main program
Show_item()
# accessing program
def access():
fobj=open(“record.csv”,”r”,newline=’’)
ro=csv.reader(fobj,delimiter=’,’)
count=0
for i in ro:
count+=1
print(“Number of records = “,count)
fobj.close()
# main program
access()
SOLUTION :
# creation program
def add():
fobj=open(“toydata.csv”,”w”, newline=’’)
wo=csv.writer(fobj,delimiter=”,”)
while True:
tid=input(“enter toy id”)
tname=input(“enter toy name”)
tprice=ini(input(“enter price”))
rec=[tid,tname,tprice]
wo.writerow(rec)
ch=input(“enter choice”)
if ch==’Nn’:
break
# main program
add()
# accessing program
def search():
fobj=open(“record.csv”,”r”,newline=’’)
ro=csv.reader(fobj,delimiter=’,’)
for i in ro:
if i[2] > 500:
print(i)
fobj.close()
# main program
access()
3 Write a Program in Python that defines and calls the following user defined
functions:
(i) update() – To accept and update data of a student to a CSV file ‘mark.csv’.
4 Write the functions to performthe required operations on csv files and call the
functions appropriately.
i) Newgadget() to add the details of new gadgets in csv file gadget.csv which
stores records in the format.Deviceno,name,price,brand Get the input from
the user.
ii) Countgadget() to read the csv file ‘gadget.csv’ and count the devices whose
brand is “Samsung”
SOLUTION :
# creation program
def Newgadget():
fobj=open(“gadget.csv”,”w”, newline=’’)
wo=csv.writer(fobj,delimiter=”,”)
while True:
dno=input(“enter device number”)
name=input(“enter device name”)
price=ini(input(“enter price”))
brand=input”Enter brand name”)
rec=[dno,name,price,brand]
# accessing program
def Countgadget():
fobj=open(“gadget.csv”,”r”,newline=’’)
ro=csv.reader(fobj,delimiter=’,’)
for i in ro:
if i[3] == “samsung”:
count+=1
print(“Total count =”,count)
fobj.close()
# main program
Countgadget()
5 Write the functions to perform the required operations on csv files and call
the functions appropriately.
i) Namelist() to add the participants for Music competition in a csv file
“music.csv” where each record has the format Name,class,age
ii) Display() to read the csv file ‘music.csv’ and display the participants under
15 years of age
Solution :
# creation program
def Namelist():
fobj=open(“music.csv”,”w”, newline=’’)
wo=csv.writer(fobj,delimiter=”,”)
while True:
name=input(“enter toy name”)
class=input(“enter class”)
age=int(input(“enter age”))
rec=[name,class,age]
wo.writerow(rec)
ch=input(“enter choice”)
# accessing program
def display():
fobj=open(“music.csv”,”r”,newline=’’)
ro=csv.reader(fobj,delimiter=’,’)
for i in ro:
if i[2] < 15:
print(i)
fobj.close()
# main program
display()
6 Write a Program in Python that defines and calls the following user defined
functions:
(i) ADD_PROD() – To accept and add information about a product
into a csv file named ‘product.csv’. Each record consists of prodname and
price to store product name and price of the product
(ii) DISPLAY_PROD() – To display details of products having price
more than 100 present in the CSV file named ‘product.csv’.
SOLUTION :
# creation program
def ADD_PROD():
fobj=open(“product.csv”,”w”, newline=’’)
wo=csv.writer(fobj,delimiter=”,”)
while True:
pname=input(“enter product name”)
price=int(input(“enter price”))
rec=[pname,price]
wo.writerow(rec)
ch=input(“enter choice”)
if ch==’Nn’:
break
# main program
# accessing program
def DISPLAY_PROD():
fobj=open(“product.csv”,”r”,newline=’’)
ro=csv.reader(fobj,delimiter=’,’)
for i in ro:
if i[1] > 100:
print(i)
fobj.close()
# main program
DISPLAY_PROD()
7 Write a program in Python that defines and calls the following user defined
functions:
i. Add(): to add the record of a student to a csv file “record.csv”. Each record
should be with field elements [admno,sname,class]
ii. Count(): to count the number of students studying in class 12
SOLUTION :
# creation program
def ADD():
fobj=open(“record.csv”,”w”, newline=’’)
wo=csv.writer(fobj,delimiter=”,”)
while True:
admno=int(input(“Enter admission number”))
sname=input(“enter student name”)
class=input(“enter class”)
rec=[admno,sname,class]
wo.writerow(rec)
ch=input(“enter choice”)
if ch==’Nn’:
break
# main program
ADD()
# accessing program
def COUNT():
SOLUTION :
# creation program
def ADD():
fobj=open(“animal.csv”,”w”, newline=’’)
wo=csv.writer(fobj,delimiter=”,”)
while True:
name=input(“enter animal name”)
type=input(“enter animal type”)
food=input(“enter anima food”))
rec=[name,type, food]
wo.writerow(rec)
ch=input(“enter choice”)
if ch==’Nn’:
break
# main program
ADD()
# accessing program
def search():
fobj=open(“animal.csv”,”r”,newline=’’)
ro=csv.reader(fobj,delimiter=’,’)
SOLUTION :
# creation program
def insertData():
fobj=open(“customerdata.csv”,”w”, newline=’’)
wo=csv.writer(fobj,delimiter=”,”)
while True:
cname=input(“enter customer name”)
mno=input(“enter mobile number”)
dop=input(“enter Date of purchase”)
Itempur=input(“item purchased”)
rec=[cname,mno,,dop,itempur]
wo.writerow(rec)
ch=input(“enter choice”)
if ch==’Nn’:
break
# main program
insertData()
# accessing program
def frequency():
fobj=open(“customerdata.csv”,”r”,newline=’’)
ro=csv.reader(fobj,delimiter=’,’)
SOLUTION :
# creation program
def AddNewRec():
fobj=open(“CAPITAL.csv”,”w”, newline=’’)
wo=csv.writer(fobj,delimiter=”,”)
while True:
country=input(“enter country name”)
capital=input(“enter capital name”)
rec=[country,capital]
wo.writerow(rec)
ch=input(“enter choice”)
if ch==’Nn’:
break
# main program
AddNewRec()
# accessing program
def showrec():
fobj=open(“CAPITAL.csv”,”r”,newline=’’)
SOLUTION :
# creation program
def Namelist():
fobj=open(“music.csv”,”w”, newline=’’)
wo=csv.writer(fobj,delimiter=”,”)
while True:
name=input(“enter toy name”)
class=input(“enter class”)
age=int(input(“enter age”))
rec=[name,class,age]
wo.writerow(rec)
ch=input(“enter choice”)
if ch==’Nn’:
break
# main program
Namelist()
# accessing program
def display():
fobj=open(“music.csv”,”r”,newline=’’)
ro=csv.reader(fobj,delimiter=’,’)
for i in ro:
SOLUTION :
# creation program
def add():
fobj=open(“file_stud.csv”,”w”, newline=’’)
wo=csv.writer(fobj,delimiter=”,”)
while True:
admnno=int(input(“enter admission number”))
sname=input(“enter student name”)
perage=int(input(“enter percentage”))
rec=[admnno,sname,perage]
wo.writerow(rec)
ch=input(“enter choice”)
if ch==’Nn’:
break
# main program
add()
# accessing program
def search():
fobj=open(“file_stud.csv”,”r”,newline=’’)
ro=csv.reader(fobj,delimiter=’,’)
for i in ro:
if i[2] > 75
print(i)
14 Write a Program in Python that defines and calls the following user
definedfunctions:
(i) ADD() – To accept and add data of an item to a csv file „events.csv‟. Each
record of the file is a list [Event_id, Description, Venue, Guests, Cost].
Event_Id, Description, and venue are of str type, Guests and Cost are of int
type.
(ii) COUNTR() – To read the data from the file events.csv, calculate and
display the average number of guests and average cost.
SOLUTION :
# creation program
def ADD():
fobj=open(“events.csv”,”w”, newline=’’)
wo=csv.writer(fobj,delimiter=”,”)
while True:
eid=input(“Enter event id”)
desc=input(“Enter Description”)
venue=input(“enter venue”)
guests=int(input(“enter number of guests”))
cost=int(input(“Enter cost”))
rec=[eid,desc,venue,guests,cost,]
wo.writerow(rec)
ch=input(“enter choice”)
if ch==’Nn’:
break
# main program
# accessing program
def COUNTR():
fobj=open(“events.csv”,”r”,newline=’’)
ro=csv.reader(fobj,delimiter=’,’)
for i in ro:
n=n+1
tot=tot+guests
totcost=totcost+cost
avggue= tot /n
avgcost=totcost/n
print(‘Average guest =”,avggue)
print(“Average cost = “,avgcost)
fobj.close()
# main program
COUNTR()
Q.No Questions
Write the full form of the following:
1 ARPANET - ADVANCE RESEARCH PROJRCT AGENCY NETWORK
2 WWW - WORLD WIDE WEB
3 PAN - PERSONAL AREA NETWORK
4 LAN - LOCAL AREA NETWORK
5 MAN - METROPOLITAN AREA NETWORK
6 WAN - WIDE AREA NETWORK
7 WLAN - WIRELESS LOCAL AREA NETWORK
8 USB - UNIVERSAL SYSTEM BUS
9 WPAN - WIRELESS PERSONAL AREA NETWORK
10 WI-FI - WIRELESS FIDELITY
11 MBPS - MEGABITS PER SECOND
12 HTTP - HYPER TEXT TRANSFER PROTOCOL
13 IETF - INTERNET ENGINEERING TASK FORCE
14 W3C - WORLD WIDE WEB CONSORTIUM
15 TCP - TRANSMISSION CONTROL PROTOCOL
16 HTML - HYPER TEXT MARKUP LANGUAGE
17 XML - EXTENSIBLE MARKUP LANGUAGE
18 FTP - FILE TRANSFER PROTOCOL
19 PPP - POINT TO PONT PROTOCOL
20 ISP - INTERNET SERVICE PROVIDER
21 SMTP - SIMPLE MAIL TRANSFER PROTOCOL
22 POP3 - POST OFFICE PROTOCOL
23 IMAP - INTERNET MESSAGING ACCESS PROTOCOL
24 IP - INTERNET PROTOCOL
25 HTTPS - HYPER TEXT TRANSFER PROTOCOL SECURE
26 TELNET - TERMINAL NETWORK
27 VOIP - VOICE OVER INTERNET PROTOCOL
28 MODEM - MODULATOR DEMODULATOR
29 NIC -NETWORK INTERFACE CARD
30 MAC - MEDIA ACCESS CONTROL
31 RJ 45 - REGISTERED JACK-45
32 OUI - ORGANISATIONAL UNIQUE IDENTIFIER
33 URI – UNIFORM RESOURCE IDENTIFIER
34 URL - UNIFORM RESOURCE LOCATOR
35 DNS - DOMAIN NAME SYSTEM
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 119 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
36 UTP - UNSHIELDED TWISTED-PAIR
37 STP - SHIELDED TWISTED-PAIR
38 VPN - VIRTUAL PRIVATE NETWORK
Difference Between Questions
39 Bus topology star topology
Linear in nature Non-linear in nature
Requires more cables Requires less cables
Connected by Hub Connected to single cable
40 XML HTML
User Defined Tags Pre Defined Tags
41 HTTP FTP
It is a communication protocol for It allows transferring of files from
the transfer of information on the one system to another like
internet and the worldwide web. uploading of file from local
machine to web server using FTP
client.
HTTP is a request / response
standard between a client and a
server.
42 LAN WAN
These are computer networks These are the networks spread
confined to a localised area such as over large distances, say across
an office or a factory. countries or even continents.
It can include a group of LAN’s
connected together.
43 HTTP SMTP
It is a communication protocol for SMTP is a set of guidelines that
the transfer of information on the allows software to transmit
internet and the worldwide web. electronic mail over the internet.
HTTP is a request / response It sends the messages to other
standard between a client and a users based on email address.
server.
44 BRIDGE ROUTER
A bridge is a device that lets you A device that works like a bridge
link two networks together. but can handle different protocols.
Bridges are smart enough to know
which computers are on which
side of the bridge.
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 120 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Bridges can handle networks that
follow same protocols.
45 SWITCH ROUTER
A switch is a device that is used to A device that works like a bridge
segment to different networks or but can handle different protocols
LAN segments.
A switch is a smart device which
identifies the intended destination
and send it to only the target
computers.
46 WEB SERVER WEB BROWSER
A web server is a server that A web browser is a www client
responds to the requests made by that navigates through the World
web browser. Wide Web and display pages.
47 Hub switch
A hub is a hardware device used to A switch is a device that is used to
connect several computers segment to different networks or
together. LAN segments.
It has multiple ports to connect A switch is a smart device which
multiple computers. identifies the intended destination
and send it to only the target
computers.
48 Domain name URL
An internet address which is A URL specifies the distinct
character based is called a domian address for each resource on the
name. internet,
49 WEB PAGE Web site
A single page in a website is called A collection of related web pages is
as the webpage. called a web site.
50 Circuit switching Packet switching
The complete end-to-end In this switching technique fixed
transmission path between the size of packet can be transmitted
source and the destination is across the network.
established and then the message
is transmitted through the path.
Guaranteed delivery of the
message.
Mostly used for voice
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 121 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
communication.
51 Coaxial cable Fiber optic cable
Data transmission rate is better It is highly suitable for harsh
than twisted pair cables. industrial environments.
It provides cheap means of It guarantees secure transmission
transporting multi-channel and has a very transmission
television. capacity.
Signals around metropolitan areas. It is used for broad band
transmission.
52 Twisted pair cable Fiber optic cable
It is easy to install and maintain. It is highly suitable for harsh
industrial environments.
It is very expensive. It guarantees secure transmission
and has a very transmission
capacity.
It is physically flexible. It is used for broad band
transmission.
53 Radio waves Micro waves
Radio waves are omnidirectional Microwave is a part of the
electromagnetic Spectrum.
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 123 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Q.No Questions
1 Fill in the Blank:
______________ is a communication methodology designed to deliver
both voice and multimedia communications over internet protocol
(a) SMTP (b) VoIP (c) HTTP (d) PPP
2 Which of the following is transmission medium for TV remotes?
(a) Infrared (b) Coaxial cable (c) Bluetooth (d)Microwave
3 Which of the following devices will connect both source and destination
computer.
(a) HUB (b) SWITCH (c) MODEM (d) ROUTER
4 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
5 Fill in the blank:
________ is the protocol used for transferring files from one machine to
another.
a) HTTP b) FTP c) SMTP d) VOIP
6 MAC address is of ___________
a) 24 bits b) 36 bits c) 42 bits d) 48 bits
7 TCP/IP stands for
a) Transmission Communication Protocol / Internet Protocol
b) Transmission Control Protocol / Internet Protocol
c) Transport Control Protocol / Interwork Protocol
d) Transport Control Protocol / Internet Protocol
8 ______is a standard network protocol used to transfer files from one host
to another host over a TCP- based network, such as the Internet.
a) TCP b) IP c) FTP d) SMTP
9 ___________ is a protocol that allows to send/upload email message from
local computer to an email server
10 Which of the following is /are email protocols?
(a) TCP (b) IP (c) SMTP (d) POP
11 A network device used to divide a single computer network into various
subnetworks .
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 124 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
i)router ii)switch iii)hub
12 Ms. Priya is an IT expert. She recently used her skills to access the Admin
password for the network server of Happiest Minds Technology Ltd. and
provided confidential data of the organization to its CEO, informing him
about the vulnerability of their network security. Out of the following
options which one most appropriately defines Ms. Priya?
a) Cracker b) Operator c) Hacker d) Network Admin
13 Name the transmission media best suitable for difficult terrain like hilly
Areas Radio Waves
14 Which of the following network device is a broadcasting device
a)switch b)hub c)gateway d)router
15 If all devices are connected to a central hub, then topology is called
a)tree topology b)bus topology c)star topology d)ring topology
16 —-- protocol is used when we browse different web pages of a website.
(a) SMTP (b) VoIP (c) HTTP (d) POP3
17 Which type of network (out of LAN, PAN and MAN) is formed, when
you connect two mobiles using Bluetooth to transfer a video?
18 A distributed network configuration in which all data/information pass
through a central computer is star network:
a)ring b)bus c)star d)mesh
19 Rearrange the following terms in increasing order of speedy medium of
data transfer.
Telephone line, Fiber Optics, Coaxial Cable, Twisted Paired Cable
Answer : Telephone line, Coaxial Cable, Twisted Paired Cable, Fiber
optics
20 Fill in the blank:
________ protocol is used to send mail.
(a) SMTP (b) FTP (c) POP (d) HTTPS
21 ________________ is the networking device that connects computers in a
network by using packet switching to receive, and forward data to the
destination.
a) Switch b)Hub c) Repeater d) Router
22 In specific, if the systems use separate protocols, which one of the
following devices is used to link two systems?
a) Repeater b) Gateway c) Bridge d) Hub
23 Switch is a ________________
A. Broadcast device B. Unicast device C. Multicast device D. None of the
above
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 125 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
24 Your school has four branches spread across the city. A computer
network created by connecting the computers of computer labs of all the
school branches, is an example of _________.
(a) LAN (b) MAN (c) WAN (d) PAN
25 Central computer which is powerful than other computers in the network
is called
a) Hub b) Sender c) Switch d) Server
26 Fill in the blank:
SMTP is the protocol used to send emails to the e-mail server and POP is
the protocol used to download mail to the client computer from the
server.
(a) SMTP,POP (b) HTTP,POP (c) FTP,TELNET (d) HTTP,IMAP
27 Which portion of the URL below records the directory or folder of the
desired resource?
https://www.nishantsingh.com/ghagwal/pgt.htm
a) http b) ghagwal c) www.nishantsingh.com d) pgt.htm
28 The Repeater is a networking device that regenerates or recreates a
weak signal into its original strength and form.
29 Danish has to share the data among various computers of his two offices
branches situated in the same city. Name the type of network which is
being formed in this process. LAN / MAN
30 A________is a set of rules that governs data communication.
(A) Forum (B) Protocol (C) Standard (D) None of the above
31 A device that forwards data packet from one network to another is called
a _________
(a) Bridge (b) Router (c) Hub (d) Gateway
32 Which of the following is used to receive emails over Internet?
a) SMTP b) POP c) PPP d) VoIP
33 What is the size of IPv4 address?
(a)32 bits (b) 64 bits (c) 64 bytes (d) 32 bytes
34 Which switching technique follows the store and forward mechanism?
(a) Circuit switching (b) message switching
(c) packet switching (d) All of these
35 Which protocol is used for transferring files over a TCP/IP network?
a) FTP b) SMTP c) PPP d) HTTP
36 Fill in the blank:
The _________________ is a mail protocol used to retrieve mail from a
remote server to a local email client.
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 126 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
(a) VoIP (b)POP3 (c) PPP (d) HTTP
37 Identify the device on the network which is responsible for forwarding
data from one device to another
(a) NIC (b) Router (c) RJ45 (d) Repeater
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 127 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Q.No Questions
2 MyPace University is setting up its academic blocks at Naya Raipur and is
planning to set up a network. The University has 3 academic blocks and
one Human Resource Center as shown in the diagram
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 128 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
3 Alpha Pvt Ltd is setting up the network in Chennai. There are four
blocks- Block A, Block B, Block C & Block D
i)Suggest the most suitable block to place the server with a suitable
reason. Block A
ii) Suggest the cable layout for connections between the various blocks.
iii) Suggest the placement of following devices with justification:
(a) Switch/Hub (b) Repeater
iv)The organization is planning to link its front office situated in the city
in a hilly region where cable connection is not possible. Suggest an
economic way to connect with reasonably high speed. Radiowave.
v) Out of following which type of Network it is LAN,MAN,WAN .WAN
4 Python University is setting up its academic blocks at Chennai and is
planning to set up a network. The University has 3 academic blocks and
one Human Resource Center as shown in the diagram below:
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 129 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 130 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
campus at Gurgaon for their day-to-day office and web-based activities.
They are planning to have connectivity between three buildings and the
head office situated in Mumbai. Answer the questions (i) to (iv) after
going through the building positions in the campus and other details,
which are given below : The given building blocks are named as Green,
Blue and Red
i. Suggest the most suitable place (i.e., building) to house the server of this
organization. Also give a reason to justify your suggested location.
Building RED. The most suitable place to install server is building “RED” because
this building have maximum computer which reduce communication delay.
ii. Suggest the placement of the following devices with justification:
a. Repeater - Since the cabling distance between buildings GREEN, BLUE and RED
are quite large, so a repeater each, would ideally be need along their path to avoid
loss of signals during the course of data flow in there routes.
b. Switch - In the layout a switch each, would be needed in all the buildings, to
interconnect the group of cables from the different computers in each building.
iii. Suggest a cable layout of connections between the buildings inside the
campus.
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 131 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
iv. The organization is planning to provide a high speed link with its head
office situated in Mumbai using a wired connection. Which of the
following cables will be most suitable for this job.
• Optical Fiber
• Co-axial Cable
• Ethernet Cable
v. While connecting the devices two modems are found to be defected.
What is the function of modem?
Modem converts digital signals to analog signals at one end and vice
versa at the other end.
6 Uplifting Skills Hub India is a knowledge and skill community which has
an aim to uplift the standard of knowledge and skills in the society. It is
planning to setup its training centers in multiple towns and villages pan
India with its head offices in the nearest cities. They have created a model
of their network with a city, a town and 3 villages as follows. As a
network consultant, you have to suggest the best network related
solutions for their issues/ problems raised in (a) to (d) keeping in mind
the distances between various locations and other given parameters.
Shortest distances between various locations:
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 132 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Note:
In Villages, there are community centers, in which one room has been
given as training center to this organization to install computers. The
organization has got financial support from the government and top IT
companies.
(a) Suggest the most appropriate location of the SERVER in the B_HUB
(out of the 4 locations), to get the best and effective connectivity. Justify
your answer. B_Town
(b) Suggest the best wired medium and draw the cable layout (location to
location) to efficiently connect various locations within the B_HUB.
Answer : Coaxial cable
(c) Which hardware device will you suggest to connect all the computers
within each location of B_HUB? Switch
(d) Which service/protocol will be most helpful to conduct live
interactions of Experts from Head Office and people at all locations of
B_HUB. VOIP
(e) Which type of network would be formed if B_HUB is connected to
their A_city. Wide Area Network
7 University of Correspondence in Allahabad is setting up the network
between its different wings (units). There are four wings named as
Science(S), Journalism(J), Arts(A) and Home Science(H).
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 133 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
(a) Suggest the suitable topology and draw the cable layout to efficiently
connect various blocks / wings of network. Star Topology
(b) Where should the server be housed ? justify your answer.
Wing A
(c) What kind of network (LAN/MAN/WAN) will be formed? LAN
(d) Suggest the fast and very effective wired communication medium to
connect another sub office at Kanpur, 670 km far apart from above
network.
(e) Suggest the placement of the following devices in the network.
i. Hub/ Switch
ii. Repeater
8 A professional consultancy company is planning to set up new offices in
India with its hub at Chennai. As a network adviser, you have to
understand their requirements and suggest to them the best available
solutions.
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 134 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
(a) Suggest the most appropriate block where the organization should
plan to install their server? Human Resources
(b) Draw a block-to-block cable layout to connect all the buildings in the
most appropriate manner for efficient communication.
(c) What will be the best possible connectivity out of the following to
connect the new set-up of offices in Chennai with its London base office?
(i) Infrared (ii) Satellite Link (iii) Ethernet Cable
(d) Which of the following devices will you suggest to connect each
computer in each of the above buildings?
(i) Gateway (ii) Switch (iii) Modem
(e ) Suggest a device/software to be installed for data security in the
campus. Firewall
9 Learn Together is an educational NGO. It is setting up its new campus at
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 135 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Jabalpur for its web-based activities. The campus has four compounds as
shown in the diagram below:
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 136 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
(a) Telephone analog line (b) Optical fibre (c) Ethernet cable.
(v) Suggest a device / software to be installed in the Jabalpur campus to
take care of data security. Firewall
10 Bias Methodologies is planning to expand their network in India, starting
with three cities in India to build infrastructure for research and
development of their chemical products. The company has planned to set
up their main office in Pondicherry at three different locations and have
named their offices as Back Office, Research Lab and Development Unit.
The company has one more research office namely Corporate Unit in
Mumbai. A rough layout of the same is as follows:
(i) Suggest the type of network required (out of LAN, MAN, WAN) for
connecting each of the following office units.
Research Lab and Back Office - LAN
Research Lab and Development Unit. - MAN
(ii) Which one of the following device, will you suggest for connecting all
the computers with in each of their office units?
Switch/Hub
Modem
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 137 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Telephone
(iii) (a) Which of the following communication medium will you suggest
to be procured by the company for connecting their local office units in
Pondicherry for very effective (high speed) communication?
Telephone cable
Ethernet cable
Optical fibre
(iv) Which building is suitable to install the server with suitable reason?
Research Lab
(v) Suggest a cable/wiring layout for connecting the company’s local
office units located in Pondicherry. Also, suggest an effective
method/technology for connecting the company’s office unit located in
Mumbai.
11 Indian School, in Mumbai is starting up the network between its different
wings. There are four Buildings named as SENIOR, JUNIOR, ADMIN
and HOSTEL as shown below:
(i) Suggest the most appropriate location of the server inside the
CHENNAI campus (out of the 4 buildings), to get the best connectivity
for maximum no. of computers. Justify your answer. ADMIN
(ii) Suggest the topology and draw the cable layout to efficiently connect
various buildings within the CHENNAI campus. Star topology
(iii) Which hardware device will you suggest to be procured by the
company to minimize the transmission loss? Switch
(iv) Which will be the most suitable wireless communication medium to
connect Chennai campus with its Delhi head office? Satellite link
(v) Which of the following will you suggest to establish the online face-
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 139 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
toface communication between the people in the Admin Office of
CHENNAI Campus and DELHI Head Office?
(a) Cable TV
(b) Email
(c) Video Conferencing
(d) Text Chat
13 Ionex Private Ltd. Patna has different divisions Marketing (A1), Sales
(A2), Finance (A3) and Production (A4). The company has another branch
in New Delhi. The management wants to connect all the divisions as well
as all the computers of each division (A1, A2, A3, A4) of Patna branch.
Distance between the divisions are as follows :
A3 to A1: 20 m
A1 to A2: 35 m
A2 to A4: 20 m
A4 to A3: 130 m
A3 to A2: 1000 m
A1 to A4: 190 m
The number of computers in each division is as follows :
A1: 50
A2: 40
A3: 110
A4: 60
Based on the above configurations, answer the following questions :
(i) Suggest the type of network (PAN, LAN, MAN, WAN) required to
connect the Finance (A3) division with the New Delhi branch by giving
suitable reasons. Wide Area Network
(ii) Suggest the placement of following devices (a) Switch (b) Repeater
(iii) Suggest the division which should be made server by quoting
suitable reasons. A3
(iv) The company wants to conduct an online video conference between
employees of the Patna and New Delhi branches. Name the protocol
which will be used to send voice signals in this conference. VOIP
(v) Suggest the topology and draw the most suitable cable layout for
connecting all the divisions of the Patna branch. Star topology
14 G. R.K International Inc. is planning to connect its Bengaluru Office Setup
with its Head Office in Delhi. The Bengaluru Office G.R.K. International
Inc. is spread across an area of approx. 1 square kilometres consisting of 3
blocks. Human Resources, Academics and Administration. You as a
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 140 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
network expert have to suggest answers to the four queries (i) to (v)
raised by them.
(i) Suggest the most suitable block in the Bengaluru Office Setup to host
the server. Give a suitable reason with your suggestion.
Human Resources.
(ii) Suggest the cable layout among the various blocks within the
Bengaluru Office Setup for connecting the blocks.
(iii) Suggest a suitable networking device to be installed in each of the
blocks essentially required for connecting computers inside the blocks
with fast and efficient connectivity. Switch
(iv) Suggest the most suitable media to provide secure, fast and reliable
data connectivity between Delhi Head Office and the Bengaluru Office
Setup. Satellite link
(v)Which type of network id formed between blocks of Bengaluru Office.
Local Area Network
15 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 three 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 (e) to
the authorities keeping in mind the distance and other given parameters.
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 141 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
a. Suggest the authorities, the cable layout amongst various blocks inside
university campus for connecting the buildings
b. Suggest the most suitable place (i.e. block) to house the server of this
university with a suitable reason. Academic Building
c. Suggest an efficient device from the following to be installed in each of
the blocks to connect all the computers Switch
d. Suggest the placement of a Repeater (if any) in the network with
justification.
e. Suggest the most suitable (very high speed) service to provide data
connectivity between Admission Building located in Delhi and the
campus located in Parampur. Microwave
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 142 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Q.No Questions
1 Which of the following will remove the primary key from MySQL table.
(a) remove (b) alter (c) drop (d) update
2 Which of the following is not an integrity constraint?
(a) Not null (b) Composite key (c) Primary key (d) Check
3 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
4 In the relational model, relationships among relations/table are created by
using _______ keys.
(a) composite (b) alternate (c) candidate (d) foreign
5 Which of the following is a DML command?
(a) SELECT (b) ALTER (c) CREATE (d) DROP
6 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
7 Fill in the blanks:
ALTER command is used to add a new column in the table in SQL
8 Which of the following will display all the tables in a database:
a) SELECT * FROM <tablename>;
b) DISPLAY TABLES;
c) SHOW TABLES;
d) USE TABLES;
9 Choose the correct option:
__________ is the number of columns in a table and ________ is the
number of rows in the table.
a) Cardinality, Degree b) Degree, Cardinality
c) Domain, Range d) Attribute, Tuple
10 The ORDER BY clause is used to display result of an SQL query in
ascending or descending order with respect to specified attribute values
11 Which function is used to display the sum of values in a specified
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 143 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
column ?
a) COUNT(column) b) TOTAL(column)
c) SUM(column) d) ADD(column)
12 To open a connector to the MySQL database, which statement is used to
connect with MySQL ?
a) connector b) connect c) password d) username
13 A database can have only one table(True/False)
14 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
15 Which is known as range operator in MySQL.
a) IN b) BETWEEN c) IS d) DISTINCT
16 Which of the following functions is used to find the largest value from the
given data in MySQL?
a) MAX ( ) b) MAXIMUM ( ) c) LARGEST ( ) d) BIG ( )
17 All aggregate functions except ___________ ignore null values in their
input collection.
a) Count (attribute) b) Count (*) c) Avg () d) Sum ()
18 Which of the following SQL commands will change the attribute value of
an existing tuple in a table?
(a) insert (b) update (c) alter (d) change
19 Fill in the blank:
An attribute or set of attributes in a table that can become a primary key is
termed as - --------------------
a) Alternate key b) Candidate key c) Foreign key d) Unique key
20 Fill in the blank:
The SELECT statement when combined with __________ clause, is used
for pattern matching
(a) Order by (b) distinct (c) like (d) between
21 Identify the invalid method to get the data from the result set of query
fetched by a cursor object mycursor.
a) mycursor.fetchone() b) mycursor.fetchall()
c) mycursor.fetchmany() d) mycursor.fetchnow()
22 (a) In an SQL table, if the primary key is combination of more than one
field, then it is called as COMPOSITE PRIMARY KEY.
(b) ALTER command is used to make an existing column as a primary
key
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 144 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
23 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
24 In MYSQL WHERE clause applies the condition on every ROW and
HAVING clause applies the condition on every GROUP
25 _________ Operator is used to compare NULL value in MYSQL table.
(a) = = (b) IN (c) IS (d) LIKE
26 Which command is used to display the structure of the table? Write the
syntax of the command. DESCRIBE < table name>;
27 Which function of mysql.connector library lets you check if the
connection to the database is established or not?
(a) connectionobject.is_connected()
(b) mysql.connector,connect()
(c) mysql.connector()
(d) mysql.connector
28 Command to remove the row(s) from table student is
(a) drop table student; (b) drop from student;
(c) remove from student; (d) delete from student;
29 Which SQL command is used to add a new attribute in a table? ALTER
30 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( )
31 The aggregate functions can only be used in the select list or WHERE
clause of a select query
32 Which SQL function is used to count all records of a table? COUNT()
33 DISTINCT key is used to uniquely identify row in a table and also does
not accept NULL values
34 State True or False: Delete command is used to remove table. FALSE
35 What does the following query do?
UPDATE employee
SET salary=salary * 1.10;
(a) It increases the salary of all the employees by 10%
(b) It decreases the salary of all the employees by 10%
(c) It increases the salary of all the employees by 110%
(d) It is syntactically correct
36 The SQL WHERE clause contains the condition that specifies which rows
are to be selected.
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 145 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
37 The RDBMS terminology for a row is
(a) Tuple (b) relation (c) attribute (d) degree
38 With SQL, how do you select all the records from a table named
“Persons” where the value of the column “FirstName” ends with an “a”?
a) SELECT * FROM Persons WHERE FirstName=’a’
b) SELECT * FROM Persons WHERE FirstName LIKE ‘a%’
c) SELECT * FROM Persons WHERE FirstName LIKE ‘%a’
d) SELECT * FROM Persons WHERE FirstName=’%a%’.
39 Which of the following is not a DDL command?
a) UPDATE b) TRUNCATE c) ALTER d) None of the Mentioned
40 Which of the following command is used to change the VALUES OF rows
that already exist in a table?
1. Insert. 2. Union. 3. Update. 4. Select
41 Write a statement in Python to declare a dictionary whose keys are
Sub1, Sub2, Sub3 and values are Physics, Chemistry, Math respectively
D1={SUB1:”PHYSICS”,SUB2:”CHEMISTRY”,SUB3:”MATHS”}
42 In SQL, name the clause that is used to sort the records in
ascending/descending order of an attribute. ORDER BY
43 In SQL, what is the use of IS NOT NULL operator? IS NOT NULL
means the data in the corresponding attribute is not empty.
44 Which of the following is not a DDL command?
a) UPDATE b)ALTER TABLE c)CREATE TABLE d)DROP TABLE
45 Which operator in SQL is used to compare a value to a specified list of
values
a)BETWEEN b)= c)IN d)ALL
46 Which keyword is used to eliminate duplicate values in an SQL select
query?
a)unique b)distinct c)key d)all
47 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
48 Fill in the blank: ______ command is used to remove database from
MySQL.
(a) update (b)remove (c) alter (d)drop
49 Which SQL statement do we use to find out the total number of records
present in the table ORDERS?
i. SELECT * FROM ORDERS;
ii. SELECT COUNT (*) FROM ORDERS;
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 146 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
iii. SELECT FIND (*) FROM ORDERS;
iv. SELECT SUM () FROM ORDERS;
50 Which among the following are valid table constraints?
a) Candidate Key b) NULL c) Distinct d) Primary Key
51 The statement in SQL which allows to change the definition of a table is
(a) Alter. (b) Update. (c) Create. (d) select.
52 Select * from employee order by salary descending, name ascending ;
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
53 Which of the following command will use to add new column in the table
from MYSQL database?
(a) DELETE TABLE (b) DROP TABLE
(c) REMOVE TABLE (d) ALTER TABLE
54 The SQL built-in function min() obtains the smallest value in a numeric
column :
55 _____ command is used to update records in the MySQL table.
(a) ALTER (b) UPDATE (c) MODIFY (d) SELECT
56 Which command used to fetch rows from the table in database?
(a) BRING (b) FETCH (c) GET (d) SELECT
57 _______ is the table constraint used to stop null values to be entered in the
field.
(i) Unique (ii) Not NULL (iii) Not Empty (iv) None
58 In SQL, we use _____ command to display the list of databases in the
server.
(a) SELECT DATABASES; (b) SELECT DATABASE;
(c) SHOW DATABASES; (d) DESC;
59 _____________ command is used to modify the attribute datatype or size
in a table structure.
a) update b) alter c) insert d) None of these
60 Which of the following clause is used to sort records in a table?
a) GROUP b) GROUP BY c) ORDER BY d) ORDER
61 ________ constraint is used to restrict entries in other table’s non key
attribute, whose values are not existing in the primary key of reference
table..
a) Primary Key b) Foreign Key c) Candidate Key d) Alternate Key
62 Which command is used to add a new record in existing table in SQL
a) insert into b) alter table c) add into d) create table
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 147 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
63 Which SQL command is used to delete an existing column from a table?
a) update b) delete c) alter d) order
64 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
65 To retrieve all the rows from the result set, which method is used?
a) fetchall b) fetchone c) fetchmany d) none of the above
66 ALTER command is used to change datatype of a field in table in SQL.
(a) update (b)remove (c) alter (d)drop
67 Which of the following commands will be delete the table from MYSQL
Database?
(a) Delete table (b) Drop Table (c) Remove Table (d) Alter Table
68 Which function is used to display the sum of column of records from
table in a database?
(a) sum(*) (b) total(*) (c) count(*) (d) return(*)
69 Which of the following operators can take wild card characters for query
condition?
(a) BETWEEN (b) LIKE (c) IN (d) NOT
70 The primary key is selected from the set of ____________
(a) Composite keys (b) Determinants
(c) Candidate keys (d) Foreign keys
71 In SQL, which command is used to change a table’s
structure/characteristics?
(a) ALTER TABLE (b) MODIFY TABLE (c) CHANGE TABLE (d)
DESCRIBE TABLE
72 Which of the following is a DDL command?
a) SELECT b) ALTER c) INSERT d) UPDATE
73 __________ is the method used in python while interfacing the SQL with
Python to save the changes permanently to the database while inserting
or modifying the records.
(a) save() (b) commit() (c) final() (d) lock()
74 The role of the statement
‘cursor=db.cursor’ is:
a)Create an instance of a cursor b)Move cursor row wise
c) Connects cursor to database d) Prepare cursor to move
75 ………………..is a set of attributes in a relation , for which no two tuples
in a relation state have the same combination of values.
a) Super Key b) Candidate Key c) Primary Key d) All of the above
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 148 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
76 SELECT name FROM class WHERE subject……NULL;
Which comparison operator may be used to fill the blank space in above
query?
a) = b)LIKE c)IS d)IS NOT
77 Which of the following is the correct command to delete an attribute
Salary from relation Employee.
(A) DELETE SALARY FROM EMPLOYEE;
(B) ALTER TABLE EMPLOYEE DELETE SALARY;
(C) ALTER TABLE EMPLOYEE DROP SALARY;
(D) DROP COLUMN SALARY FROM EMPLOYEE;
78 A column added via ALTER TABLE command initially contains NULL
value for all existing rows.
79 All aggregate function except _________ ignore NULL values in order the
produce the output.
(A) AVG( ) (B) COUNT( ) (C) COUNT(*) (D) TOTAL( )
80 Select correct collection of DDL Command?
(A) CREATE, DELETE, ALTER, MODIFY
(B) CREATE, DROP, ALTER
(C) CREATE, DROP, ALTER, MODIFY
(D) CREATE, DELETE, ALTER, UPDATE
81 Which statement is used to display the city names without repetition from
table Exam?
(A) SELECT UNIQUE(city) FROM Exam;
(B) SELECT DISTINCT(city) FROM Exam;
(C) SELECT PRIMARY(city) FROM Exam; (D) All the above
82 Ronak want to show the list of movies which name end with ‘No-1’.
Select the correct query if table is MOVIE and field attribute is
Movie_Name.
(A)SELECT Movie_Name FROM MOVIE WHERE Movie_Name = ‘%No-1’;
(B)SELECT Movie_Name FROM MOVIE WHERE Movie_Name = ‘No-1%’;
(C)SELECT Movie_Name FROM MOVIE WHERE Movie_Name LIKE ‘%No-1’;
(D)SELECT Movie_Name FROM MOVIE WHERE Movie_Name LIKE ‘No-1%’;
83 COMMIT command is belongs to _________
(A)DDL Command (B) DML Command (C) TCL Command (D) None of
the above
84 No. of rows in a relation is called ………………….. .
(a) Degree b. Domain c. Cardinality d. Attributes
85 Fill in the blank:
The ………………. clause, places condition with aggregate functions .
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 149 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
a. HAVING b. WHERE c. IN d.BETWEEN
86 Sunita executes following two statements but got the variation in result 6
and 5 why?
(i) select count(*) from user ;
(ii) select count(name) from user ;
ANSWER : COUNT(*) will include the NULL value records.
COUNT( attribute name) will not include the NULL value records.
87 WHERE clause of the following query must be added with keyword
SELECT to display the fields given in the select list as per a given
condition.
select id,name,salary*1.1 where instructor=10005;
(a) where, having (b) select, from (c) where, from (d) where,select
88 Consider the following SQL statement. What type of statement is this?
insert into instructor values(10211,'Amit','Science',6600);
(a) DDL (b) DML (c) DCL (d) TCL
89 A database______ is a special control structure that facilitates the row by
row processing of records in the result set.
(a) fetch (b) table (c) cursor (d) query
90 Which of the following attributes cannot be considered as a choice for
primary key?
(a) id (b) License number (c)Street no (d) dept_id
91 Which of the following commands will remove the entire database from
MYSQL?
(A) DELETE DATABASE (B) DROP DATABASE
(C) REMOVE DATABASE (D) ALTER DATABASE
92 Which of the following statements is True?
a) There can be only one Foreign Key in a table.
b) There can be only one Unique key is a table
c) There can be only one Primary Key in a Table
d) A table must have a Primary Key
93 _____________ Keyword is used to obtain unique values in a SELECT
query
a) UNIQUE b) DISTINCT c) SET d) HAVING
94 Which of the following is a valid sql statement?
a) ALTER TABLE student SET rollno INT(5);
b) UPDATE TABLE student MODIFY age = age + 10;
c) DROP FROM TABLE student;
d) DELETE FROM student;
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 150 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
95 Which of the following commands will delete the rows of table?
(a) DELETE command (b) DROP Command
(c) REMOVE Command (d) ALTER Command
96 Logical Operators used in SQL are?
(a) AND,OR,NOT (b) &&,||,! (c) $,|,! (d) None of these
97 ___________ command is used to ADD a column in a table in SQL.
(a) update (b)remove (c) alter (d)drop
98 An alternate key is a ___________ , which is not the primary key of the
table.
a) Primary Key b) Foreign Key c) Candidate Key d) Alternate Key
99 Select the correct statement, with reference to RDBMS:
a) NULL can be a value in a Primary Key column
b) '' (Empty string) can be a value in a Primary Key column
c) A table with a Primary Key column cannot have an alternate key.
d) A table with a Primary Key column must have an alternate key.
100 A relation can have only one _______ key and one or more than one
_________keys.
(a) PRIMARY, CANDIDATE (b) CANDIDATE, ALTERNATE
(c )CANDIDATE ,PRIMARY (d) ALTERNATE, CANDIDATE
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 151 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Q.No Questions
1
Solution:
(i) SELECT SUM(SALARY) FROM EMPLOYEE WHERE
ZONE=”WEST”;
(ii) SELECT COUNT(GRADE) FROM EMPLOYEE WHERE GRADE IS
NULL;
(iii) SELECT ZONE,MAX(SALARY), MIN(SALARY) FROM
EMPLOYEE GROUP BY ZONE;
2 Write the output for SQL queries (i) to (iv), which are based on the table:
STUDENT
given below:
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 152 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
(I)
COUNT(*) CITY
2 MUMBAI
2 DELHI
2 MOSCOW
(II)
MAX(DOB) MIN(DOB)
08-12-1995 07-05-1993
(III)
NMAE GENDER
SANAL F
STORE M
(IV)
DISTINCT CLASS
X
XII
XI
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 153 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
3
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 154 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
(A)
PARTICIPANT POINTS
JUHI CHAWLA 350
ABRAHAM 300
AKSHAY KUMAR 250
AJAY DEVGAN 200
SUNNY DEOL 200
MADHURI DIXIT 200
(B)
HOUSE COUNT(PARTICIPANT)
GANDHI 2
BOSE 3
BHAGAT 1
(C)
DISTINCT POINTS
200
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 155 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
300
250
350
(D)
PID EVENTDATE
101 2022-02-03
103 2019-09-23
5 As part of Fit India Campaign, Suresh has started a juice shop that serves
healthy juices. As his database administrator, answer the following
questions based on the data given in the table below.
(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 below table?
(iii) Write the statements to:
a. Insert the following record into the table
DrinkCode – 107, Dname – Santara Special, Price – 25.00, Calorie – 130
b. Increase the price of the juices by 3% whose name begins with ‘A’.
OR (Option for part iii only)
(iii) Write the statements to:
a.Delete the record of those juices having calories more than 140.
b. Add a column Vitamins in the table with datatype as varchar with 20
characters.
i) To display the details of all the item in ascending order of item names
ii)To display item name and price of all those items whose price in range
of 10000 to 30000
iii) To display max and min price of the table
iv)To display the total amount of digiclick company
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 157 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
(A)
PUBLISHER PRICE
EEE 750
EPB 250
(B)
BOOK_NAME TYPE
The tears fiction
Thunderbolts fiction
(c)
Sum(price)
925
(d)
Min(qty)
5
8 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”.
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 158 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
(i)
Max(fees) Min(fees)
6000 4000
(ii)
Count (distinct sname)
4
(iii)
sname Sum(no_of_ players)
Foot ball 25
Basket ball 80
Volley ball 25
Kho-kho 40
(iv)
Avg(fees * no_of_players)
5250
9 Naveen created a table SALES_DONE to maintain the sales made by his
sales department. The table consists of 10 employees records. To record
every months sales he is adding a new column with first three characters
of that month
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 159 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 160 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
EMPLOYEE table?
(I)
SALARY + 100
100
(II)
NAME
NEEV
11
a) List the names of those students who obtained DIV 1 sorted by NAME .
b )Display a report, listing NAME , STIPEND , SUBJCT and amount of
stipend received in a year assuming that the STIPEND is paid every
month.
C.) Give the output of the following SQL statements based on table
GRADUATE :
(i) Select MIN(AVERAGE ) from GRADUATE where
SUBJECT=”PHYSICS”;
(ii)Select SUM(STIPEND) from GRADUATE where DIV=1;
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 163 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
(I)
NO TITLE TYPE RATING SEATS_LEF PRICE
T
1 SANJU BIOPIC A 4 250
3 RACE3 ACTION C 7 245
5 BAHUBALI DRAMA A 3 300
(III)
NO TITLE TYPE RATING SEATS_LEFT PRICE
2 RAID ACTION B 2 175
4 HAAMI COMEDY A 3 130
5 BAHUBALI DRAMA A 3 300
(II)
MAX(PRICE)
300
15 Navdeep creates a table HOUSE with a set of records to maintain. After
creation of the table, he has entered data of 6 houses in the table.
Based on the data given above answer the following questions:
(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?
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 164 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
(iii) Write the statements to:
a. Insert the following record into the table HID – H7, Location -
Chirimiri, Quantity - 10, Unit _Price -600000, Dcode- 3,
b. Increase the unit price of the house by 3% whose name ends with ‘ur’.
OR
(iii) Write the statements to:
a. Delete the record of house location Ambikapur
b. Add a column REMARKS in the table with datatype as varchar with 50
Characters
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 165 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
SOLUTION :
(I)
SUM(SALARY)
43000
(II)
MAX(DOB) MIN(DOB)
1995-10-08 1993-07-05
(III)
GENDER COUNT(*)
F 3
M 3
(IV)
NAME
RAJU
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 166 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
18 ABC Gym has created a table TRAINER. Observe the table given below
and answer the
following questions accordingly
a. What is Degree and Cardinality of the above table?
b. Which field should be made as the primary key? Justify your answer.
c. Write the query to:
i. Insert a record: (107,Bhoomi,Delhi,2001-12-15,90000)
ii. Increase the salary by 1% for the trainers whose salary is more than
80000
OR
i. Delete the record of Richa
ii. Add a new column remarks of VARCHAR type with 50 characters.
SOLUTION :
(A) DEGREE IS - 5 CARDINALITY IS - 6
(B) THE PRIMARY KEY IS TID, BECAUSE THE VALUES ENTERED
ARE UNIQUE.
(C)
(I) INSERT INTO TRAINER VALUES ( 107,”BHOOMI”,’2001-12-
15’,90000);
(II) UPDATE TRAINER SET SALARY = SALARY + SALARY * 1 / 100
WHERE SALARY > 80000;
[OR]
(I) DELETE FROM TRAINER WHERE TNAME =”RICHA”;
(II) ALTER TABLE TRAINER ADD REMARKS VARCHAR(50);
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 167 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
19 Write the output of the queries (i) to (iv) based on the table “Product”,
showing details of
products being sold in a grocery shop.
(I)
PNAME AVERAGE(PRICE)
WASHING POWDER 120
TOOTHPASTE 59.5000
SOAP 31.5000
SHAMPOO 245
(II)
DISTINCT MANUFACTURER
SURF
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 168 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
COLGATE
LUX
PEPSODENT
DOVE
(III)
DISTINCT(PNAME)
WASHING POWDER
TOOTHPASTE
SOAP
SHAMPOO
(IV)
PNAME MAX(PRICE) MIN(PRICE)
WASHING POWDER 120 120
TOOTHPASTE 65 54
SOAP 38 25
SHAMPOO 245 245
20 Arjun creates a table Employee with a set of records to maintain their
Inventory. After creation of table, he entered data of 7 employees in the
table.
(a) Identify the attribute best suitable to be declared as a primary key
(b) If two columns and two rows are added what will be the degree and
cardinality of the table Employee
(c) i) Insert the following data into the attributes empID, empName and
empDept respectively in the given table employee empID = 1042,
empName = “Abhinav” and empDept = “support”
ii) Write a command display structure of table employee.
OR
(c) i) Write a command to add new column bonus to Employee Table
ii) Write SQL statement to update the Bonus of all employees by 20% of
salary
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 169 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 170 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
a) Karan wants to remove all the data from table WORKER from the
database department. Write the command to delete above said
information.
b) Identify the attribute best suitable to be declared as a primary key.
c) (i) Karan wants to increase the size of the FIRST_NAME column from
10 to 20 characters. Write an appropriate query to change the size.
(ii) Write a query to display the structure of the table Worker, i.e. name of
the attribute and their respective data types
ANSWER :
(A) DELETE FROM WORKER;
(B) WORKER_ID is the best suitable field for primary key.
(C) (I) ALTER TABLE WORKER MODIFY FIRST_NAME
VARCHAR(20);
(III) DESCRIBE WORKER
22 Nishant creates a table RESULT with a set of records to maintain the
marks secured by students in Sem 1, Sem2, Sem3 and their division. After
creation of the table, he has entered data of 7 students in the table
ANSWER :
(I) ROLL_NO is the appropriate primary key.
(II) Degree is - 8 cardinality is - 5
(III) (A) INSERT INTO RESULT VALUES (108,”AADIT”,470,444,475,I);
(B)UPDATE RESULT SET SEM2= SEM2 + SEM2 * 3/100 WHERE
NAME LIKE ‘%N’;
[or]
(III)
(A) DELETE FROM RESULT WHERE DIVISION = “I”;
(B) ALTER TABLE RESULT ADD REMARKS VARCHAR(50);
23 Write SQL commands for (a) to (d) and write output for (e) to (f) on the
basis of PRODUCTS table:
OUTPUT:
(E)
COUNT(DISTINCT COMPANY)
4
MAX(PRICE)
39000
24 A music store MySports is considering to maintain their inventory using
SQL to store
the data. The detail is as follow:
Name of the database – MySports
Name of the table – Sports
The attributes of SPORTS are as follows:
SCode – character
SportName – character of size 20
Noofplayers – numeric
coachname – character of size 20
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 173 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
he use from the following:
i) DELETE Coachname FROM SPORTS;
ii) ALTER Coachname FROM SPORTS
iii) ALTER TABLE SPORTS DROP Coachname
iv) DELETE Coachname FROM SPORTS
ANSWER :
(A) SCODE is the primary key.
(B) DEGREE IS - 4 CARDINALITY IS -6
(C) INSERT INTO SPORTS VALUES (“S007”,”kabbadi”,15);
(D) ALTER TABLE SPORTS DROP COACHNAME;
25 Consider the following table HOSPITAL. Answer the questions that
follows the table:
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 174 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
(II)DEGREE IS - 7 CARDINALITY IS - 10
(III)
(A) DELETE FROM HOSPITAL WHERE NAME LIKE ‘Z%’;
(B) UPDATE HOSPITAL SET CHARGES = 1000 WHERE NAME =
“ANKITA”;
[ OR ]
A) DESCRIBE HOSPITAL;
B) UPDATE HOSPITAL SET AGE = AGE + 2 ;
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 175 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Q. Questions
N
o
1 Write SQL statements for the q.no (i) to (iv) and output for (v)
(i) Write any one point of difference between Equi join and Natural join.
(ii) Find output:
(a) select *from product p, supplier s where p.supid=s.supid;
(b) select *from product natural join supplier;
OR
(i) Write a Query to insert House_Name=Tulip, House_Captain= Rajesh
and House_Point=278 into table House(House_Name, House_Captain,
House_Points)
ANSWER :
(I) SQL Equi Join performs a JOIN against equality or matching
columns values of the associated tables. An equal to sign is used as
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 177 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
comparison operator in the where clause to refer equality.
SYNTAX :
SELECT column_list FROM table1, table2 WHERE
table1.column_name = table2_column_name;
The SQL NATURAL JOIN is atype of EQUI JOIN and is structured
in such a way that column with the same name of associated tables will
appear once only.
SYNTAX :
SELECT * FROM table1 NATURAL JOIN table2;
(II) A)
B)
supid sname city pno pname Price
222 Ttt Chennai 101 Pen 10
333 Aax Cbe 102 Pencil 10
222 Ttt Chennai 103 Eraser 5
[OR]
(I) INSERT INTO HOUSE VALUES(“TULIP:,”RAJESH”,278);
3 Consider the following DEPT and WORKER tables. Write SQL queries
for the following
(i) To display Wno, Name, Gender from the table WORKER in
descending order of Wno.
(ii) To display the Name of all the FEMALE workers from the table
WORKER
(iii) Write statements
a) To display the Wno and Name of those workers from the table
WORKER who are born between '1987-01-01' and '1991-12-01'.
b) To count and display MALE workers who have joined after '1986-01-
01".
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 178 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
ANSWER :
(I) SELECT WNO,NAME,GENDER FROM WORKER ORDER BY WNO
DESCENDING;
(II) SELECT NAME FROM WORKER WHERE GENDER = “FEMALE”;
(III)
(A) SELECT WNO, NAME FROM WORKER WHERE DOB BETWEEN
'1987-01-01' and '1991-12-01';
(B)SELECT SUM (GENDER) FROM WORKER WHERE DOB>'1986-01-
01" AND GENDER = “MALE”;
4 In a database School, there are two tables given below:
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 179 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
(ii) What is the degree of the table students?
(iii) Write SQL statements to perform the following operations
a) To display the name and game played by sports students
b) To change the address and phonenumber of “Meena ” to B 54,
8864113
(OR only to subpart iii)
iii) a) To make the field class in table STUDENTS mandatory while
inserting data
b) To delete the game CRICKET from SPORTS TABLE.
ANSWER :
(I) ADMNO is the foreign key in the table sports.
(II) Degree is 7
(iii)
A) SELECT STUDENTS.NAME, SPORTS.GAME FROM STUDENTS,
SPORTS ;
B) UPDATE STUDENTS
SET ADDRESS=”B 54” , PHONE=8864113;
[OR]
(A) To make the field class in table STUDENTS mandatory while
inserting data ,include NOT NULL while creating the structure.
(B) DELETE FROM SPORTS WHERE GAME =”CRICKET”;
5 Write the SQL Queries for (i) to (iii) based on the table EMPLOYEE and
DEPARTMENT
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 180 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 181 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
ANSWER :
(I) SELECT NAME FROM DOCTOR WHERE DEPT =
“ORTHOPEDIC” AND EXPERIENCE > 10;
(II) SELECT AVG(SALARY.BASIC + SALARY.ALLOWANCE) FROM
DOCTOR, SALARY WHERE DEPT=”ENT”;
(III) SELECT MIN(ALLOWANCE) FROM SALARY;
(IV) SELECT MAX(SALARY.CONSULTATION) FROM
DOCTOR,SALARY WHERE DOCTOR.SEX=”M”;
(V) SHOW TABLES;
7 Write SQL commands for the queries (i) to (iii) and output for (iv) &
(vii) based on a table COMPANY and CUSTOMER
I) Identify the most appropriate Primary key for Tables Company and
Customer.
Ii) To display those company name which are having prize less than
30000.
iii a.To increase the price by 1000 for those customer whose name starts
with S?
b) What is the cardinality and degree of table customer?
Or
Iii)a) Delete the records from table customer whose name has KUMAR.
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 182 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
B. Insert a new record in table COmpany where CID : 777, Name :
APPLE City KOCHI and PRODUCTNAME is LAPTOP
ANSWER :
(I) The primary key for company table is - CID
The primary key for customer table is - CUSTID
(ii) Display company.name from company, customer where
customer.prize<30000;
(iii) (a)Update customer set price = price + 1000 where name like “%s”;
(b) Cardinality is - 7 Degree is - 5
[or]
(a) DELETE FROM CUSTOMER WHERE NAME=”%KUMAR”;
(b) INSERT INTO COMPANY VALUES
(777,”APPLE”,”KOCHI”,”LAPTOP”);
8 Consider the following tables. Write SQL commands for the statements
(i) to (iv)
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 183 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
ANSWER :
(I) SELECT SENDER.SENDERNAME FROM SENDER WHERE
SENDERCITY = “MUMBAI”;
(II) SELECT
RECIPIENT.RECID,SENDER.SENDERNAME,SENDER.SENDERADDR
ESS,RECIPIENT.RECNAME,RECIPIENT.RECADDRESS FROM
SENDER, RECEIPIENT FROM SENDER, RECIPIENT;
(III) SELECT * FROM RECIPIENT ORDER BY RECNAME ASC;
(IV) SEELCT RECCITY, COUNT(RECCITY) FROM RECIPIENT
GROUP BY RECCITY;
(V) DESCRIBE SENDER; DESCRIBE RECIPIENT;
9 Consider the following tables MobileMaster and MobileStock. Write
SQL commands for the statements (i) to (v)
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 184 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
ANSWER :
(I) SEELCT M_COMPANY, M_NAME, M_PRICE FROM
MOBILEMASTER ORDER BY M_MF_DATE;
(II) SELECT * FROM MOBILEMASTER WHERE M_NAME LIKE
“S%”;
(III) SELECT M_SUPPLIER, M_QTY FROM MOBILESTOCK WHERE
M_ID NOT= “MB003:
(IV) SELECT M_COMPANY FROM MOBILEMASTER WHERE
M_PRICE BETWEEN 3000 AND 5000;
(V) SELECT MOBILEMASTER.M_COMPANY,
MOBILESTOCK.M_SUPPLIER, MOBILEMASTER.M_PRICE FROM
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 185 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
MOBILEMASTER, MOBILESTOCK WHERE
MOBILEMASTER.M_PRICE>5000;
10 Write SQL commands for the following queries (i) to (iv) based on the
relations Shoppe and Accessories given below:
(i)to display name and price of all the accessories in descending order of
their price.
(ii)to display id and sname of all shoppe located in nehru place.
(iii)to display minimum and maximum price of each name of
accessories.
(iv) to display name, price of all accessories and their respective sname
where they are available.
ANSWER :
(I) SEELCT NAME, PRICE FROM ACCESSORIES ORDER BY PRICE;
(II) SELECT ID, SNAME FROM SHOPPE WHERE AREA = “NEHRU
PALACE”;
(III) SELECT MAX(PRICE), MIN(PRICE) FROM ACCESSORIES
GROUP BY NAME;
(IV) SELECT ACCESSORIES.NAME, ACCESSORIES.PRICE ,
SHOPPE.SNAME FROM ACCESSORIES, SHOPPE;
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 186 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Q.No Questions
1 The code given below inserts the following record in the table Student:
Empno – integer
EName – string
Designation – integer
Salary – integer
Bonus - Integer
Note the following to establish connectivity between Python and MYSQL:
Username is root
Password is tiger
The table exists in a MYSQL database named Employee.
The details (Empno, EName, Designation, Salary and Bonus) are to be
accepted
from the user.
Solution :
import mysql.connector
mydb=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”
tiger”,database=”employee”)
Mycursor=mydb.cursor()
eno=int(input(“Enter Employee number”))
ena=input(“enter name”)
desg=input(“enter Designation”)
sal=int(input(Enter Salary”))
bon=int(input(“enter bonus”))
mycursor.execute(“INSERT INTO
student(empno,ename,designation,salary, bonus) VALUES
({},’{}’,’{}’,{},{})”.FORMAT (eno,ena,desg,sal,bon))
mydb.commit()
2 The code given below inserts the following record in the table Student:
RollNo – integer
Name – string
Class– integer
Marks – integer
Note the following to establish connectivity between Python and MYSQL:
Username is root,Password is tiger The table exists in a MYSQL database
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 187 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
named school.The details (RollNo, Name, Clas and Marks) are tobe
accepted from the user
3 The code given below inserts the following record in the table Student:
Rollno - integer
Name - string
Age - integer
Note the following to establish connectivity between Python and
MYSQL:
• Usemame is root
• Password is sys
• The table exists in a MYSQL data base named school.
• The details(Roll no, Name and Age) are to be accepted from the user
4 The code given below inserts the following record in the table
Book:
B_No – integer
B_Name – string
B_Author – string
Price – Decimal
Note the following to establish connectivity between Python and
MYSQL:
Username is root
Password is tiger
The table exists in a MYSQL database named Library.
The details (B_No, B_Name, B_Author and Price) are to be accepted from
the user.
5 The code given below inserts the following record in the table Emp:
EmpNo – integer
EName – string
Desig – string
Salary – integer
Note the following to establish connectivity between Python and MYSQL:
Username is admin
Password is 22admin66
The table exists in a MYSQL database named company.
The details (EmpNo, EName, Desig and Salary) are to be accepted
from the user.
6 The code given below inserts the following record in the table Player:
PNo – integer
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 188 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Name – string
NoofGames– int
Goals – integer
Note the following to establish connectivity between Python and MYSQL:
a. Username is root
b. Password is sport
c. The table exists in a MYSQL database named Football.
d. The details (Pno,Name,NoofGames,Goals) are to be accepted from the
user
7 The code given below inserts the following record in the table Student:
RollNo – integer
Name – string
Marks – integer
Address –String
Phone-integer
Note the following to establish connectivity between Python and MYSQL:
Username is root
Password is root
The table exists in a MYSQL database named school.
The details (RollNo, Name, Marks,Address,Phoneno) are to be
accepted from the user.
8 The code given below inserts the following record in the table Employee:
Eid – integer
Name – string
DeptID – integer
Salary – integer
Note the following to establish connectivity between Python and MYSQL:
Username is root
Password is tiger
The table exists in a MYSQL database named Company.
The details (Eid, Name, DeptID and Salary) are to be accepted from the
user. Write the following missing statements to complete the code:
9 The code given below reads the following record from the table
named Employee and displays only those records who have salary
greater than 15,000:
ENo – integer
EName – string
Dept – string
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 189 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Salary – integer
Note the following to establish connectivity between Python and MYSQL:
* Username is root
* Password is tiger
* The table exists in a MYSQL database named Company
10 The code given below search for a record using ID in Python
The employee table consists of the following details:
Employee Name
Salary
Designation
City
Birth Date
Note the following to establish connectivity between Python and
MYSQL:
• Username is root
• Password is tiger
• The table exists in a MYSQL database named Company
11 Considering a table Product stored in database Inventory,complete the
Mysql connectivity code to delete the products whose name is beginning
with “M” Product table has following attributes –(pno,pname,price,qty)
Note the following to establish connectivity between Python and MYSQL:
a. Username is root
b. Password is stock
12 The code given below reads the following record from the table named
student and displays only those records who have marks greater than 75:
RollNo – integer
Name – string
Clas – integer
Marks – integer
Note the following to establish connectivity between Python and MYSQL:
Username is root
Password is tiger
13 The code given below reads the following record from Table named
Employee and display
those record salary >= 30000 and <= 90000:
Empno – integer
EName – string
Desig – integer
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 190 of 191
CLASS 12 BOARD REVISION STUDY MATERIAL SOLUTIONS
Salary – integer
Note the following to establish connectivity between Python and MYSQL:
Username is root
Password is Password
The table exists in a MYSQL database named Bank
Prepared By Faculty Members, Dept of ComputerScience, Vel’s Vidhyalaya Kovilpatti Page 191 of 191