Question Bank 2023-24 Computer Science
Question Bank 2023-24 Computer Science
SAMBALPUR
SAMPLE QUESTIONS
CHAPTER WISE
PREPARED BY:-
MR.PRAFULLA KUMAR GOUDA
MOB-7999552828
Computer Science CBSE Prescribed Syllabus (Theroy-70 Marks)
1. Unit I: Computational Thinking and Programming – 2
2. Unit II: Computer Networks
3. Unit III: Database Management
Project
The aim of the class project is to create something that is tangible and useful using
two to three students and should be started by students at least 6 months before
the submission deadline. The aim here is to find a real world problem that is
worthwhile to solve.
Computational thinking and programming-1-Python
Python Introduction`
It is widely used general purpose, high level programming language. Developed by Guido van
Rossum in 1991.
It is used for:
software development,
web development (server-side),
system scripting,
Mathematics.
Features of Python
1. Easy to use – Due to simple syntax rule
2. Interpreted language – Code execution & interpretation line by line
3. Cross-platform language – It can run on windows, Linux, Macintosh etc. equally
4. Expressive language – Less code to be written as it itself express the purpose of the code.
5. Completeness – Support wide range of library
6. Free & Open Source – Can be downloaded freely and source code can be modify for improvement
Shortcomings of Python-
Script mode
Script mode is useful for creating programs and then run the programs later and get the complete
output. It is not suitable for testing code.
Indentation
Python uses indentation to create blocks of code. Statements at same indentation level are part
of same block/suite
if 3 > 2:
print(“Three is greater than two!") //syntax error due to not indented
E.g.2x
if 3 > 2:
print(“Three is greater than two!") //indented so no error
Token`
Smallest individual unit in a program is known as token.
1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Punctuators/Delimiters
Keywords
Keywords are reserved words carrying special meaning and purpose to the language
compiler/interpreter. For example, if, elif, etc. are keywords.
Identifiers
Identifiers are user defined names for different parts of the program like variables, objects, classes,
functions, etc. Identifiers are not reserved. They can have letters, digits and underscore. They must
begin with either a letter or underscore. For example, _chk, chess, trail, etc.
Literals
Literals are data items that have a fixed value. The different types of literals allowed in Python are:
String literals- A string is literal and can be created by writing a text(a group of Characters )
surrounded by a single(”), double(“), or triple quotes.
# in single quote
s = 'geekforgeeks'
# in double quotes
t = "geekforgeeks"
# multi-line String
m = '''geek
for
geeks'''
print(s)
print(t)
print(m)
Numeric literals- Integer , Float ,Complex
Boolean literals- True or False
Special literal- None
Literal collections- List ,Tuple,Dict,Set
Operators
Operators are tokens that trigger some computation/action when applied to variables and other
objects in an expression.
Operators can be defined as symbols that are used to perform operations on operands.
Types of Operators
1. Arithmetic Operators.
2. Relational Operators.
3. Assignment Operators.
4. Logical Operators.
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
1. Arithmetic Operators Arithmetic Operators are used to perform arithmetic operations like
addition, multiplication, division etc.
6. Membership Operators
The membership operators in Python are used to validate whether a value is found within a sequence
such as such as strings, lists, or tuples.
7. Identity Operators Identity operators in Python compare the memory locations of two
objects.
Operators Precedence:
Highest precedence to lowest precedence table. Precedence is used to decide, which operator to be
taken first for evaluation when two or more operators comes in an expression.
Variable Python
Python variables are simply containers for storing data values
Example - x=25 here x is a variable
Punctuators/Delimiters
Barebones of a python program
R-value - Rvalue refers to the value we assign to any variable. It can appear on RHS of assignment
Sum=a+b here a+b is R-Value
Dynamic typing
Data type of a variable depend/change upon the value assigned to a variable on each next statement.
Dynamic typing means that the type of the variable is determined only during runtime
Example -
X = 25 # integer type
X = “python” # x variable data type change to string on just next line
Now programmer should be aware that not to write like this:
Y = X / 5 # error !! String cannot be divided
Mutable and Immutable Data type
A mutable data type can change its state or contents and immutable data type cannot.
Mutable data type: list, dict, set, byte array
Immutable data type: int, float, complex, string, tuple, frozen set
[note: immutable version of set], bytes
Mutability can be checked with id() method.
x=10 print(id(x))
x=20
print(id(x))
#id of both print statement is different as integer is immutable
What is the difference between implicit type conversion and explicit type conversion?
Answer
Example: Example:
a, b = 5, 25.5 a, b = 5, 25.5
c=a+b c = int(a + b)
Debugging
Debugging means the process of finding errors, finding reasons of errors and techniques of their
fixation. An error, also known as a bug, is a programming code that prevents a program from its
successful interpretation. Errors are of three types –
• Logical Error
These errors are basically of 2 types – Syntax Error :Violation of formal rules of a programming
language results in syntax error.
str1=”ips’
print(str1)
Semantics Error: Semantics refers to the set of rules which sets the meaning of statements. A
meaningless statement results in semantics error.
For example - x * y = z
Logical Error
Logical Error If a program is not showing any compile time error or run time error but not
producing desired output, it may be possible that program is having a logical error. Some example-
• Use of wrong operator in place of correct operator required for operation X=a+b (here – was
required in place of + as per requirement
Run time Error These errors are generated during a program execution due to resource limitation.
Python is having provision of checkpoints to handle these errors.
For example –
a=10
b=int(input(“enter a number”))
c=a/b
Value of b to be entered at run time and user may enter 0 at run time,that may cause run time error,
because any number can’t be divided by 0
Run time Error In Python, try and except clauses are used to handle an exception/runtime error
which is known as exception handling
a=10
b=int(input(“enter a number”))
c=a/b
except:
Debugger tool
1. if statements
Syntax:
if(condition):
statement
[statements]
e.g.
noofbooks = 2
if (noofbooks == 2):
print('You have ')
print(‘two books’)
print(‘outside of if statement’)
Output
You have two books
2. if-else Statements
2. if-else Statements If-else statement executes some code if the test expression is true (nonzero)
and some other code if the test expression is false.
Syntax:
if(condition):
statements
else:
statements
e.g.
a=10
if(a < 100):
print(‘less than 100')
else:
print(‘more than equal 100')
OUTPUT
less than 100
3. Nested if-else statement The nested if...else statement allows you to check for multiple test
expressions and execute different codes for more than two conditions.
Iteration statements (loop) are used to execute a block of statements as long as the condition is
true. Loops statements are used when we need to run same code again and again.
Python Iteration (Loops) statements are of three type :-
1. While Loop
2. For Loop
3. Nested For Loops
1. While Loop It is used to execute a block of statement as long as a given condition is true. And
when the condition become false, the control will come out of the loop. The condition is checked
every time at the beginning of the loop.
2. For Loop It is used to iterate over items of any sequence, such as a list or a string.
Syntax
for val in sequence:
statements
e.g.
for i in range(3,5):
print(i)
Output
3
4
2. For Loop continue Example programs
for i in range(5,3,-1):
print(i)
Output
5
4
range() Function Parameters
start: Starting number of the sequence.
stop: Generate numbers up to, but not including this number.
step(Optional): Determines the increment between each numbers in the
Nested Loop
A nested loop is an inner loop in the loop body of the outer loop. The inner or outer loop can be any
type, such as a while loop or for loop. For example, the outer for loop can contain a while loop and
vice versa
String
String is a sequence of characters, which is enclosed between either single (' ') or double quotes ("
"), python treats both single and double quotes same.
Creating String Creation of string in python is very easy.
e.g. a=‘Computer Science'
b=“Informatics Practices“
Accessing String Elements
Iterating/Traversing through string Each character of the string can be accessed sequentially using
for loop.
e.g.
str='Computer Sciene‘
for i in str:
print(i)
output-
C
O
M
P
U
R
String comparison
We can use ( > , < , <= , <= , == , != ) to compare two strings.
Python compares string lexicographically i.e using ASCII value of the characters.
Suppose you have str1 as "Maria" and str2 as "Manoj" . The first two characters from str1 and str2 (
M and M ) are compared. As they are equal, the second two characters are compared. Because they
are also equal, the third two characters ( r and n ) are compared. And because 'r' has greater ASCII
value than ‘n' , str1 is greater than str2 .
Updating Strings
String value can be updated by reassigning another value in it.
e.g.
var1 = 'Comp Sc'
var1 = var1[:7] + ' with Python'
print ("Updated String :- ",var1 )
OUTPUT
('Updated String :- ', 'Comp Sc with Python')
String Special Operators
e.g.
a=“comp”
b=“sc”
Triple Quotes It is used to create string with multiple lines.
e.g.
Str1 = “””This course will introduce the learner to text mining and text manipulation basics. The
course begins with an understanding of how text is handled by python”””
String functions and methods
a=“comp”
b=“my comp”
a=“comp”
String functions and methods
a=“comp”
#Python Program to calculate the number of digits and letters in a string
string=raw_input("Enter string:")
count1=0
count2=0
for i in string:
if(i.isdigit()):
count1=count1+1
count2=count2+1
print("The number of digits is:")
print(count1)
print("The number of characters is:")
print(count2)
List in Python
Introduction
It is a collection of items and each item has its own index value. Index of first item is 0 and the last item is n-1.Here n
is number of items in a list.
Creating a list
Lists are enclosed in square brackets [ ] and each item is separated by a comma.
Initializing a list
e.g.
list1 = [‘English', ‘Hindi', 1997, 2000]
list2 = [11, 22, 33, 44, 55 ]
list3 = ["a", "b", "c", "d"]
Blank list creation
List4=[ ]
e.g.
list =[3,5,9]
for i in range(0, len(list)):
print(list[i])
Output
3
5
9
List Operations
1. Joining List
2. Repeating or Replicating Lists
3. Slicing the List
4. Making True Copy of a List
list1=[2,5,6]
list2=[“school”, 45.23]
list1+list2
List1=[1,3,5]
List1*3
[1,3,5,1,3,5,1,3,5]
a=[1,2,3]
b=a
5. Extend()- The extend() is also used for adding multiple elements (given in the form of list) to a list.
Syntax-List.extend(list)
Example –
fruits = ['apple', 'banana', 'cherry']
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo']
fruits.clear()
[]
9. Count()-Returns the number of elements with the specified value
Syntax- list.count(item)
Example –
fruits = ['apple', 'banana', 'cherry']
x = fruits.count("cherry")
1
10. Revers()-Reverses the order of the list
Syntax- list.reverse()
Tuples
Introduction
Creating and Accessing tuples
Tuples operations
Tuple Functions and Methods
Tuples- Tuples are immutable sequences of python. We cannot change the elements of a tuple in place.
It is a sequence of immutable objects. It is just like list. Difference between the tuples and the lists is that the tuples
cannot be changed unlike lists. Lists uses square bracket whereas tuples use parentheses.
Creating A Tuple
A tuple is enclosed in parentheses () for creation and each item is separated by a comma.
e.g.
tup1 = (‘comp sc', ‘info practices', 2017, 2018)
tup2 = (5,11,22,44)
Tuples operations
apple
banana
cherry
Dictionary
It is an unordered collection of items where each item consist of a key and a value. It is
mutable (can modify its contents ) but Key must be unique and immutable
Creating A Dictionary
It is enclosed in curly braces {} and each item is separated from other item by a comma(,).
Within each item, key and value are separated by a colon (:).
Passing value in dictionary at declaration is dictionary initialization.get() method is used to
access value of a key
e.g. dict = {‘Subject': ‘Informatic Practices', 'Class': ‘11'}
Accessing List Item
dict = {'Subject': 'Informatics Practices', 'Class': 11}
print(dict) print ("Subject : ", dict['Subject'])
print ("Class : ", dict.get('Class'))
OUTPUT
{'Class': '11', 'Subject': 'Informatics Practices'}
('Subject : ', 'Informatics Practices')
('Class : ', 11
Iterating / Traversing through A Dictionary Following example will show how dictionary
items can be accessed through loop.
e.g. dict = {'Subject': 'Informatics Practices', 'Class': 11} for i in dict: print(dict[i]) OUTPUT 11
Informatics Practices Updating/Manipulating Dictionary Elements We can change the
individual element of dictionary. e.g. dict = {'Subject': 'Informatics Practices', 'Class': 11}
dict['Subject']='computer science' print(dict) OUTPUT {'Class': 11, 'Subject': 'computer
science'}
Python Revision Tour-I
Multiple Choice Questions (MCQs)
(a) Which of the following is not considered a valid identifier in Python?
(i) two2 (ii) _main (iii) hello_rsp1 (iv) 2 hundred
(b) What will be the output of the following code— print(“100+200”)?
(i) 300 (ii) 100200 (iii) 100+200 (iv) 200
(c) Which amongst the following is a mutable datatype in Python?
(i) int (ii) string (iii) tuple (iv) list
(d) pow() function belongs to which library?
(i) math (ii) string (iii) random (iv) maths
(e) Which of the following statements converts a tuple into a list?
(i) len(string) (ii) list(string) (iii) tup(list) (iv) dict(string)
(f) The statement: bval = str1 > str2 shall return .............................. as the output if two strings
str1 and str2 contains “Delhi” and “New Delhi”.
(i) True (ii) Delhi (iii) New Delhi (iv) False
(g) What will be the output generated by the following snippet?
a = [5,10,15,20,25]
k=1
i =a[1] +1
j =a[2] +1
m = a[k+1]
print(i,j,m)
7) Which of the following is not a valid identifier name in Python? Justify reason for it not
being a valid name.
a) 5Total b) _Radius c) pie d)While
Answers
Ans1. (i)
Ans 2. i) Keyword ii) identifier
Ans 3. i) iv) vi) viii)
Ans 4. ii) and iv)
Ans 5. %, ==, not, or, =
Ans 6. c)False
Ans 7. a) 5Total Reason: An identifier cannot start with a digit
Ans 8. d) 7 Sisters
Ans 9. (iv) ||
Ans 10. Valid operators are : (ii) is (iii) ^
Ans 11. Math.pow(x,y) – 4 * math.pow(x,9)
Ans 12. i) math (ii) random
Ans. 13. a) 11 b) True c) 0 d) 51 e) True
Chapter 1. Python Revision Tour-I (2 Marks Questions)
Dictionary List
1.Unordered collection of elements 1. Ordered collection of elements
2. Group of objects are not in any particular 2. Elements are in particular order
order
Keyword Identifier
1. Special word that has special meaning & is 1.User defined name given to a part of
predefined program
2.these are reserved words 2.These are not reserved words
T FINDING QUESTIONS
Q 2. t6=('a','b')
t7=('p','q')
t8=t6+t7
print(t8*2)
Ans: ('a', 'b', 'p', 'q', 'a', 'b', 'p', 'q')
Q 3. t9=('a','b')
t10=('p','q')
t11=t9+t10
print(len(t11*2))
Ans: 8
Q 4. t12=('a','e','i','o','u')
p, q, r, s, t=t12
print("p= ",p)
print("s= ",s)
print("s + p", s + p)
Ans: p= a
s= o
s + p oa
Q5.
t13=(10,20,30,40,50,60,70,80)
t14=(90,100,110,120)
t15=t13+t14
print(t15[0:12:3])
Ans: 10, 40, 70, 100
Q2. Find the errors
1. t1=(10,20,30,40,50,60,70,80)
t2=(90,100,110,120)
t3=t1*t2 Print(t5[0:12:3])
Ans: a. t1*t2 can not multiply
b. P is in uppercase in print command
c. t5 is not defined
2. t1=(10,20,30,40,50,60,70,80)
i=t1.len()
Print(T1,i)
Ans: a. len() is used wrongly
b. P is in uppercase in print command
c. T1 is not defined
3. t1=(10,20,30,40,50,60,70,80)
t1[5]=55
t1.append(90) print(t1,i)
Ans: a. 'tuple' object does not support item assignment in line 2
b. Append() Method is not with tuple
4. t1=(10,20,30,40,50,60,70,80)
t2=t1*2 t3=t2+4
print t2,t3
Ans: a) line 3 cannot concatenate with int
b) Parenthesis is missing in line 4
5. t1=(10,20,30,40,50,60,70,80)
str=”” str=index(t1(40))
print(“index of tuple is ”, str)
str=t1.max()
print(“max item is “, str)
10. Which of the following can be used as valid variable identifier(s) in Python?
(i) 4thSum (ii) Total (iii) Number# (iv) _Data
Ans: ii) and iv)
Ans:
x= int(“Enter value of x:”)
for in range (0,10):
if x==y :
print( x + y)
else:
print( x‐y)
Q2. Rewrite the following program after finding and correcting syntactical errors and
underlining it.
a, b = 0
if (a = b)
a +b = c
print(c)
Ans:
a,b = 0,0
if (a = =b) :
c=a +b
print(c)
Q3. 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,7]:
print (STRING(S))
Ans:
STRING= "WELCOME NOTE”
for S in range (0, 7) :
print (STRING [S])
Ans: a-O-U-i-e-i-
Q6. Find and write the output of the following python code :
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)
Ans: G*L*TME
Q7. 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)
Ans: 1 20 P$
4 30 P$R$
9 60 P$R$S$
Q8. Find and write the output of the following python code:
Text1="AISSCE 2018"
Text2=""
I=0
while I<len(Text1):
if Text1[I]>="0" and Text1[I]<="9":
Val = int(Text1[I])
Val = Val + 1
Text2=Text2 + str(Val)
elif Text1[I]>="A" and Text1[I] <="Z":
Text2=Text2 +(Text1[I+1])
else:
Text2=Text2 + "*"
I=I+1
print(Text2)
Ans: ISSCE*3129
Q 9. Find and write the output of the following python code:
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
Ans: 47.0
35.0
54.0
26.0
Q10. Find output generated by the following code:
line = "I'll come by then."
eline = ""
for i in line:
eline += chr(ord(i)+3)
print(eline)
Ans: L*oo#frph#e|#wkhq1
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=” ”)
(i)10 $ 7 $ (ii) 21 $ 7 $
(iii) 21 $ 10 $ (iv) 7 $
Ans: Options (ii) & (iv)
Minimum value -1
Maximum value-2
3) What possible output(s) are expected to be displayed on the screen at the time of execution of the
program from the following code?
import random
print( 100+random.randint(5,10), end = " ")
print( 100+random.randint(5,10), end = " ")
print( 100+random.randint(5,10), end = " ")
print( 100+random.randint(5,10))
(i)102 105 104 105 (ii)110 103 104 105
(iii)108 107 110 105 (iv) 110 110 110 110
Ans: (iii)108 107 110 105 (iv) 110 110 110 110
4) Find output and also find maximum value for FROM and TO
import random
name=[‘ALOK’,’HARI’,’JUGAL’,’HANS’,’RAKESH’,’KISHORE’]
FROM= random.randint(1,3)
TO= random.randint(2,4)
for k in range(FROM,TO+1):
print(name[k],end=’%’)
(i) HARI%JUGAL%HANS%Rakesh% (ii) JUGAL%HANS%RAKESH%
(iii) ALOK%HARi (iv) JUGAL%HANS%RAKESH%KISHORE%
Ans: (i) HARI%JUGAL%HANS%RAKESH% (ii) JUGAL%HANS%RAKESH%
Maximum value for FROM is - 2 and TO is - 3
5) Write the possible output (expected on screen out of (i) to (iv)) and write the maximum and
minimum values for the variable T
import random
NUM = [75,95,35,15]
T=random.randint(0,len(NUM))
for r in range (T):
if (NUM[r] % 3==0):
print(NUM[r], end="#")
6) import random
TEXT ="CBSEONLINE"
COUNT =random.randint(0,3)
C=9
while(TEXT[C]!=’L’):
print(TEXT[C]+TEXT[COUNT[+’*’,end=’ ’)
COUNT= COUNT + 1
C =C-1
9) import random
X= random.random()
Y= random.randint(0,4) print(int(X),":",Y+int(X))
(i) 0 : 0 (ii) 1 : 6 (iii) 2 : 4 (iv) 0 : 3
Ans: Option i) and iv) are correct
Q2.
t3=("sun","mon","tue","wed","thru","fri")
if "sun" in t3:
for i in range (0,3):
print(t3[i])
else:
for i in range (3,6):
print(t3[i])
Ans: sun
mon
tue
Q 3.
t4=("sun","mon","tue","wed","thru","fri")
if "sun" not in t4:
for i in range (0,3):
print(t4[i])
else:
for i in range (3,6):
print(t4[i])
Ans: wed
thur
fri
Q 4. t5=("sun",2,"tue",4,"thru",5)
if "sun" not in t5:
for i in range (0,3):
print(t5[i])
else:
for i in range (3,6):
print(t5[i])
Ans:
4
thru
5
Ans:30
TXT = ["400","200","700","90"]
CNT = 3
TOTAL = 0
for C in [3,5,7,9]:
T = TXT[CNT]
TOTAL = float(T) + C
print(TOTAL)
CNT -= 1
Ans:
93.0
705.0
207.0
409.0
Q.13. Find errors in the following code (if any) and correct the code by rewriting it and underlining the
corrections:
x= int("Enter value for x:"))
for in range[0,11]:
if x = y
print x+y
else:
Print x-y
Ans.
x=int(input("Enter value for x:"))
for y in range(0,11):
if x == y:
print(x+y)
else:
print(x-y)
Q.14. How many times is the word ‘HELLO’ printed in the following statement?
s='python rocks'
for ch ins[3:8]:
print('Hello')
Ans. 5 times
Q.15. Find errors, underline them and rewrite the same after correcting the following code:
d1=dict[]
i= 1
n=input("Enter number of entries:")
while i<=n:
a=input("Enter name:")
b=input("Enter age:")
d1(a)=b
i = i+1
l = d1.key[]
for i in l:
print(i,'\t','d1[i]')
Ans.
d1=dict()
i=1
num=int(input("Enter the no:"))
for i in range(num):
a = input("Enter name:")
b = input("Enter age:")
d1[a] = b
l = d1.keys()
i=i+1
for i in l:
print(i,"\t",d1[i])
Q.16 Rewrite the following code in Python after removing all syntax error(s). Underline each correction
donein the code.
30=To
forKinrange(0,To)
IFk%4==0:
print(K*4)
Else:
print(K+3)
Ans. To=30
for K in range(0,To):
if K%4==0:
print(K*4)
else:
print(K+3)
Ans: -
if N>=0:
print(“odd”)
else:
print("even")
Q.4 What problem occurs with the following code
X=40
while X< 50 :
print(X)
Ans: - The given code does not have the incrementing value of X, thus the loop becomes
endless.
Q5. What will be the output of the following code snippet?
values =[ ]
for i in range (1,4):
values.append(i)
print(values)
Ans:
[1]
[1 ,2 ]
[1,2,3]
Application Based Questions ( 3 Marks)
Ans:
he hello wor ld
w ll
llo wo or
Q2. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
250 = Number
WHILE Number<=1000:
if Number=>750
print (Number)
Number=Number+100
else
print( Number*2)
Number=Number+50
Ans:
Number = 250
while Number<=1000:
if Number >= 750:
print (Number)
Number = Number+100
else:
print (Number*2)
Number = Number+50
Q3. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
Val = int(input("Value:"))
Adder = 0
for C in range(1,Val,3)
Adder+=C
if C%2=0:
Print (C*10)
Else:
print (C*)
print (Adder)
Ans:
Val = int(input("Value:")) # Error 1
Adder = 0
for C in range(1,Val,3) : # Error 2
Adder+=C
if C%2==0 : # Error 3
print( C*10 ) # Error 4
else: # Error 5
print (C ) # Error 6
print(Adder)
Q4. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
25=Val
for I in the range(0,Val)
if I%2==0:
print( I+1):
Else:
print [I-1]
Ans:
Val = 25 #Error 1
for I in range(0,Val): #Error 2 and Error 3
if I%2==0:
print (I+1)
else: #Error 4
print (I-1)
Q5. 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]:
print (STRING(S))
Ans:
STRING= "WELCOME"
NOTE=" "
for S in range (0, 7) :
print (STRING [S])
Also range(0,8) will give a runtime error as the index is out of range. It should be
range(0,7)
Q6. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
a=int{input("ENTER FIRST NUMBER")}
b=int(input("ENTER SECOND NUMBER"))
c=int(input("ENTER THIRD NUMBER"))
if a>b and a>c
print("A IS GREATER")
if b>a and b>c:
Print(" B IS GREATER")
if c>a and c>b:
print(C IS GREATER)
Ans:
Q7. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
i==1
a=int(input("ENTER FIRST NUMBER"))
FOR i in range[1, 11];
print(a,"*=", i ,"=",a * i)
Ans:
i=1
a=int(input("ENTER FIRST NUMBER"))
for i in range(1,11):
print(a,"*=",i,"=",a*i)
Q8. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
a=”1”
while a>=10:
print("Value of a=",a)
a=+1
Ans:
a=1
while a<=10:
print("Value of a=",a)
a+=1
Q9. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
Num=int(input("Number:"))
sum=0
for i in range(10,Num,3)
Sum+=1
if i%2=0:
print(i*2)
Else:
print(i*3 print Sum)
Ans:
Num=int(input("Number:"))
sum=0
for i in range(10, Num,3):
sum+=1
if i%2==0:
print(i*2)
else:
print(i*3)
print(sum)
Q10. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
weather='raining'
if weather='sunny':
print("wear sunblock")
elif weather='snow':
print("going skiing")
else:
print(weather)
Ans:
weather='raining'
if weather=='sunny':
print("wear sunblock")
elif weather=='snow':
print("going skiing")
else:
print(weather)
Q11. Write the modules that will be required to be imported to execute the following
code in Python.
def main( ):
for i in range (len(string)) ):
if string [i] = = ‘’ “
print
else:
c=string[i].upper()
print( “string is:”,c)
print (“String length=”,len(math.floor()))
Q12. Rewrite the following code in python after removing all syntax error(s).Underline
each correction done in the code
x=integer(input('Enter 1 or 10'))
if x==1:
for x in range(1,11)
Print(x)
Else:
for x in range(10,0,-1):
print(x)
Ans:
x=int(input('Enter 1 or 10'))
if x==1:
for x in range(1,11):
print(x)
else:
for x in range(10,0,-1):
print(x)
Q13. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
30=To
for K in range(0,To)
IF k%4==0:
print (K*4)
else
print (K+3)
Ans :
To=30
for K in range(0,To) :
if k%4==0:
print (K*4)
else:
print (K+3)
WORKSHEET
DATA FILE HANDLING
1 Give one difference between Text file and Binary File
Ans Text file contains EOL character at the end of every line, there is no such character
in binary file
2 Write a Python statement to open a text file “DATA.TXT” so that new contents can
be written on it.
Ans f = open(„DATA.TXT‟,‟w‟)
3 Write a Python statement to open a text file “DATA.TXT” so that new content can be
added to the end of file
Ans f = open(„DATA.TXT‟,‟a‟)
4 Write a Python statement to open a text file “DATA.TXT” so that existing contents
can be read from file.
Ans f = open(„DATA.TXT‟)
5 A file “MYDATA.TXT” is opened as
file1 = open(“MYDATA.TXT”)
Write a Python statement to close this file.
Ans file1.close()
6 What is the different in file opening mode “a” and “w” ?
Ans “w” is used to write in file from the beginning. If file already exists then it will
overwrite the previous content.
“a” (append – add at the end ) is also used to write in file. If file already exists it will
write after the previous content i.e. it will not overwrite the previous content and
add new content after the existing content.
6 What is the significance of adding „+‟ with file opening mode, with context to „r+‟ ?
Ans “+” is used to add alternate action with specified mode i.e. if used with “r” as “r+” it
means it will allows to read and alternate action write.
7 What is the difference between readline() and readlines() ?
Ans readline() allows to read single line from file and return the content as string.
readlines() function will read all the lines from file and return it as a List of
lines/string.
8 What is the purpose of using flush() in file handling operations ?
Ans When we are writing data in file the content will be stored in file only when we close
the file. Before closing the file i.e. during the operations fill will be created but the
content will be in buffer not in file and when we close the file content will be shifted
to file from buffer.
flush() allows the user to send content in file before closing the file. It means when
flush() is used it will clear the buffer and transfer content to file.
9 What is the advantage of opening file using „with‟ keyword?
Ans With keyword reduces the overheads involve in file handling operations like closing
the file after operation or handling the file closing with exceptions. When file is
opened using “with” it will manage these things i.e. file will be automatically closed
after operations. It ensures the closing of file even if exceptions arises.
10 Considering the content stored in file “CORONA.TXT”
O Corona O Corona
Jaldi se tum Go na
Social Distancing ka palan karona
sabse 1 meter ki duri rakhona
Lockdown me ghar me ho to
Online padhai karona
1|Page
www.python4csip.com
2|Page
www.python4csip.com
15 Write a function in python to read lines from file “POEM.txt” and count how many
times the word “Corona” exists in file.
For e.g. if the content of file is :
O Corona O Corona
Jaldi se tum Go na
Social Distancing ka palan karona
sabse 1 meter ki duri rakhona
Lockdown me ghar me ho to
online padhai karona
O Corona O Corona
Jaldi se tum Go na
Output should be: Number of time word Corona occurs : 4
Ans Solution 1:
def CoronaCount():
f = open('poem.txt')
count = 0
for line in f:
words = line.lower().split()
count += words.count('corona')
print("Number of time words Corona occurs: ",count)
Solution 2:
def CoronaCount():
f = open('poem.txt')
count = 0
for line in f:
words = line.split()
for w in words:
if w.lower()=='corona':
count+=1
print("Number of time words Corona occurs: ",count)
16 Write a function in python to read lines from file “POEM.txt” and display all those
words, which has two characters in it.
For e.g. if the content of file is
O Corona O Corona
Jaldi se tum Go na
Social Distancing ka palan karona
sabse 1 meter ki duri rakhona
Lockdown me ghar me ho to
online padhai karona
O Corona O Corona
Jaldi se tum Go na
Output should be : se Go na ka ki me me ho to se Go na
Ans def TwoCharWord():
f = open('poem.txt')
count = 0
for line in f:
words = line.split()
for w in words:
if len(w)==2:
print(w,end=' ')
17 Write a function COUNT() in Python to read contents from file “REPEATED.TXT”, to
count and display the occurrence of the word “Catholic” or “mother”.
For example:
If the content of the file is “Nory was a Catholic because her mother was a Catholic , and
Nory‟s mother was a Catholic because her father was a Catholic , and her father was a
Catholic because his mother was a Catholic , or had been
3|Page
www.python4csip.com
O Corona O Corona
Jaldi se tum Go na
Social Distancing ka palan karona
Sabse 1 meter ki duri rakhona
Lockdown me ghar me ho to
online padhai karona
O Corona O Corona
Jaldi se tum Go na
The function should display:
Social Distancing ka palan karona
Sabse 1 meter ki duri rakhona
Ans def dispS():
f = open('poem.txt')
count = 0
for line in f:
if line[0].lower()=='s':
print(line)
19 Write a function COUNTSIZE() in Python to read the file “POEM.TXT” and display
size of file. For e.g. if the content of file is :
O Corona O Corona
Jaldi se tum Go na
Social Distancing ka palan karona
sabse 1 meter ki duri rakhona
Lockdown me ghar me ho to
online padhai karona
O Corona O Corona
Jaldi se tum Go na
The function should display
Size of file is 184
Ans def COUNTSIZE():
f = open('poem.txt')
s = f.read()
print(„Size of file is „,len(s))
20 Write a python function ATOEDISP() for each requirement in Python to read the file
“NEWS.TXT” and
(I) Display “E” in place of all the occurrence of “A” in the word COMPUTER.
(II) Display “E” in place of all the occurrence of “A”:
I SELL COMPUTARS. I HAVE A COMPUTAR. I NEED A COMPUTAR. I WANT A
COMPUTAR. I USE THAT COMPUTAR. MY COMPUTAR CRASHED.
The function should display
4|Page
www.python4csip.com
Ans f.write(str.encode())
7 ________ function is used to fetch binary data from binary file
Ans
8 ________ function is used to convert binary string to string
Ans read() and load()
9 ________ function is used in binary mode to send the read pointer to desired
position
Ans seek()
5|Page
www.python4csip.com
10 Consider a binary file which stores Name of employee, where each name
occupies 20 bytes (length of each name) in file irrespective of actual
characters. Now you have to write code to access the first name, 5th name and
last name.
f = open("Emp.txt","rb")
s = ________ #code to get first record
print(s.decode())
___________ # code to position at 5th record
s = f.read(size)
print(s.decode())
___________ # code to position at last record
s = f.read(20)
print(s.decode())
f.close()
Ans f.read(20)
f.seek((5-1)*20)
f.read(((os.path.getsize(„Emp.txt‟)/20)-1)
11 Write a Python statement to reposition the read pointer to 20 bytes back
from the current position.
f = open("Emp.txt","rb")
f.read(20)
f.read(20)
f.read(20)
f.___________ # reposition read pointer to previous record
f.close()
Ans f.seek(-20,1)
12 Write a function RECCOUNT() to read the content of binary file „NAMES.DAT‟
and display number of records ( each name occupies 20 bytes in file ) in it.
For. e.g. if the content of file is:
SACHIN
AMIT
AMAN
SUSHIL
DEEPAK
HARI SHANKER
Function should display
Total Records are 6
Ans import os
def RECCOUNT():
size_of_rec = 20 #Each name will occupy 20 bytes
file_len = os.path.getsize('Names.dat')
num_record = file_len/size_of_rec
print("Total Records are :",num_record)
13 Write a function SCOUNT() to read the content of binary file „NAMES.DAT‟ and
display number of records (each name occupies 20 bytes in file ) where name
begins from „S‟ in it.
6|Page
www.python4csip.com
7|Page
www.python4csip.com
Ans sys
23 From the given path identify the type of each:
(i) C:\mydata\web\resources\img.jpg
(ii) ..\web\data.conf
Ans (i) Absolute
(ii) Relative
24 Consider the following Binary file „Emp.txt‟, Write a function RECSHOW() to
display only those records who are earning more than 7000
if found==False:
print("## SORRY EMPLOYEE NUMBER NOT FOUND ##")
f.close()
24 CSV stands for _______________________
Ans Comma Separate Value
25 __________ object is used to read data from csv file?
Ans reader
26 __________ object is used to perform write operation on csv file.
Ans writer
27 __________ function of writer object is used to send data to csv file to store.
Ans writerow()
28 Consider the following CSV file (emp.csv):
1,Peter,3500
2,Scott,4000
3,Harry,5000
4,Michael,2500
5,Sam,4200
Write Python function DISPEMP() to read the content of file emp.csv and display
only those records where salary is 4000 or above
8|Page
www.python4csip.com
Write a Python function DISPEMP() to read the content of file emp.csv and count
how many employee are earning less than 5000
Ans import csv
def DISPEMP():
with open('emp.csv') as csvfile:
myreader = csv.reader(csvfile,delimiter=',')
count=0
print("%10s"%"EMPNO","%20s"%"EMP NAME","%10s"%"SALARY")
print("==================================================")
for row in myreader:
if int(row[2])<5000:
count+=1
print("==================================================")
print("%40s"%"#EMPLOYEE GETTING SALARY <5000 :",count)
print("==================================================")
30 Consider the following CSV file (emp.csv):
1,Peter,3500
2,Scott,4000
3,Harry,5000
4,Michael,2500
5,Sam,4200
Write a Python function SNAMES() to read the content of file emp.csv and display
the employee record whose name begins from „S‟ also show no. of employee with
first letter „S‟ out of total record.
Output should be:
2,Scott,4000
5,Sam,4200
Number of „S‟ names are 2/5
Ans import csv
def SNAMES():
with open('emp.csv') as csvfile:
myreader = csv.reader(csvfile,delimiter=',')
count_rec=0
count_s=0
for row in myreader:
9|Page
www.python4csip.com
if row[1][0].lower()=='s':
print(row[0],',',row[1],',',row[2])
count_s+=1
count_rec+=1
print("Number of 'S' names are ",count_s,"/",count_rec)
31 Write a python function CSVCOPY() to take sourcefile, targetfile as parameter
and create a targetfile and copy the contents of sourcefile to targetfile
Ans import csv
def CSVCOPY(sourcefile,targetfile):
with open(sourcefile) as csvfile:
f2 = open(targetfile,'w')
mywriter=csv.writer(f2,delimiter=',')
myreader = csv.reader(csvfile,delimiter=',')
for row in myreader:
mywriter.writerow([row[0],row[1],row[2]])
f2.close()
10 | P a g e
(Concept of Python Libraries)
CBSE Exam Solved Questions
1 Name the Python Library modules which need to be imported to invoke the following functions:
(i) load() (ii) dump()
2 Name the Python Library modules which need to be imported to invoke the following functions:
Answers of Worksheet 2
pickle module
load()/dump()
math module
log()/pow()/gamma()/sin()/cos()/tan()/factorial()/degrees()/radians()/remainder()/comb()/dist()/exp()/erf()/
ceil( )/floor()/trunk()/fabs()/abs()
random module
randint()/randrange()/getrandbits()/setstate()/getstate()/uniform()/speed()/choice()/choices()/shuffle()
/sample()/random()/triangular()/gauss()
A module is a file containing python definitions, variables and classes and statement with .py extension A
Python package is simply a directory of python modules.
A library in python is collection of various packages. Conceptually there is no difference between package
and python Library.
Creation of Module :
The following point must be noted before creating a module
• A module name should always end with .py extension
• We will not able to import module if it does not end with .py
• A module name must not be a Python keyword
A module is simply a python file which contains functions, classes and variables
Let us consider the following example of a module name area.py which contains three functions name
area_circle(r),area_square(s),area_rect(l,b)
import math
def area_circle(r):
return math.pi*r*r def area_square(s):
return s*s def area_rect(l,b):
return l*b
importing Modules:
There are two ways to import a modules
1) Using import statement: we can import single as well as multiple modules
1.1 For importing Single module
Syntax: import modulename
2) Using from Statement :To import some particular Function(s) from module we will use import
statement
2.1 To import Particular Function
Syntax: From <module name> import <write name of Function(s)>
OR
From <module name> import *
(This statement will import all the functions from modules)
To use a function inside a module you have to directly call function if your are importing the modules using
from statement
Example : Let us consider the following code.In this program we import the module with the help of from
statement and directly use the function instead of specifying Module name
Note : we can also provide alias name to function of modules whenever we are using it with python from
statement and whenever we have to call any statement then we have to provide function alias name instead
of function original name ‘
Example: from area import area_Circle as C
C(6) # C is the alias name of function area_circle of module area
Q4. Which of the following is false about “import module name” form of import?
a) The namespace of imported module becomes part of importing module
b) This form of input prevents name clash
c) The namespace of imported module becomes available to importing module
d) The identifiers in module are accessed as: modulename.identifier
Q5. what is the order of namespaces in which python looks for an identifier?
a) python first searches the global namespace, then the local namespace and finally the built in
namespace
b) python first searches the local namespace, then the global namespace and finally the built in
namespace
c) python first searches the built in namespace, then the global namespace and finally the local
namespace
d) python first searches the built in namespace , then the local namespace and finally the global
namespace
Q7. Which operator is used in the python to import all modules from packages?
(a) . operator (b) * operator
(c) ‐> symbol (d) , operator
Q8. Which file must be part of the folder containing python module file to make it importable python
package?
(a) init.py (b) steup .py
(c) init .py (d) setup.py
Q9. In python which is the correct method to load a module math?
(a) include math
(b) import math
(c) #include<math.h>
(d) using math
Q10. Which is the correct command to load just the tempc method from a module called usable?
(a) import usable,tempc (b) Import tempc from usable
(c) from usable import tempc (d) import tempc
Q3. What happens when python encounters an import statement in a program? What would happen, if there
is one more important statement for the same module, already imported in the same program?
Q2. Consinder the code given in above and on the basis of it, complete the code given below:
# import the subtract function #from the math_operation module
1. #subtract 1from 2
2. print( (2,1) ) # output : 1
# Import everything from math operations
3.
print (subtract (2,1) ) # output:1
print (add (1,1) ) # output:2
Ans 4. In the “from–import” from of import, the imported identifiers (in this case factorial()) become part of
the current local namespace and hence their module’s name aren’t specified along with the module name.
Thus, the statement should be:
print( factorial (5) )
Ans 5. There is a name clash. A name clash is a situation when two different entities with the same name
become part of the same scope. Since both the modules have the same function name, there is a name clash,
which is an error..
Ans 1 . 1. input
2. math_operation_name_
3. math.operation.add
Ans 4. The possible outputs could be (ii), (iii) (v) and (vi).
The reason being that randint( ) would generate an integer between range 2…4, which is then raised to
power 2.
www.python4csip.com
WORKSHEET
DATA STRUCTURE
1 Stack is a data structure that follows _________ order
a. FIFO
b. LIFO
c. LILO
d. FILO
Ans b. LIFO
2 Queue is a data structure that follows ___________ order
a. FIFO
b. LIFO
c. LILO
m
d. FILO
Ans a. FIFO
3 What will be the output of the following Python code :
co
mylist =[‘java’,’c++’,’python’,’vb’,’vc++’,’php’,’cobol’]
print(mylist.pop())
mylist.append(‘c#’)
print(len(mylist))
p.
mylist.insert(3,’basic’)
print(mylist)
mylist.sort()
si
print(mylist)
print(mylist.index(‘php’))
Ans cobol
4c
7
['java', 'c++', 'python', 'basic', 'vb', 'vc++', 'php', 'c#']
['basic', 'c#', 'c++', 'java', 'php', 'python', 'vb', 'vc++']
on
4
4 Identify the error in following code:
(i) List1 = [10,20,30,40]
List1[4]=100
Name=”Michael Jackson”
th
(ii)
Name[2]=”k”
Ans (i) Index 4 is out of range, because List1 contains 4 items (Index 0 to 3 only)
(ii) String is immutable type so we can’t change any character of string in place.
py
Page | 1
www.python4csip.com
m
(v) Keyboard buffering
Ans (i) Stack
(ii) Queue
co
(iii) Stack
(iv) Stack
(v) Queue
8 Write down the steps to perform Binary Search for the following items in the
given list MYLIST.
(i)
(ii)
17
30
p.
si
MYLIST = [5,11,17,19,25,29,30,32,46,90]
Ans (i)
4c
First we will find mid, here low = 0 and high=9
mid = (low+high)//2 => (0+9)//2 = 4
Now we will compare 17 with middle position item MYLIST[4] which is 25
25 > 17 therefore 17 will be towards the left of 25 so we will update high=mid-1
on
(ii)
First we will find mid, here low = 0 and high=9
mid = (low+high)//2 => (0+9)//2 = 4
Now we will compare 30 with middle position item MYLIST[4] which is 25
25 < 30 therefore 30 will be towards the right of 25 so we will update low=mid+1
Page | 2
www.python4csip.com
m
9 Given the list:
MYLIST = [5,11,17,19,25,29,30,30,32,46,90]
co
Write down the Python statements for the following requirement:
(i) To find the number of items in MYLIST
(ii) To find the frequency of item 30 in MYLIST i.e. how many times 30 is in
MYLIST
p.
(iii) Write the code to insert 45 in the above sorted list to its correct position (do
not disturb the sorting)
si
(iv) Write the code to delete 17 from the above sorted list
Ans (i) print(len(MYLIST))
4c
(ii) print(MYLIST.count(30))
(iii) import bisect
bisect.insort(MYLIST,45)
print(MYLIST)
on
(iv) MYLIST.remove(17)
print(MYLIST)
5 11 17 19 25 29 30 32 56 90
Output should be :
Total = 133
Ans def sumAlternate(MYLIST):
sum=0
for i in range(0,len(MYLIST),2):
sum+=MYLIST[i]
print("Total = ",sum)
Page | 3
www.python4csip.com
11 Write the function SumEvenOdd(MYLIST) to find the sum of all Even elements
and sum of all Odd elements present in MYLIST
For e.g if the elements are
8 12 17 19 25 29 33 32 56 90
Output should be:
Even Sum = 198
Odd Sum = 123
Ans def SumEvenOdd(MYLIST):
sume=0
sumo=0
for i in range(len(MYLIST)):
if MYLIST[i]%2==0:
sume+=MYLIST[i]
else:
m
sumo+=MYLIST[i]
print("Even Sum = ",sume)
print("Odd Sum = ",sumo)
co
12 Write the function CountEvenOdd(MYLIST) to find the count of all Even
elements and sum of all Odd elements.
For e.g if the elements are
p.
8 12 17 19 25 28 33 32 56 90
Output should be:
Even Count = 6
Odd Sum = 4
si
Ans def CountEvenOdd(MYLIST):
counte=0
4c
counto=0
for i in range(len(MYLIST)):
if MYLIST[i]%2==0:
counte+=1
on
else:
counto+=1
print("Even Count = ",counte)
print("Odd Count = ",counto)
th
Page | 4
www.python4csip.com
m
for i in range(len(MYLIST)):
if MYLIST[i]%2==0:
MYLIST[i]//=2
co
else:
MYLIST[i]*=2
16 Write a function Sum7End(MYLIST), which display only those items from the list
which ends from the digit 7, also find total of these elements.
sum=0
for i in range(len(MYLIST)):
if MYLIST[i]%10==7:
print(MYLIST[i])
th
sum+=MYLIST[i]
print('Total=',sum)
17 Write QueueUp(Student) and QueueDel(Student) methods/function Python to add a
py
new Student and delete a Student from a List of Student names, considering them to
act as insert and delete operations of the Queue data structure
Ans def QueueUp(Student):
name = input('Enter any name')
Student.append(name)
def QueueDel(Student):
if len(Student)==0:
print('Underflow')
else:
name = Student.pop(0)
print('Deleted Name was ',name)
Page | 5
www.python4csip.com
m
act as insert and display operations of the Queue data structure
Ans def QueueUp(Student):
name = input('Enter Name')
co
Student.append(name)
def QueueDisp(Student):
if len(Student)==0:
print('Underflow')
else:
p.
print('Queue Items Front-to-Rear')
for i in range(len(Student)):
si
print(Student[i])
20 Write a function in python, Push(Employee) and Show(Employee) to add a new
4c
Employee and display Employee names from a List of Employee, considering them to
act as push and show operations of the Stack data structure.
Ans def Push(Employee):
name=input('Enter name :')
on
Employee.append(name)
def Show(Employee):
if len(Employee)==0:
print('Underflow')
th
else:
print('Employee Names ')
for i in range(len(Employee)):
py
print(Employee[i])
Page | 6
www.python4csip.com
m
After Second Pass
[53, 51, 52, 54, 55, 56, 57]
After Third Pass
co
[51, 52, 53, 54, 55, 56, 57]
23 Consider the randomly ordered numbers stored in a list
55,53,57,51,52,54,56
Show the content of list after the First, Second and third pass of the Insertion sort
p.
method used for arranging in ascending order
Note: show the status of all elements after each pass very clearly encircling the
changes.
si
Ans After Pass 1
[53, 55, 57, 51, 52, 54, 56]
4c
After Pass 2
[53, 55, 57, 51, 52, 54, 56]
After Pass 3
[51, 53, 55, 57, 52, 54, 56]
on
Page | 7
www.python4csip.com
25 Raj is a Python programmer working on sorting module. For a small list of values he
has written the Bubble sorting code but code is not executing. Help Raj and rewrite
the code after removing all the errors and underlining the correction(s) made:
def BubbleSort(num):
for i in range(num-1):
for j in range(num-1-i):
if num[j+1]>num[j]:
num[i],num[j+1]=num[j+1],num[i]
Ans def BubbleSort(num):
for i in range(len(num)-1):
for j in range(len(num)-1-i):
if num[j]>num[j+1]:
m
num[j],num[j+1]=num[j+1],num[j]
26 Raj is a Python programmer working on sorting module. For this he has written the
Insertion sorting code but code is not executing. Help Raj and rewrite the code after
co
removing all the errors and underlining the correction(s) made:
def InsertionSort(mylist):
i=1
while i<len(mylist):
p.
key=mylist[i]
j=i-1
while j>=0 and mylist[j]<key:
si
mylist[j]=mylist[j+1]
j-=1
4c
key = mylist[j+1]
i-=1
Ans def InsertionSort(mylist):
on
i=1
while i<len(mylist):
key=mylist[i]
th
j=i-1
while j>=0 and mylist[j]>key:
py
mylist[j+1]=mylist[j]
j-=1
mylist[j+1]=key
i+=1
27 Write a Python function/method Count5and7(N), to find and display count of all
number between 1 to N which are either divisible by 5 or by 7.
For e.g. if the N is 20 then output should be:
Count=6
As (5,7,10,14,15,20) are the number between 1 to N which are divisible by either 5 or by 7)
Page | 8
www.python4csip.com
m
[66,88,11,22,44,55]
Ans def SwapMiddle(Codes):
co
i=0
mid = len(Codes)//2
p.
while i<mid:
Codes[i],Codes[mid+i]=Codes[mid+i],Codes[i]
i+=1
si
29 Raj is a Python programmer working of Data structure Stack to store name of visitors,
he has implemented the code for PUSH and POP, but both functions are not
4c
producing the correct result. Help Raj in identifying the error(s) and also write the
Correct code for specific line number:
def PUSH(VISITOR,name):
on
name.append(VISITOR) #Line 1
top = len(VISITOR)-1 #Line 2
def POP(VISITOR):
th
if len(VISITOR)==1: #Line 3
return "Sorry! No Visitor to delete " #Line 4
else:
py
Ans #Line 1
VISITOR.append(name)
Page | 9
www.python4csip.com
#Line 3
if len(VISITOR)==0:
#Line 5
val = VISITOR.pop()
#Line 6
if len(VISITOR)==0:
#Line 8
top = len(VISITOR)-1
30 Raj is a Python programmer working of Data structure Queue to store name of
REQUESTNO, he has implemented the code for ENQUEUE and DEQUEUE, for insert
and delete operation in Queue resp. But both functions are not producing the correct
result. Help Raj in identifying the Line Number where code is incorrect and also write
the Correct code for same Line Number.
def Enqueue(REQUESTNO,item):
m
REQUESTNO.add(item) #Line 1
if len(REQUESTNO)==1: #Line 2
front=rear=1 #Line 3
co
else:
rear=len(REQUESTNO)-1 #Line4
def Dequeue(REQUESTNO):
if REQUESTNO==0:
else:
print("Underflow")
#Line 5
#Line 6
p.
si
val = REQUESTNO.pop(len(REQUESTNO)-1) #Line 7
if len(REQUESTNO)==0: #Line 8
4c
front=None #Line 9
return val
Ans #Line 1
REQUESTNO.append(item)
on
#Line 3
front = rear = 0
#Line 5
if len(REQUESTNO)==0:
th
#Line 7
val = REQUESTNO.pop(0)
#Line 9
py
Page | 10
MYSQL REVISION TOUR
MYSQL
It is freely available open source Relational Database Management System (RDBMS) that uses Structured Query
Language(SQL). In MySQL database , information is stored in Tables. A single MySQL database can contain many tables
at once and store thousands of individual records.
SQL is a language that enables you to create and operate on relational databases, which are sets of related information
stored in tables.
A data model refers to a set of concepts to describe the structure of a database , and certain constraints (restrictions)
that the database should obey. The four data model that are used for database management are :
1. Relational data model : In this data model, the data is organized into tables (i.e. rows and columns). These tablesare
called relations.
2. Hierarchical data model 3. Network data model 4. Object Oriented data model
6. Primary Key : This refers to a set of one or more attributes that can uniquely identify tuples within the relation.
7. Candidate Key : All attribute combinations inside a relation that can serve as primary key are candidate keys as these
are candidates for primary key position.
8. Alternate Key : A candidate key that is not primary key, is called an alternate key.
9. Foreign Key : A non-key attribute, whose values are derived from the primary key of some other table, is known as
foreign key in its current table.
REFERENTIAL INTEGRITY
- A referential integrity is a system of rules that a DBMS uses to ensure that relationships between records in related
tables are valid, and that users don’t accidentally delete or change related data. This integrity is ensured by foreign
key.
MySQL ELEMENTS
LITERALS
It refer to a fixed data value. This fixed data value may be of character type or numeric type. For example, ‘replay’ ,
‘Raj’, ‘8’ , ‘306’ are all character literals.
Numbers not enclosed in quotation marks are numeric literals. E.g. 22 , 18 , 1997 are all numeric literals.
Numeric literals can either be integer literals i.e., without any decimal or be real literals i.e. with a decimal point e.g. 17
is an integer literal but 17.0 and 17.5 are real literals.
DATA TYPES
Data types are means to identify the type of data and associated operations for handling it. MySQL data types are
divided into three categories:
Numeric
Date and time
String types
DATABASE COMMNADS
OR
INSERT INTO employee (ECODE , ENAME , GENDER , GRADE , GROSS)
VALUES(1001 , ‘Ravi’ , ‘M’ , ‘E4’ , 50000);
In order to insert another row in EMPLOYEE table , we write again INSERT command :
INSERT INTO employee
VALUES(1002 , ‘Akash’ , ‘M’ , ‘A1’ , 35000);
- To insert value NULL in a specific column, we can type NULL without quotes and NULL will be inserted in that
column. E.g. in order to insert NULL value in ENAME column of above table, we write INSERT command as :
GENDER
M
M
F
M
F
F
DISTINCT(GENDER)
M
F
e.g. to display ECODE, ENAME and GRADE of those employees whose salary is between 40000 and 50000, command
is:
SELECT ECODE , ENAME ,GRADE
FROM EMPLOYEE
WHERE GROSS BETWEEN 40000 AND 50000 ;
Output will be :
- The NOT IN operatorfinds rows that do not match in the list. E.g.
SELECT * FROM EMPLOYEE
WHERE GRADE NOT IN (‘A1’ , ‘A2’);
Output will be :
e.g. to display names of employee whose name starts with R in EMPLOYEE table, the command is :
SELECT ENAME
FROM EMPLOYEE
WHERE ENAME LIKE ‘R%’ ;
Output will be :
ENAME
Ravi
Ruby
Output will be :
Output will be :
e.g. to display the details of employees in EMPLOYEE table in alphabetical order, we use command :
SELECT *
FROM EMPLOYEE
ORDER BY ENAME ;
Output will be :
ECODE ENAME GENDER GRADE GROSS
1002 Akash M A1 35000
1004 Neela F B2 38965
1009 Neema F A2 52000
1001 Ravi M E4 50000
1006 Ruby F A1 45000
1005 Sunny M A2 30000
e.g. display list of employee in descending alphabetical order whose salary is greater than 40000.
SELECT ENAME
FROM EMPLOYEE
WHERE GROSS > 40000
ORDER BY ENAME desc ;
Output will be :
ENAME
Ravi
Ruby
Neema
e.g. to change the salary of employee of those in EMPLOYEE table having employee code 1009 to 55000.
UPDATE EMPLOYEE
SET GROSS = 55000
WHERE ECODE = 1009 ;
UPDATING MORE THAN ONE COLUMNS
e.g. to update the salary to 58000 and grade to B2 for those employee whose employee code is 1001.
UPDATE EMPLOYEE
SET GROSS = 58000, GRADE=’B2’
WHERE ECODE = 1009 ;
OTHER EXAMPLES
Increase the salary of each employee by 1000 in the EMPLOYEE table.
UPDATE EMPLOYEE
SET GROSS = GROSS +100 ;
Double the salary of employees having grade as ‘A1’ or ‘A2’ .
UPDATE EMPLOYEE
SET GROSS = GROSS * 2 ;
WHERE GRADE=’A1’ OR GRADE=’A2’ ;
Change the grade to ‘A2’ for those employees whose employee code is 1004 and name is Neela.
UPDATE EMPLOYEE
SET GRADE=’A2’
WHERE ECODE=1004 AND GRADE=’NEELA’ ;
So if we do not specify any condition with WHERE clause, then all the rows of the table will be deleted. Thus above
line will delete all rows from employee table.
DROPPING TABLES
The DROP TABLE command lets you drop a table from the database. The syntax of DROP TABLE command is :
DROP TABLE <tablename> ;
e.g. to drop a table employee, we need to write :
DROP TABLE employee ;
Once this command is given, the table name is no longer recognized and no more commands can be given on that table.
After this command is executed, all the data in the table along with table structure will be deleted.
To add a column to a table, ALTER TABLE command can be used as per following syntax:
However if you specify NOT NULL constraint while adding a new column, MySQL adds the new column with the default
value of that datatype e.g. for INT type it will add 0 , for CHAR types, it will add a space, and so on.
e.g. Given a table namely Testt with the following data in it.
Col1 Col2
1 A
2 G
Now following commands are given for the table. Predict the table contents after each of the following statements:
(i) ALTER TABLE testt ADD col3 INT ;
(ii) ALTER TABLE testt ADD col4 INT NOT NULL ;
(iii) ALTER TABLE testt ADD col5 CHAR(3) NOT NULL ;
(iv) ALTER TABLE testtADD col6 VARCHAR(3);
MODIFYING COLUMNS
Column name and data type of column can be changed as per following syntax :
DELETING COLUMNS
To delete a column from a table, the ALTER TABLE command takes the following form :
e.g. to add PRIMARY KEY constraint on column ECODE of table EMPLOYEE , the command is :
ALTER TABLE EMPLOYEE
ADD PRIMARY KEY (ECODE) ;
REMOVING CONSTRAINTS
- To remove primary key constraint from a table, we use ALTER TABLE command as :
ALTER TABLE <table name>
DROP PRIMARY KEY ;
- To remove foreign key constraint from atable, we use ALTER TABLE command as :
ALTER TABLE <table name>
DROP FOREIGN KEY ;
ENABLING/DISABLING CONSTRAINTS
Only foreign key can be disabled/enabled in MySQL.
To disable foreign keys : SET FOREIGN_KEY_CHECKS = 0 ;
To enable foreign keys : SET FOREIGN_KEY_CHECKS = 1 ;
INTEGRITY CONSTRAINTS/CONSTRAINTS
- A constraint is a condition or check applicable on a field(column) orset of fields(columns).
- Common types of constraints include :
Columns SID and Last_Name cannot include NULL, while First_Name can include NULL.
DEFAULT CONSTARINT
The DEFAULT constraint provides a default value to a column when the INSERT INTO statement does not provide a
specific value. E.g.
UNIQUE CONSTRAINT
- The UNIQUE constraint ensures that all values in a column are distinct. In other words, no two rows can hold the
same value for a column with UNIQUE constraint.
e.g.
CREATE TABLE Customer
( SID integer Unique ,
Last_Name varchar(30) ,
First_Name varchar(30) ) ;
Column SID has a unique constraint, and hence cannot include duplicate values. So, if the table already contains the
following rows :
CHECK CONSTRAINT
- The CHECK constraint ensures that all values in a column satisfy certain conditions. Once defined, the table will only
insert a new row or update an existing row if the new value satisfies the CHECK constraint.
e.g.
CREATE TABLE Customer
( SID integer CHECK(SID > 0),
Last_Name varchar(30) ,
First_Name varchar(30) ) ;
will result in an error because the values for SID must be greater than 0.
- You can define a primary key in CREATE TABLE command through keywords PRIMARY KEY. e.g.
Or
CREATE TABLE Customer
( SID integer,
Last_Name varchar(30) ,
First_Name varchar(30),
PRIMARY KEY (SID) ) ;
- The latterway is useful if you want to specify acomposite primary key, e.g.
e.g.
Parent Table
TABLE: STUDENT
ROLL_NO NAME CLASS
Primary key
1 ABC XI
2 DEF XII
3 XYZ XI Child Table
TABLE: SCORE
ROLL_NO MARKS
1 55
2 83
3 90
Here column Roll_No is a foreign key in table SCORE(Child Table) and it is drawing its values from Primary key
(ROLL_NO) of STUDENT table.(Parent Key).
REFERENCING ACTIONS
Referencing action with ON DELETE clause determines what to do in case of a DELETE occurs in the parent table.
Referencing action with ON UPDATE clause determines what to do in case of a UPDATE occurs in the parent table.
Table : EMPL
1. AVG( )
This function computes the average of given data.
e.g. SELECT AVG(SAL)
FROM EMPL ;
Output
AVG(SAL)
6051.6
2. COUNT( )
This function counts the number of rows in a given column.
If you specify the COLUMN name in parenthesis of function, then this function returns rows where COLUMN is not
null.
If you specify the asterisk (*), this function returns all rows, including duplicates and nulls.
3. MAX( )
This function returns the maximum value from a given column or expression.
5. SUM( )
This function returns the sum of values in given column or expression.
Output
SUM(SAL)
30258
NESTED GROUP
- To create a group within a group i.e., nested group, you need to specify multiplefields in the GROUP BY expression.
e.g. To group records job wise within Deptno wise, you need to issue a query statement like :
MySQL FUNCTIONS
A function is a special type of predefined command set that performs some operation and returns a single value.
Types of MySQL functions : String Functions , Maths Functions and Date & Time Functions.
Table : EMPL
STRING FUNCTIONS
1. CONCAT( ) - Returns the Concatenated String.
Syntax : CONCAT(Column1 , Column2 , Column3, …….)
e.g. SELECT CONCAT(EMPNO , ENAME) FROM EMPL WHEREDEPTNO=10;
Output
CONCAT(EMPNO , ENAME)
8369SMITH
8912SUR
e.g.2.
SELECT LENGTH(ENAME) FROM EMPL;
Output
LENGTH(ENAME)
5
4
4
4
3
NUMERIC FUNCTIONS
These functions accept numeric values and after performing the operation, return numeric value.
1. MOD( ) – Returns the remainder of given two numbers. e.g. SELECT MOD(11 , 4) ;
Output
MOD(11, 4 )
3
2. POW( ) / POWER( ) - This function returns mn i.e , a numberm raised to the nth power.
e.g. SELECT POWER(3,2) ;
Output
POWER(3, 2 )
9
e.g. 2. SELECT ROUND(15.193 , -1); - This will convert the number to nearest ten’s .
Output
ROUND(15.193 , -1)
20
5. SQRT( ) – This function returns the square root of a given number. E.g.
SELECT SQRT(25) ;
Output
SQRT(25)
5
6. TRUNCATE( ) – This function returns a number with some digits truncated. E.g.
SELECT TRUNCATE(15.79 , 1) ;
Output
TRUNCATE(15.79 , 1)
15.7
E.g. 2. SELECT TRUNCATE(15.79 , -1); - This command truncate value 15.79 to nearest ten’s place.
Output
TRUNCATE(15.79 , -1)
10
2. DATE( ) – This function extracts the date part from a date. E.g.
SELECT DATE( ‘2016-02-09’) ;
Output
DATE( ‘2016-02-09’)
09
3. MONTH( ) – This function returns the month from the date passed. E.g.
SELECT MONTH( ‘2016-02-09’) ;
Output
MONTH( ‘2016-02-09’)
02
6. DAYOFMONTH( ) – This function returns the day of month. Returns value in range of 1 to 31.
E.g. SELECT DAYOFMONTH( ‘2016-12-14’) ;
Output
DAYOFMONTH( ‘2016-12-14’)
14
7. DAYOFWEEK( ) – This function returns the day of week. Return the weekdayindex for date. (1=Sunday,
2=Monday,……., 7=Saturday)
SELECT DAYOFWEEK( ‘2016-12-14’) ;
Output
DAYOFWEEK( ‘2016-12-14’)
4
8. DAYOFYEAR( ) – This function returns the day of the year. Returns the value between 1 and 366. E.g.
SELECT DAYOFYEAR(‘2016-02-04) ;
Output
DAYOFYEAR( ‘2016-02-04’)
35
10. SYSDATE( ) – It also returns the current date but it return the time at which SYSDATE( ) executes. It differs from the
behavior for NOW( ), which returns a constant time that indicates the time at which the statement began to execute.
e.g. SELECT SYSDATE( ) ;
JOINS
- A join is a query that combines rows from two or more tables. In a join- query, more than
one table are listed in FROM clause.
Table : empl
Table : dept
This query will give you the Cartesian product i.e. all possible concatenations are formed of all rows
of both the tables EMPL and DEPT. Such an operation is also known as Unrestricted Join. It returns
n1 x n2 rows where n1 is number of rows in first table and n2 is number of rows in second table.
EQUI-JOIN
- The join in which columns are compared for equality, is called Equi- Join. In equi-join, all the
columns from joining table appear in the output even if they are identical.
e.g. SELECT * FROM empl, dept
WHERE empl.deptno = dept.deptno ;
deptno column is appearing twice in output.
Q: with reference to empl and dept table, find the location of employee SMITH.
ename column is present in empl and loc column is present in dept. In order to obtain the result, we
have to join two tables.
Q: Display details like department number, department name, employee number, employee
name, job and salary. And order the rows by department number.
QUALIFIED NAMES
Did you notice that in all the WHERE conditions of join queries given so far, the field(column) names
are given as: <tablename>.<columnname>
This type of field names are called qualified field names. Qualified field names are very useful in
identifying a field if the two joining tables have fields with same time. For example, if we say deptno
field from joining tables empl and dept, you’ll definitely ask- deptno field of which table ? To avoid
such an ambiguity, the qualified field names are used.
TABLE ALIAS
- A table alias is a temporary label given along with table name in FROM clause.
e.g.
Q: Display details like department number, department name, employee number, employee
name, job and salary. And order the rows by employee number with department number. These
details should be only for employees earning atleast Rs. 6000 and of SALES department.
NATURAL JOIN
By default, the results of an equijoin contain two identical columns. One of the two identical
columns can be eliminated by restating the query. This result is called a Natural join.
empl.* means select all columns from empl table. This thing can be used with any table.
The join in which only one of the identical columns(coming from joined tables) exists, is called
Natural Join.
S1 S2
Roll_no Name Roll_no Class
1 A 2 III
2 B 4 IX
3 C 1 IV
4 D 3 V
5 E 7 I
6 F 8 II
SELECT S1.ROLL_NO, NAME,CLASS
FROM S1 LEFT JOIN S2 ON S1.ROLL_NO=S2.ROLL_NO;
RIGHT JOIN
- It works just like LEFT JOIN but with table order reversed. All rows from the second table are
going to be returned whether or not there are matches in the first table.
- You can use RIGHT JOIN in SELECT to produce right join i.e.
SELECT <select-list>
FROM <table1> RIGHT JOIN <table2> ON <joining-condition>;
om
WWW : World Wide Web
XML : Extensible Markup Language
ASP : Active Server Pages
HTTP: Hypertext Transfer Protocol
TCP/IP : Transmission Control Protocol / Internet Protocol
.c
2 Differentiate between Start Topology and Bus Topology. What are the advantages and
disadvantages of Star Topology over Bus Topology?
Ans.
STAR
Each node is connected to each other
through central node i.e. Switch / Hub
ip BUS
Each node is connected to each other
though backbone cable
cs
If Switch/Hub fails entire network will If Backbone cable fails entire network
be stopped will be stopped
Data transmission speed is fast Data transmission speed is slow as
compare to Star
4
More cable is required Less cable is required
Fault Diagnosis is easy Fault Diagnosis is difficult
Adding/Removal of node is easy Difficult as compare to Star to
on
Add/Remove nodes
High cost setup Low cost setup as compare to Star
Signal transmission is not unidirectional Signal transmission is unidirectional
3 Classify each of the following Web Scripting as Client Side Scripting and Server Side
th
Scripting :
(i) Java Scripting
(ii) ASP
py
(iii) VB Scripting
(iv) JSP
Ans. Client Side : Java Scripting, VB Scripting
Server Side : ASP, JSP
4 Raj has been informed that there had been a backdoor entry to his computer, which
has provided access to his system thought a malicious user/program, allowing
confidential and personal information to be subjected to theft. It happened because
he clicked a link provided in one of the pop-ups from a website announcing him to
be the winner of prizes worth 10 Million Dollars. Which of the following has caused
this out of the following?
(i) Virus (ii) Worm (iii) Trojan Horse
Also mention what he should do to prevent this infection
Ans. (ii) Trojan Horse
5 Raj Singhania is in India and he is interested in communicating with her uncle in
America. He wants to show one of her own designed gadgets to him and also wants
to demonstrate its working without physically going America. Which protocol out of
the following will be ideal for the same?
(i) POP3 (ii) SMTP (iii) VoIP (iv) HTTP
Ans. (ii) VoIP
6 Give 2 differences between 3G and 4G telecommunication technologies.
Ans. i) 4G data transfer rate is faster than 3G
ii) Better video calling and video conferencing in 4G
7 Write the expanded names for the following abbreviated terms used in Networking
om
and Communications:
(i) MBPS (ii) WAN (iii) CDMA (iv) WLL
Ans. MBPS : Mega byte per second
WAN : Wide Area Network
CDMA : Code division multiple access
WLL : Wireless local loop
.c
8 Identify and expand the terms used in Designing the web page:
(i) HTTP (iv) XML (iii) FTP (iv) HTML
Ans. HTTP : hypertext transfer protocol
XML : extensible markup language
FTP : File transfer protocol
HTML : hypertext markup language ip
cs
9 Which of the following device send data to every connected node:
(i) Switch (ii) Hub (iii) Router (iv) Gateway
Ans. HUB
10 In which type of switching first the connection is established between sender and
4
11 _________ is used to provide short-range wireless connectivity between two electronic devices
that within the distance of 5-10 meters
Ans. Infrared
12 Which out of the following, will you use to have an audio-visual chat with an expert sitting in
a far-away place to fix up a technical issue?
th
(i) VoIP
(ii) Email
(iii) FTP
py
Ans. VoIP
13 Identify the cable which consists of an inner copper core and a second conducting outer
sheath:
(i) Twisted Pair (ii) Co-axial (iii) Fiber Optical (iv) Shielded Twisted Pair
Ans. Co-axial
14 In fiber optic transmission, data is travelled in the form of:
(i) Light (ii) Radio link (iii) Microwave Link (iv) Very low frequency
Ans. Light
15 Out of the following, Which transmission media has the highest transmission speed in a
network?
(i) Twisted Pair Cable (ii) Co-axial Cable (iii) Fiber Optical (iv) Electrical Cable
Ans. Fiber Optical
16 Which of the following devices modulates digital signals into analog signals that can be sent
over traditional telephone lines?
(i) Router (ii) Gateway (iii) Bridge (iv) Modem
Ans. Modem
17 What is the name of earliest form of Internet? Also expand it
Ans. ARPANet :Advanced Research Project Agency Network
18 A Local telephone line network is an example of ___________ network
(i) Packet Switched (ii) Line Switched (iii) Circuit Switched (iv) Bit switched
Ans. Circuit Switched
19 Packet switching is based on the _____________ principal
a. Stop and Wait
b. Store and Forward
om
c. Store and Wait
d. Stop and Forward
Ans. Store and Forward
20 The required resources for communication between end systems are reserved for the
duration of the session between end systems in ________ method
a. Packet Switching
.c
b. Line Switching
c. Parallel Switching
d. Circuit Switching
Ans.
21
Circuit Switching
ip
In which type of Switching techniques, the resources are allocated on demand?
a. Packet Switching
cs
b. Line Switching
c. Parallel Switching
d. Circuit Switching
Ans. Packet Switching
4
22 What is Internet? What are the major services offered by Internet?
Ans. A global computer network providing a variety of information and communication facilities,
consisting of interconnected networks using standardized communication protocols.
on
d) Online Shopping
e) Online Education
f) E-Governance etc.
py
23 Which client server program allows multiple users to communicate online with real time
audio, video and text chat in dynamic 3D environment?
Ans. Interspace
24 What is Bandwidth? What is the measuring unit of Bandwidth in term of range of
frequencies a channel can pass?
Ans. Bandwidth: Data transfer rates that can be supported by a network is called its bandwidth.
Bandwidth can be measured in 2 ways:
(i) In Hertz : KHz, MHz, GHz
(ii) In Bits per second : Mbps, Gpbs
25 What are the different types of Transmission Media? Give example of each.
Ans. There are 2 types of Transmission media:
(i) Wired : Twisted pair cable, co-axial cable, fiber optical cable
(ii) Wireless : Radio waves, microwaves, infrared, satellite
26 What is the difference between Radio wave transmission and Microwave transmission?
Ans. Radio waves Microwaves
It travels in Omni-directional It travels in straight line
It can penetrate solid objects It cannot penetrate solid objects
Sender and receiver antenna need not to be Sender and receiver antenna must be
properly aligned proper aligned as it is line-of-sight
transmission
om
27 Which wireless transmission medium is used for controlling our TV, AC with Remote?
Ans. Infrared
28 Which of the transmission is suitable for the transferring data from one place to anywhere in
the world?
Ans. Satellite
29 Out of the following guided media, which is not susceptible to external interference?
.c
(i) Twisted Pair (ii) Co-axial Cable (iii) Fiber Optical (iv) Electric Wire
Ans. Fiber Optical
30 Raj is working as a manager in ABC Ltd. He wants to install CCTV Camera in every part of
Ans. Switch filters the incoming packets and finds the destination node from the MAC table. It
transmit data only to intended node.
35 Which of the following device is used to connect network of different protocols so that they
py
om
(3) Failure of node does not affect the network
Disadvantages:
(1) Fault diagnosis is difficult
(2) At a time only one node can transmit data
(3) In case of backbone failure, entire network will fail.
39 In Star topology all the nodes are connected though which device?
.c
Ans. Switch / Hub
40 What is Star Topology? What are its advantages and Disadvantages?
Ans. Star Topology : In star topology each node is directly connected to a hub/switch.
Advantages:
(1) Easy to install
(2) Easy to expand the node
(3) Fault diagnosis is easy ip
cs
Disadvantages:
(1) Switch failure means entire network failure
(2) More cable required
(3) Costly
4
41 What is Tree Topology? What is the main purpose of using Tree Topology?
Ans. Tree Topology: is a combination of bus and star topologies.
on
The main purpose of Tree topology is to combine multiple star topology networks. All star are
connected together like bus.
42 Which type of Network is generally privately owned and links the devices in a single office,
building or Campus?
a. LAN
th
b. MAN
c. WAN
d. PAN
Ans. LAN
py
om
47 Rearrange the following types of network PAN, MAN, LAN, WAN in descending order of their
area coverage.
Ans WAN > MAN >LAN >PAN
48 What is the possible maximum area covered by LAN
a. 100-500 meter
b. 1-5 KM
.c
c. 1-10 KM
d. 1-2KM
Ans. 1-10KM
establishing LAN?
a. Ethernet
b. Telephone ip
49 Which of the following Cabling technique is considered best between buildings for
cs
c. Optical fiber
d. Co-axial
Ans. Ethernet
4
50 Raj is a Cable TV operator; he wants to give connection to his customers. Which type of
Cable will be best for Raj to connect his subscribers in the different areas of City?
on
a. Ethernet
b. Telephone
c. Optical fiber
d. Co-axial
Ans. Co-axial
th
WORKSHEET – 2
py
NETWORKING
1 Every device connected to network must follow certain rules known as?
Ans. Protocol
2 Out of following protocol, which protocol is used for sending emails to recipient?
a. POP3
b. SLIP
c. SMTP
d. HTTP
Ans. SMTP
3 Out of the following protocol, which protocol is used to establish connection between sender
and receiver through handshaking process?
a. HTTP
b. TCP/IP
c. FTP
d. SMTP
Ans. TCP/IP
4 Out of the following protocol, which protocol is used for downloading or uploading of file from
local PC to web server and vice-versa?
a. FTP
b. SMTP
c. HTTP
d. TCP/IP
om
Ans. FTP
5 In which type of protocol, data is transmitted between two directly connected computers?
a. TCP/IP
b. HTTP
c. SLIP
d. PPP
.c
Ans. PPP
6 Raj is looking for some information about How Router works, for this he opens the browser
and typed the URL of requested site. In few moments he received the requested page on his
browser screen. Identify the type of protocol, used between Browser (Client) and Web Server
for the communication?
a. TCP/IP
b. HTTP ip
cs
c. SMTP
d. POP3
Ans. HTTP
7 Raj is a working as Group Leader in XL corporation. 30 employees are working under Raj,
and they have to constantly report to Raj through email, and also Raj communicate to them
4
through email. Now Raj wants a system through which emails are automatically downloaded
to Outlook so that later on he will be able to read emails even if offline. Identify the protocol
on
Ans. POP3
8 Identify the Protocol used for voice communication over Internet through compression of
py
om
and it was inbuilt in the handset?
a. CDMA
b. GPRS
c. GSM
d. WLL
Ans. CDMA
.c
13 Which service was used in 2G and 3G network for Internet connection which charges the
user on the basis of volume of data used?
a. CDMA
b. GPRS
Ans. GRPS
c. GSM
d. WLL
ip
cs
14 ________ consists of user handset and a base station. The base station is connected to central
exchange as well as antenna.
a. CDMA
b. GPRS
c. GSM
4
d. WLL
Ans. WLL
on
Ans.
Based on LTE-Advanced (Long Term Evolution)
Voice as VoIP (Voice over Internet Protocol (VoLTE)
Better Video calling than 3G, Video conferencing etc.
py
17 In which generation only voice call was possible and there was not data exchange?
a. 1G
b. 2G
c. 3G
d. 4G
Ans. 1G
18 Name any two popular Mobile processors?
Ans. Qualcomm Snapdragon, Apple A13 Bionic
19 What are the 2 main sub processors of Mobile processor?
Ans. Communication Processing Unit & Application Processing Unit
20 Which sub-processor of Mobile process is responsible for making and receiving calls?
Ans. Communication Processing Unit
21 The status code of HTTP, when page not found is?
Ans. 404
22 The status code of HTTP, which page is found is?
Ans. 200
23 Which of the following is reliable communication protocol?
a. IP
b. TCP
c. FTP
d. All of the above
Ans. All of the above
24 This is the telecommunication protocol that all computers must use to be part of the
Internet.
om
a. FTP
b. IP
c. TCP
d. POP
Ans. TCP
25 In network HTTP resource are located by:
.c
a. Uniform Resource Identifier
b. Uniform Resource Log
c. Unique Resource Locator
d. Uniform Resource Locator
Ans.
26
Ans.
Uniform Resource Locator
What are the two popular Chat protocols?
IRC (Internet Relay chat) ip
cs
XMPP (Extensible Messaging and Presence Protocol)
27 Out of the 2 Chat protocols IRC and XMPP, which one is used in the latest apps like
Facebook, WhatsApp for Chat?
Ans. XMPP
4
28 Raj is working as a Sales promoter in XL corporation; He is right now in Sri Lanka, and
wants to address to some of his subordinates. Raj wants to have meeting in which they can
watch each other and also communicate with audio in real time. Identify the Protocol used
on
om
.c
(i) ip
Suggest the most suitable place (i.e. School/Center) to install the server of this
cs
university with suitable reason
(ii) Suggest an ideal layout for connecting these school/center for a wired connectivity
(iii) Which device will you suggest to be placed/installed in each of these school/center
to efficiently connect all the computers within these school/center?
(iv) The university is planning to connect its admission center in the closest big city,
4
which is more than 350 KM from the University. Which type of network out of LAN,
MAN, WAN will be formed? Justify your answer.
on
25 m 45 m
py
Technology School
Business School
Law School
60 m
(iii) Switch
(iv) WAN (distance is more than 50 km which is higest area coverage of MAN to transfer data)
(B) Ravya industries has setup its new center at kakadeo nagar for its office and web based
activities. The company compound has 4 buildings as shown in the diagram below :
om
.c
(i)
(ii)
(iii) ip
Suggest the most suitable place (i.e. School/Center) to install the server of this
university with suitable reason
Suggest an ideal layout for connecting these school/center for a wired connectivity
Suggest the placement of following devices with suitable reason:
cs
(a) Internet Connecting Device/ Model
(b) Switch
(iv) The organization is planning to link its sale counter situated in various parts of the
same city, which type of network out of LAN, MAN or WAN will be formed? Justify
4
your answer
(C) Arogya Training Education Institute is setting up its centre in Kanpur with four specialized
departments for Orthopedics, Neurology and Pediatrics along with an administrative office in
on
separate buildings. The physical distances between theses department buildings and the
number of computers to be installed in these department and administrative office are given
as follows. You, as a network expert, have to answer the queries as raised by them in (i) to
(iv)
Shortest distance between various locations in meters:
th
om
(ii) Suggest the best cable layout for effective network connectivity of the building
having server with all the other buildings
(iii) Suggest the devices to be installed in each of these buildings for connecting
computers install within the building out of the following:
Gateway
Model
Switch
.c
(iv) Suggest the topology of the network and network cable for efficiently connecting
each computer installed in each of the buildings out of the following:
Topologies : Bus Topology, Star Topology
Ans. (i)
ip
Network Cable : Single Pair Telephone Cable, Coaxial Cable, Ethernet Cable
Administrative office (maximum number of computer here)
cs
(ii)
4
55m 40m
on
30m
th
py
(iii) Switch
(iv) Star / Ethernet cable
WORKSHEET
NETWORK SECURITY, WEB SERVICE AND EPAYMENT
1 Virus that fool a user into downloading and /or executing them by pretending to be useful
applications are also sometimes called
a. Crackers
b. Key loggers
c. Trojan Horse
d. Worm
Ans. Trojan Horse
2 __________ are often delivered to a PC through an email attachment & are often designed to do
harm
a. Email messages
b. Virus
om
c. Spam
d. Portals
Ans. Virus
3 What is the most common way to get a virus in your computer „s hard disk
a. By opening emails
b. By uploading pictures from mobile to PC
.c
c. By installing games from CD-ROM
d. None of the above
Ans. By opening emails
4
ip
_________ is the action of recording the keys struck on a keyboard, typically covertly, so that
the person using the keyboard is unaware that their actions are being monitored
a. Spamming
cs
b. Key logging
c. Denial of Service
d. Exploits
Ans. Key logging
5 What is the software called which when get downloaded on computer scans your hard drive for
4
b. Antiware
c. Backdoors
d. Spyware
Ans. Spyware
6 Which type of Virus replicates itself and eats your entire disk space or network bandwidth?
th
a. Trojan Horse
b. Adware
c. Worm
d. Spamming
py
Ans. WORM
7 Which of the following is a type of program that either pretends to have, or is described as
having, a set of useful or desirable features but actually contains damaging code.
a. Trojans
b. Viruses
c. Worm
d. Adware
Ans. Trojans
8 Which of the following is a program capable of continually replicating but requires user
intervention
a. Trojans
b. Virus
c. Worm
d. Adware
Ans. Virus
9 Which of the following is software that, once installed on your computer, tracks your internet
browsing habits and sends you popups containing advertisements related to the sites and
topics you‟ve visited?
a. Trojans
b. Adware
c. Spam
d. Virus
Ans. Adware
10 Unwanted commercial email is known as ___________
a. Malware
b. Virus
om
c. Spam
d. Adware
Ans. Spam
11 What is the difference in Virus and Worm?
Ans. VIRUS WORK
They are designed to damage files, corrupt They do not damage the files
.c
OS files and cause annoying effects
It requires user intervention to replicate It replicate itself without user intervention
12
ip
What is Trojan? Any two type of activities performed by Trojan
Ans. Is a program that appears harmless (such as text editor or a utility program) but actually
performs malicious functions such as deleting or damaging files.
cs
Activities performed by Trojans:
• Data theft
• Installation of unwanted softwares
• Keystroke logging
• Downloading or uploading of files, etc.
4
13 _________ is a small text file created by web server on client computer to store user preferences,
user name, session information etc.
on
Ans. Cookies
14 Raj, an executive in a multinational company, one day when he logged in to check emails he
found lots of commercial promotional emails are there and he is not able to track the useful
mails and it is taking too much of time also his time killed in deleting those mails. What kind
of attack Raj is facing?
th
a. Adware
b. Spam
c. Trojan
py
d. Virus
Ans. Spam
15 What are the 2 main security concerns with Cookie?
Ans. 1) Session Data (Chance of hacking of username and password)
2) Tracking information
16 ________ is a software/hardware of combination of both is used to block unauthorized access
and allows only authorized user allowed by administrator.
Ans Firewall
17 HTTPS is abbreviated as _________
Ans. Hypertext Transfer protocol Secure (SSL – Secure Socket Layer)
18 Users are able to see a pad-lock icon in the address bar of the browser when there is _______
connection.
a. HTTP
b. HTTPS
c. SMTP
d. FTP
Ans. HTTPS
19 Raj a web developer working on online payment screen. Requirement of Client is that the
confidential information entered by the customer should be transfer securely over the network.
What kind of network security protocol used by Raj to achieve this task?
a. HTTP
b. FTP
c. HTTPS
d. FTP
Ans. HTTPS
20 Which types of network security protocol ensure data is transferred in encrypted form to keep
it secure from eavesdropper and cannot be stolen?
om
a. HTTPS
b. TCP/IP
c. SMTP
d. PPP
Ans. HTTPS
21 When IT Act 2000 came into effect in India?
.c
a. October 17, 2001
b. October 17, 2000
c. November 11, 2001
d. November 11, 2000
Ans.
22
October 17, 2000
How many schedules are there in IT Act 2000
a. 1 ip
cs
b. 2
c. 3
d. 4
Ans. 4
4
23 Which is the Act which provides legal framework for e-Governance in India?
a. IT(amendment) Act 2008
b. IPC
on
c. IT Act 2000
d. None of the above
Ans. IT Act 2000
24 What is/are component of IT Act 2000?
a. Legal recognition to Digital Signatures
th
om
29 Raj is a social worker, one day he noticed someone is writing, insulting or demeaning
comments on his post. What kind of Cybercrime Raj is facing?
Ans. Cyber Bullying.
30 When a person is harassed repeatedly by being followed, called or be written to he/she is a
victim of
a. Bullying
.c
b. Identify Theft
c. Stalking
d. Phishing
Ans. Stalking
31
Ans.
32
Local Police Station
Expand the term IPR ip
When any cybercrime happed with you, whom will you approach first?
cs
Ans. Intellectual Property Rights
33 What is Intellectual Property Rights? What are the two categories of IPR issues?
Ans. IPR refers to something owner has legal rights. Intellectual Property refers to creations of the
intellect, inventions, literacy and artistic work, symbols, names, image and design used in
4
commerce are part of it.
Two Categories of IPR:
1) INDUSTRIAL PROPERTY
on
2) COPYRIGHT
34 What is the difference between Hacking and Cracking?
Ans. Hacking: Process to gain access to systems with a view to fix the identified weakness. They
may also perform penetration testing and vulnerability assessments.
Cracking: Refers to gain unauthorized access to computer systems for personal gain. The
th
intent is usually to steal corporate data, violate privacy rights, transfer funds from bank
accounts etc.
35 Explain the term WWW? When it was invented?
py
.
36 What is the difference between HTML and XML?
om
.c
ip
4 cs
on
th
py