CS-Part_A
CS-Part_A
XII
COMPUTER
SHORT NOTES-2025-2026
CLASS (083
XII )
Based on the latest CBSE Exam Pattern for the Session
Sr.No. Topic Page No.
1 REVIEW OF PYTHON 1 to 15
2 FUNCTIONS 16 to 29
3 EXCEPTION HANDLING 30 to 33
5 DATA STRUCTURE 37 to 65
6 COMPUTER NETWORKS 66 to 87
3. Distribution of Marks:
Theory Practical
Total 70 110 70
1 Lab Test: 8
1. Python program (60% logic + 20%
documentation + 20% code quality)
2. SQL queries (4 queries based on one or 4
two tables)
2 Report file: 7
● Minimum 15 Python programs.
● SQL Queries – Minimum 5 sets using
one table / two tables.
● Minimum 4 programs based on Python -
SQL connectivity
3 Project (using concepts learnt in Classes 11 8
and 12)
4 Viva voce 3
Variables and data types: Variables are used to store data. Data types of variables:
● Numeric Types: int, float, complex ● Boolean – True or False values.
● None – a special type with an unidentified value or absence of value.
● Sequence: an ordered collection of elements. String, List and Tuples are sequences.
● Mappings – Dictionaries are mappings. Elements of dictionaries are key-value pairs.
Multiple Assignments:
• Assigning same value to multiple variables - a = b = c = 1
• Different values to different variables- a, b, c = 5,10,20
print statement: used to display output. If variables are specified i.e., without quotes then
value contained in variable is displayed.
E.g., x = "kve " Output:
print(x) kve
To combine both text and a str variable, Python uses the “+” character:
Example
x = "awesome" Output:
print("Python is " + x) Python is awesome
Precedence of Operators: The operator having high priority is evaluated first compared to
an operator in lower order of precedence when used in an expression.
Examples:
1. x = 7 + 3 * 2 2. >>> 3+4*2
13 11
* has higher precedence than +, so it first Multiplication gets evaluated before the
multiplies 3*2 and then adds into 7 addition operation
Comments: Comments are ignored by the Python interpreter. Comments gives some
message to the Programmer. It can be used to document the code. Comments can be:
• Single-line comments: It begins with a hash(#) symbol and the whole line is considered
as a comment until the end of line.
• Multi line comment is useful when we need to comment on many lines. In python, triple
double quote (" " ") and single quote (' ' ') are used for multi-line commenting.
Example:
# This is a single line comment
' ' 'I am a multi
line comment ' '
'
input() function:An input() function is used to receive the input from the user through the
keyboard. Example: x=input('Enter your name') age = int( input ('Enter your age'))
Selection Statements: It helps us to execute some statements based on whether the condition
is evaluated to True or False.
if statement: A decision is made based on the result of the comparison/condition. If condition
is True then statement(s) is executed otherwise not.
Syntax:
if <expression>:
statement(s) Example:
a = 3 if a > 2: Output:
print(a, "is greater") 3 is greater
print("done")
done
If-else statement:
If condition is True then if-block is executed otherwise else-block is executed.
Syntax: if test
expression:
Body of if stmts else:
Body of else
Example:
a=int(input('enter the number')) Output: enter the
if a>5: number 2
print("a is greater") a is smaller than the input given
else:
print("a is smaller than the input given")
If-elif-else statement: The elif statement allows us to check multiple expressions for TRUE
and execute a block of code as soon as one of the conditions evaluates to TRUE.
Syntax:
If <test expression>:
Body of if stmts elif
< test expression>:
Body of elif stmts else:
Body of else stmts
Example:
var = 100 if var == 200: print("1 - Got Output:
a true expression value") print(var) elif 3 - Got a true expression value
var == 150: print("2 - Got a true
100
expression value") print(var) elif var
== 100: print("3 - Got a true expression
value") print(var) else: print("4 -
Got a false expression value")
print(var)
While loop: while loop keeps iterating a block of code defined inside it until the desired
condition is met.
For loop: for loop iterates over the items of lists, tuples, strings, the dictionaries and other
iterable objects.
Syntax:
for <loopvariable> in <sequence>:
Statement(s)
Example 1: Output is:
L = [ 1, 2, 3, 4, 5] 12345
for var in L:
print( var, end=’ ‘)
Example 2: output: 0,1,2,3,4,5,6,7,8,9
for k in range(10):
print(k, end =’ , ‘)
List:Lists are ordered mutable data types enclosed in square brackets. E.g., [ 'A', 87, 23.5 ]
Python has a set of built-in methods that you can use on lists
Method Description
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
Tuples: A tuple is a collection which is ordered and unchangeable. In Python tuples are
created by enclosing items within round brackets. Tuple is immutable. We can create tuple in
different ways.
X=( ) # an empty tuple
X=(1,2,3) # a tuple with three elements
X=tuple(list1)
X=1,2,3,4
Accessing elements of a tuple:
We can use index to access the elements of a tuple. From left to right, index varies from 0 to
n1, where n is total number of elements in the tuple. From right to left, the index starts with -1
and the index of the leftmost element will be –n, where n is the number of elements.
T = ( 1, 2,4,6) Output:
print(T[0]) print(T[- 1
1]) 6
Some important functions which can be used with tuple: count ():
Returns the number of times a specified value occurs in a tuple
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2) output: 4
>>> x.count(2)
index (): Searches the tuple for a specified value and returns its position in the tuple.
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2) Output: 1
>>> x.index(2)
len(): To know the number of items or values present in a tuple, we use len().
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2) output: 12
>>> y=len(x)
>>> print(y)
setdefault(key[,d]) If key is in the dictionary, return its value. If not, insert key
with a value of d and return d (defaults to None).
update([other]) Update the dictionary with the key/value pairs from other,
overwriting existing keys.
values() Return a new view of the dictionary's values
remove() It removes or pop the specific item of dictionary
del( ) Deletes a particular item
len( ) we use len() method to get the length of dictionary
10. Which point can be considered as difference between string and list?
a. Length c. Indexing and Slicing
b. Mutability d. Accessing individual elements
16. If D=1,2,3
What will be the data type of D?
a)List b)tuple c)set d)invalid type
Answers of MCQ:
1)a 2)a 3)b 4)a 5)d 6)c 7)a 8)b 9) d 10)b 11)b 12)b 13)a 14)c
15)c 16)b 17)c 18)a 19)b 20)a 21)c
11 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
while True:
print(A)
A =A+1
6. Give the output of the following. Also find how many
times the loop will execute.
A=0
while A<10:
print(A, ‘ , ‘)
A =A+1
12 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
14. Give the output of the following L = [1,2,3,4,5,6,7,8,9]
print(L.count(2)) print(L.index(2)
15. Write python code to sort the list, L, in descending order.
18.Find output.
vowels=['a','e','i']
vowels.append('o')
vowels.append(['u'])
vowels.extend(['A','E'])
print("New List:",vowels)
19.Given the following declaration, what will be the output of the
following: Lst=(1,2,3,4,5) del Lst[2] print(Lst)
20.Identify the statement(s) from the following options which will raise TypeError exception.
a)print(‘5’*’3’)
b)print(5*3)
c)print(‘5’+3)
d)print(‘5’+’3’)
e)print(‘5’*3)
Answers for VSA Questions
1)10
2)30
3)
*
* *
* * *
4) * * * * *
* ***
13 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
* * *
* * *
5)infinite loop. Condition / test expression is always Ture.
6) 0,1,2,3,4,5,6,7,8,9
7) 0,1,2,3,4,5,6,7,8,9
10
10)TypeError
11) [1,2,3,4,5,6,7,8,9]
12) [1,2,3,4,5,6,7,8]
c)print(‘5’+3)
2.Write Python code to remove an element as entered by the user form the list, L
3.Create a list k, by selecting all the odd numbers within the given range, m and n. User will
input the values of m , n at run time
4.Write Python code to create and add items to a dictionary. Ask the user to input key value
pairs. Continue as long as the user wishes.
5.Write Python code to find whether the given item is present in the given list using for loop.
14 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
6.Create a list, L, with the squares of numbers from 0 to 10
7.Write a program to accept a list of numbers and to create a dictionary with two keys ODD
and EVEN whose values are all the odd numbers from the list and all the even numbers from
the list respectively.
8.Mr. Rahul wants created a dictionary to store the details of his students and to manipulate the
data. He wrote a code in Python, help him to complete the code:
studentDict = ______ # stmt 1 n = int(input("How
Many Students you Want To Input?"))
for i in range(___): # stmt 2 - to enter n number of students
data rollno = input("Enter Roll No:") name = input("Enter
Name:")
physicsMarks = int(input("Enter Physics Marks:"))
chemistryMarks = int(input("Enter Chemistry Marks:")) mathMarks
= int(input("Enter Maths Marks:")) studentDict[rollno]=__________ # stmt 3
Answers /Hints: Short answer Type Questions.
1) for k in D.items(): print(k)
2) a =int(‘input the item to be
deleted’) l.remove(a)
3) m = int(input(‘lower
limit’)) n =
int(input(‘upper limit’))
n = n+1
L = [x for x in range(m, n) if x%2!=0]
4) D = { } while True:
K = input(‘type a key’)
V = int(input(‘type the value’)
D[K] = V
C = input(‘type ‘y’ to add more’)
if C!=’y’:
break
5) flag = 0
L = eval(input(‘input a list on numbers’))
E = int(input(‘item to be searched’)
K =len(L) for p in range(K): if
E ==L(p):
flag = 1
print(‘found and index is ‘,p) if
flag==0:
print(‘not found’)
15 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
6) list1=[] for x in
range(10):
list1.append(x**2)
list1
Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
OR
list1=list(map(lambda x:x**2, range(10)))
7) L=eval(input("Enter a
list")) D={"ODD":
[],"EVEN":[]} for i in
L: if i%2!=0:
D["ODD"].append(i)
else:
D["EVEN"].append(i)
print(D)
8) Statement 1 :
StudentDict = dict( )
Statement 2 = for i in
range( n ):
Statement 3: studentDict[rollno]=[name, physicsMarks, chemistryMarks, mathMarks]
FUNCTIONS
Functions: A function is a named sequence of statement(s) that performs a computation. They
can be categorized as: Built-in function, Functions defined in module and User defined
functions
a) Built-in functions: Built in functions are the function(s) that are built into Python and can
be accessed by a programmer. We don’t have to import any module to use these functions.
Name of the Description Example
function
16 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
provided then x is rounded to 0 -100.0
decimal digits. >>> round (80.23456)
80
import statement: It is simplest and most common way to use modules in our code. syntax is:
import modulename1 [, modulename2, ]
Example: import math
To use/ access/invoke a function, you will specify the module name and name of the function-
separated by dot (.). This format is also known as dot notation.
17 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
pow( x, y ) It returns the value of xy, where x and y math.pow(100, 2) 10000.0
are numeric expressions. math.pow(100, -2) 0.0001
math.pow(2, 4) 16.0
math.pow(3, 0) 1.0
sqrt (x ) It returns the square root of x for x > 0, math.sqrt(100)
where x is a numeric expression. 10.0
math.sqrt(7)-
2.6457513110645907
18 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
b. After the keyword comes an identifier i.e. name of the function, followed by
parenthesized list of parameters and the colon which ends up the line.
c. Next follows the block of statement(s) that are the part of function. Syntax:
def function_name([parameter1, parameter2,....]) :
statement1
statement2
...
[return <value1, value2, ...> ]
Formal Parameters or Parameters: These are the values provided in Parenthesis when we
write a function Header.
Actual Parameters or Arguments: These are the values passed to the function when it is
called/invoked.
Example:
def area_of_circle( radius ): # radius Formal Parameter OUTPUT
parameter print(“Area of circle = “,3.1416*radius*radius) Enter radius of circle 10
r=int(input(“Enter radius of circle”)) ar=area_of_circle(r)
Area of circle = 314.16
# r - Actual Parameter or Argument
(i) Default Parameters: The parameters which are assigned with a value in function header
while defining the function are known as default parameters. Default parameters will be
written in the end of the function header, which means positional parameter cannot
appear to the right side of default parameter. If no value is provided in function call, then
the default value will be taken by the parameter.
Example:
def SICal(amount, rate, time=10): #time has default parameter
(ii) Positional Parameters/ Required Arguments: The function call statement must match
the number and positional order of arguments as defined in the function definition, then it is
called the positional parameters.
Example:
def Test(x,y,z): # x,y,z are positional parameters
Then we can call function using following statements p,q,r=3,4,6
Test(p,q,r) #3 variables are passed
Test(4,q,r) # 1 literal and 2 variables are passed
19 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Example 1: def add10(x,y,z): Output
return x+10,y+10,z+10 (20, 30, 40)
x=10
y=20
z=30
result=add10(x,y,z)
print(result)
Example 2: def add10(x,y,z): Output:
return x+10,y+10,z+10 20 30 40
x=10
y=20
z=30
a,b,c=add10(x,y,z) #unpack
SCOPE OF VARIABLES: Scope of a variable is the portion of a program where the variable
is recognized and can be accessed therein. There are two types of scope for variables:
1.Local Scope: A variable declared in a function-body is said to have local scope. It cannot be
accessed outside the function.
2. Global Scope: A variable declared in top level segment (main) of a program is said to have
a global scope.
Example 1:
def Sum(x , y) : #x,y,z local
z=x+y return z a
=5 #a,b global
b=7s=
Sum(a , b)
print(s)
Practice Questions (1 MARK)
1 Which of the following is a valid function name?
a) Start_game() b) start game() c) start-game() d) All of the above
2 If the return statement is not used in the function then which type of value will be
returned by the function?
a)int b) str c) float d) None
3 What is the minimum and maximum value of c in the following code snippet?
import random
a=random.randint(3,5)
b = random.randint(2,3)
c=a+b
print(c)
a) 3 , 5 b) 5, 8 c) 2, 3 d) 3, 3
4 pow( ) function belongs to which library ?
20 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
a) math b) string c) random d) maths
5 What data type is the object below?
L = (1, 23, ‘hello’,1)
a) list b) dictionary c) array d) tuple
6 What is returned by int(math.pow(3, 2))?
a) 6 b) 9 c) error, third argument required d) error, too many arguments
15 If you want to communicate between functions i.e. calling and called statement, then
you should use
a) values b) return c) arguments d) none of the above
16 Which of the following function header is correct?
a) def mul(a=2, b=5,c) b) def mul(a=2, b, c=5)
c) def mul(a, b=2, c=5) d) def mul(a=2, b, c=5)
21 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
17 Find the flow of execution of the following code:
1. def calculate (a, b):
2. res=a**b
3. return res
4.
5. def study(a):
6. ans=calculate(a,b)
7. return ans
8.
9. n=2
10. a=study(n)
11. print(a)
a) 1 > 5 > 9 > 10 >6 > 2 > 3 > 7 > 11 b) 5 > 9 > 10 > 6 > 2 > 3 > 7 > 11
c) 9 > 10 > 5 > 1 > 6 > 2 > 3 > 7 > 11 d) None of the above
18 A can be skipped in the function call statements a)
named parameter b) default parameter
c) keyword parameters d) all of the above
ANSWERS
1 a)Start_game()
2 d) None
3 b) 5, 8
4 a) math
5 d) tuple
6 b) 9
7 c) input()
8 c)pickle
9 b) 0 or many
a) 10
10
10
11 a) True
12 b) local
13 a) built in function
14 c) scope
15 c) arguments
16 c) def mul(a, b=2, c=5)
17 a) 1 > 5 > 9 > 10 >6 > 2 > 3 > 7 > 11
18 b) default parameter
22 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Practice Questions (2 MARKS)
1. What is the output of the following
code? def cube(x): return x * x * x x
= cube(3) print( x)
a) 9 b)3 c)27 d) 30
23 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
7 What is the output of the program given
below? x = 50 def func (x) :
x=2
func (x)
print ('x is now', x)
A) x is now 50 B) x is now 2 C) x is now 100
D) Error
9 Predict the output of the following code
fragment def update(x=10): x+=15
print("x=",x)
x=20 update()
print("x=",x)
a) x=20 b) x=25 x=25
x=25
c) x=20 d) x=25
x=25 x=20
24 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
14 Predict the output of the following code
snippet: def Execute(M): if M%3==0:
return M*3 else:
return M+10; def
Output(B=2): for T in range
(0,B):
print(Execute(T),"*",end="")
print() Output(4)
Output()
Output(3)
16 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="")
25 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
18 What will be the output of the following
code total=0 def add(a,b): global total
total=a+b print(total)
add(6,6) print(total)
a) 12 b) 12 c) 0 d) None of these
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=" ")
26 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
21 Choose the correct option:
Statement1: Local Variables are accessible only within a function or block in which it
is declared.
Statement2: Global variables are accessible in the whole program.
a. Statement1 is correct but Statement2 is incorrect
b. Statement2 is correct but Statement1 is incorrect
c. Both Statements are Correct
d. Both Statements are incorrect
22 Consider the following code and choose correct
answer: def nameage(name, age): return
[age,name]
t=nameage('kishan',20)
print(type(t))
a) tuple b) list c) (kishan,20) d) None of all
Write the output of the following: a=(10,
23
12, 13, 12, 13, 14, 15) print(max(a)
+ min(a) + a.count(2))
a) 13 b) 25 c) 26 d) Error
24 Consider the code given below and Identify how many times the message “Hello
All” will be printed. def prog(name): for x in name: if x.isalpha():
print('Alphabet')
elif x.isdigit():
print('Digit') elif
x.isupper():
print('Capital Letter')
else: print('Hello
All')
prog('vishal123@gmail.com')
a) 0 b) 2 c) 1 d) 3
27 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
b=20
a=changer(a,b)
print(a,"$",b)
a=changer(a)
print(a,"$",b)
ANSWERS
1. Ans. C) 27
2 Ans.d
Both A and B
3 Ans c)Name Error
4. Ans. B)new#dehli#
5. Ans. C)No Output
6 Ans.c) def fun(x=1,y=1,z=2)
7 Ans. A)
A) x is now 50
9 Ans. d)
x=25
x=20
10 Ans. a)
55
63
12 5
12 Ans. b) [6, 7, 8, 9]
14 Ans.
0 *11 *12 *9 *
0 *11 *
0 *11 *12 *
15. Ans: c) PPW%RRllN%
16 Ans. Options i and iii
i)40 @50 @ iii) 40 @50
@70 @90 @
Maximum value of L and U : L=2 ,U=5
18 Ans : a)12
12
19 Ans. The new string is :
cBsEeXaMs@2022cbs
20 Ans. iv) 7 $
Maximum value of x is 2
Minimum value of x is 1
21 Ans.c) Both Statements are correct
22 Ans : b)
23 Ans : b) 25
|KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
27
24 Ans: b) 2
25 Ans.
10.0 # 10.0
10.0 $ 20
1.0 # 1.0
1.0 $ 20
ANSWERS
2 (c) A is True but R is False
3 (b)Both A and R are true and R is not the correct explanation for A
4 (a) Both A and R are true and R is the correct explanation for A
5 (b)Both A and R are true and R is not the correct explanation for A
7 (a) Both A and R are true and R is the correct explanation for A
29 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
8 (a) Both A and R are true and R is the correct explanation for A
9 (b)Both A and R are true and R is not the correct explanation for A
Exception Handling
An exception is a python object that represents an error. The exception needs to be handled by
the programmer so that the program does not terminate abruptly.
Eg:
Try and Except Block: An exception is caught in the try block and handled in except block.
An exception is said to be caught when a code designed to handle a particular exception is
executed.
While executing the program if an exception is encountered further execution of the code inside
the try block is stopped and the control is transferred to the except block.
try...except…else clause:
We can put an optional else clause along with the try...except clause. An except block will be
executed only if some exception is raised in the try block. But if there is no error then none of
the except blocks will be executed. In this case, the statements inside the else clause will be
executed.
31 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Eg:
try:
numerator=50
denom=int(input("Enter the denominator: "))
quotient=(numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed") except
ValueError:
print ("Only INTEGERS should be entered") else:
print ("The result of division operation is ", quotient) Finally
clause:
The try statement in Python can also have an optional finally clause. The statements inside the
finally block are always executed regardless of whether an exception has occurred in the try
block or not.
32 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Some of the commonly occurring built-in exceptions are :
S. No Name of the Builtin Explanation
Exception
1 SyntaxError It is raised when there is an error in the syntax of the Python
code.
2 ValueError It is raised when a built-in method or operation receives an
argument that has the right data type but mismatched or
inappropriate values.
3 IOError It is raised when the file specified in a program statement
cannot be opened.
4 KeyboardInterrupt It is raised when the user accidentally hits the Delete or Esc key
while executing a program due to which the normal flow of the
program is interrupted.
5 ImportError It is raised when the requested module definition is not found.
33 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
6 EOFError It is raised when the end of file condition is reached without
reading any data by input().
7 ZeroDivisionError It is raised when the denominator in a division operation is zero.
8 IndexError It is raised when the index or subscript in a sequence is out of
range.
9 NameError It is raised when a local or global variable name is not defined.
10 IndentationError It is raised due to incorrect indentation in the program code.
11 TypeError It is raised when an operator is supplied with a value of incorrect
data type.
12 OverFlowError It is raised when the result of a calculation exceeds the maximum
limit for numeric data type.
13 Key-Error Python raises a KeyError whenever a dict() object is requested
(using the format a= adict[key]) and the key is not in the
dictionary.
34 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
5. Can one block of except statements handle multiple exception? A. yes, like
except TypeError, SyntaxError [,…]
B. yes, like except [TypeError, SyntaxError]
C. No
D. None of the above
Ans : A
Explanation: Each type of exception can be specified directly. There is no need to put it in a
list.
7. What will be the output of the following Python code?
lst = [1, 2, 3]
lst[3]
a) NameError
b) ValueError
c) IndexError
d) TypeError Answer: c
Explanation: The snippet of code shown above throws an index error. This is because the index
of the list given in the code, that is, 3 is out of range. The maximum index of this list is 2.
Absolute Path – It is a full path of the file from the root directory. Ex
: - C:\\Users\\Tanmay\\Desktop\\Delete\\file_handling.txt
f=open(“C:\\Users\\Tanmay\\Desktop\\Delete\\file_handling.txt”,r)
35 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Relative Path – Relative Path is the hierarchical path that locates a file or folder on a file
system starting from the current working directory.
f=open(“file_handling.txt”, r)
open() function
syntax: open(filename, mode). If mode not specified, default mode is 'r' i.e., read text file
Modes Description
1. r,rb Read only
2. r+, rb+ Read and write
3. w,wb Write only
4. w+, wb+ Write and Read.
5. a,ab Append.
6. a+, ab+ Append and read.
b stands for binary file, otherwise opens in text mode r In all r modes file must exist prior to
open otherwise error is thrown. File pointer is placed at beginning.
w In all w modes, if file exists then it is removed and it always creates a blank file. File pointer
placed at beginning a In all a modes, if file exists then newly added data is added at the end. If
file does not exist then a new file is created.
readline() : Reads a line of the file and returns in form of a string. For specified n, reads at most
n bytes. However, does not reads more than one line, even if n exceeds the length of the line.
File_object.readline([n])
readlines() : Reads all the lines and return them list in which each line as a string element
File_object.readlines()
36 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
writelines() function98
This function writes the content of a list to a file.
file_name.writelines(list_of_lines)
The seek() method: This method is used to position the file object at a particular position in a
file. The syntax of seek() is: file_object.seek(offset ,[ reference_point])
In the above syntax, 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. That is, with reference to which
position, the offset has to be counted. It can have any of the following values:
0 - beginning of the file
1 - current position of the file
2 - end of file
By default, the value of reference_point is 0, i.e. the offset is counted from the beginning of the
file. For example, the statement fileObject.seek(5,0) will position the file object at 5th byte
position from the beginning of the file.
SAMPLE PROGRAMS
1. Write a program to write roll no and name to xiib.txt
2.Write read contents from story.txt and count no: of independent words “to” in the file
3 To read the entire remaining contents of the file as a string from a file object myfile,
we use
a. myfile.read(2)
b. myfile.read()
c. myfile.readline()
d. myfile.readlines()
4 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.
38 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
5 Which function of a file object can be used to fetch the current cursor position in
terms of number of bytes from beginning of file?
a. seek( )
b. bytes( )
c. tell( )
d. fetch( )
a. AllngsAll
b. AllcanAll
c. Allcancan
d. Allngscan
7 What will be the most correct option for possible output of the following code, given
that the code executes without any error.
f = open(‘cricket.txt’) data
= f.read(150)
print(len(data))
8. For the following python code, what will be the datatype of variables x, y, z given
that the code runs without any error?
f = open(‘story.txt’)
x = f.read(1) y =
f.readline() z =
f.readlines()
a. string, list, list
b. None, list, list
c. string, string, list
d. string, string, string
ANSWERS:
39 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
1. a. Beginning of file
2. d. All of the mentioned
3. b. myfile.read()
4. c. L1 will be a string and L2 will be a list with 9 elements.
5. c. tell( )
6. a. AllngsAll
7. d. Less than or equal to 150
8. c. string, string, list
3. In ___________ files each line terminates with EOL or ‘\n’ or carriage return, or
‘\r\n’.
Ans: Text File
4. Observe the following code and answer the questions that follow.
File=open(“MyData”,”a”)
_____________ #Blank1
File.close()
a) What type (text/binary) of file is MyData ?
b) Fill the Blank1 with statement to write “ABC” in the file “Mydata”
Ans: a) Text File
c) File.write(“ABC”)
40 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
from_where: This is used for defining the point of reference. It can take
0: beginning of the file. 1: current position of the file. 2: end of the file.
2. Write a function in Python that counts the number of “the” or “this” words
present in a text file “myfile.txt”. Example: If the “myfile.txt” contents are as
follows:
This is my first class on Computer Science. File handling is the easiest topic for me
and Computer Networking is the most interesting one. The output of the function should be:
Count of the/this in file: 3 Answer:
def displayTheThis():
num=0
f=open("myfile.txt","r")
N=f.read() M=N.split()
for x in M: if x=="the"
or x== "this":
print(x)
num=num+1
f.close()
print("Count of the/this in file:",num)
4. Write a Python program to count all the line having 'a' as last character.
Answer: count =0
f=open('fracture.txt',"r")
data=f.readlines() for
line in data:
if line[-2] == 'a':
count=count+1
print("Number of lines having 'a' as last character is/are : " ,count)
f.close()
Binary file: A binary file is a file whose content is in a binary format consisting of a series
of sequential bytes, each of which is eight bits in length.
41 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Opening a Binary file in Python
Syntax: file_object= open (file_name, access_mode)
Example: myObject=open(“myfile.txt”, “ab+”)
Pickling: The process of converting the structure (lists and dictionary etc.) into a byte stream
just before writing to the file. This is also called as object serialization. It converts a Python
object (list, dictionary, etc.) into a character stream.
Unpickling: A reverse of pickling process where information from byte stream gets converted
into object structure.
Pickle module: Python pickle module is used for serializing and de-serializing a Python object
structure. Any object in Python can be pickled so that it can be saved on disk. First, we need to
import the module.
import pickle
It provides two main methods for the purpose- dump and load.
1. pickle.dump(): This function is used to pickle the data object into byte stream and
stores it in the binary file.
2. Pickle.load() : This function reads pickled objects from a file, whereas loads()
deserializes them from a bytes-like object.
Output:
[1,2,3,4,5]
43 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Question and Answers (Binary Files)
1. Which functions is used to close a file in python?
(A) close (B) cloose() (C) Close() (D) close()
Ans: (D) close()
3. Which of the following python statement will bring the read pointer to 10th character from
the end of a file containing 100 characters, opened for reading in binary mode.
a) File.seek(10,0) b) File.seek(-10,2) c) File.seek(-10,1) d) File.seek(10,2)
Ans: File.seek(-10,2)
4. Which of the file opening mode will open the file for reading and writing in binary mode. a)
rb b) rb+ c) wb d) a+
Ans: b) rb+
8. Which file mode can be used to open a binary file in both append and read mode?
a) w+ b) wb+ c) ab+ d) a+
Ans: (c) ab+
9. Sheela is a Python programmer. She has written a code and created a binary file “book.dat”
that has structure [BookNo, Book_Name,Author, Price]. The following user defined function
CreateFile() is created to take input data for a record and add to book.dat and another user
defined function CountRec(Author) which accepts the Author name as parameter and count
and return number of books by the given Author.As a Python expert, help her to complete the
following code based on the requirement given above:
import ___________ #statement1
def createFile():
fobj = open("book.dat","________") #statement2
BookNo = int(input("Book number:"))
Book_Name = input("Book Name:")
Author = input("Author:")
Price = int(input("Price:"))
rec = [BookNo, Book_Name, Author, Price]
pickle.__________________
#statement3 fobj.close() def
Count_Rec(Author):
fobj = open("book.dat","rb")
num = 0
try:
while True:
rec = pickle._______________ #statement4
if Author == rec[2]:
num=num+1
except:
45 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
fobj.close()
return num
(i) Which module should be imported in the program? (Statement 1)
(ii) Write the correct statement required to open a file named book.dat.(Statement 2)
(iii) Which statement should be filled in Statement 3 to write the data into the binary file,
book.dat?
(iv) Statement 4 to read the data from the file, book.dat?
Ans:
(i) pickle
(ii) ab
(iii) dump(rec, fobj)
(iv)load(fobj)
10. Mr. Deepak is a Python programmer. He has written a code and created a binary file
“MyFile.dat” with empid, ename and salary. The file contains 15 records. He now has to update
a record based on the employee id entered by the user and update the salary. The updated
record is then to be written in the file “temp.dat”. The records which are not to be updated also
have to be written to the file “temp.dat”. If the employee id is not found, an appropriate
message should to be displayed. As a Python expert, help him to complete the following code
based on the requirement given above:
import _______ #Statement 1
def update_rec():
rec={}
fin=open("MyFile.dat","rb")
fout=open("_____________") #Statement 2
found=False eid=int(input("Enter employee id to
update salary : ")) while True: try:
rec=______________ #Statement 3
if rec["empid"]==eid:
found=True
rec["salary"]=int(input("Enter new salary : "))
pickle.____________ #Statement
4 else: pickle.dump(rec,fout)
except:
break
if found==True: print("The salary of employee id ",eid," has been
updated.")
else:
print("No employee with such id is not found")
fin.close()
fout.close()
(i) Which module should be imported in the program? (Statement 1)
(ii) Write the correct statement required to open a temporary file named temp.dat.(Statement
2) (iii) Which statement should Deepak fill in Statement 3 to read the data from the binary
file, record.dat and in Statement 4 to write the updated data in the file, temp.dat?
46 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Ans: (i) Ans: pickle
(ii) fout=open(‘temp.dat’, ‘wb’) (iii)
Statement 3: pickle.load(fin)
iv)Statement 4:
pickle.dump(rec,fout)
CSV FILE: A Comma Separated Values (CSV) file is a plain text file that contains the
comma-separated data. These files are often used for exchanging data between different
applications.
Python CSV Module: To work with CSV Files, programmer has to import CSV Module.
import csv
writer( ) Object Methods : The writer object has two functions that can be used:
● w_obj . writerow( <Sequence> ) : Write a Single Line/row
● w_obj . writerows ( <Nested Sequence> ) : Write Multiple Lines/rows
Example:- ## writerow()
import csv
row=['Nikhil', 'CEO', '2', '9.0']
f=open("myfile.csv", 'w')
w_obj = csv.writer(f)
w_obj.writerow(row)
f.close()
## writerows() import csv
rows = [['Nikhil','CEO','2','9.0'],
['Sanchit','CEO','2','9.1']]
f=open("myfile.csv",'w') w_obj = csv.writer(f)
w_obj.writerows(rows)
f.close()
reader( ) Methods: This function returns a reader object which is used to iterate over lines
of a given CSV file. Each iteration over the reader object returns a list of strings
r_obj = csv.reader(csvfile_obj)
47 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Example: reading a csv file:
import csv
f=open("myfile.csv",'r')
r_obj = csv.reader(f) for
data in r_obj:
print(data)
f.close()
2.Write a program to add/insert records in file “data.csv”. Structure of a record is roll number,
name and class. import csv
field = ["Roll no" , "Name" , "Class"]
f = open("data.csv" , 'w')
d=csv.writer(f)
d.writerow(field)
rn=int(input("Enter Roll number:
")) nm = input("Enter name: ") cls
= input("Enter Class: ")
rec=[rn,nm,cls]
d.writerow(rec)
f.close()
48 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
a. EOL b. Delimiter c. EOF d. Default
4. _____ module of Python provides the functionality to read and write tabular data in
CSV file.
a. pickle b. csv c. file d. ccv
10. The opening function of a csv file is similar to the opening of:
a. Binary file
b. Text File
c. Both of them
d. None of them
11. The _______argument of open function is to specify how Python handle the
newline
characters in csv file
a. newline b. line c. mode d. char
49 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
12. Which among the following is an iterable object?
a. writer
b. file
c. reader
d. All of the above
13. To specify a different delimiter while writing into a csv file,argument is used with writer
object:
a. newline b. separator c. character d. delimiter
14. Which mode opens the file for exclusive creation, which fails in the case where file
already exists
a. a b. w c. x d. r
15. The file mode to open a CSV file for reading as well as writing is .
a. a+ b. w+ c. r+ d. All the above.
16. Identify the line number which may cause an error: import csv #Line1
line=[[1,2,3],[4,5,6]]#Line 2 with open("sample.csv","w",newline="") as csvfile: #Line3
writer=csv.writer(csvfile,delimiter="|") #Line4 for line in writer: #Line5
writer.writerow(line)
20. Ajaikrishna wants to separate the values by a $ sign. Suggests him a pair of function and
parameter to use it.
a. open, quotechar
b. writer, quotechar
c. open, delimiter
50 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
d. writer, delimiter
21. Tejalakshmi of Class 12 have written the below code. Observe and fill in the given
blanks so that it opens the file “data.csv” and read and print all the records.
V. What is the default data type of data read from this file?
a. List b. String c. Tuple d. Integer
22. Sudev, a student of class 12th, is learning CSV File Module in Python. During examination,
he has been assigned an incomplete python code to create a CSV file ‘customer.csv’. Help him
in completing the code which creates the desired CSV file.
51 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
I. Identify suitable code for the blank space in line marked as Statement-1.
a) include b) add c) Import d) import
II. Identify the missing code for the blank space in line marked as Statement-2.
a) Customer
b) reader
52 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
c) csvwriter
d) writer
III. Identify the argument name for the blank space in line marked as Statement-3?
a) Row
b) Rec
c) row
d) rec
IV. Identify the missing file name for the blank space in line marked as Statement-4?
a) customer
b) customer.csv
c) customer.txt
d) customer.dat
V .Identify the object name for the blank space in line marked as Statement-5?
a) i
b) Rec
c) row
d) rec
23. Daya of class 12 is writing a program to create a CSV file “empdata.csv” with empid, name
& mobile number. Also, to search a particular empid and display its record details. He has
written the following code. As a programmer, help him to successfully execute the given task.
53 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
I. Choose the module he should import in Line1.
a) math b) pickle c) csv d) random
II. Choose a code to write the column heading from fields list in Line2.
a) writerows(fields) b) writerow(field)
c) writerow(fields) d) writerows(fields)
III. Choose a code to write the row from rows list in Line3.
a) writerows(row) b) writerow(row)
c) writerow(rows) d) write_row(row)
IV. Choose a code for line 4 to read the data from a csv file.
a) csv.reader(f) b) csv.read(f) d) pickle.load(f) e)f.read()
25. Rinsha of class 12 is writing a program to create a CSV file “user.csv” which will contain
user name and password for some entries. She has written the following code. As a
programmer, help her to successfully execute the given task.
54 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
I. Name the module she should import in Line 1.
a. CSV b. csv c. math d. File
II. In which mode, Rinsha should open the file to add data into the file.
a. r b. a c. w d. w+
III. Fill in the blank in Line 3 to read the data from a csv file.
a. writer()
b. reader()
c. write()
d. read()
IV. Fill in the blank in Line 4 to close the file.
a. End() b. Close() c. close() d. end()
55 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
ANSWERS
QNO
OPT
I b
II b
25 III b
IV c
28. Vedansh is a Python programmer working in a school. For the Annual Sports Event, he has
created a csv file named Result.csv, to store the results of students in different sports events.
The structure of Result.csv is : [St_Id, St_Name, Game_Name, Result]
Where
St_Id is Student ID (integer)
ST_name is Student Name (string)
Game_Name is name of game in which student is participating(string)
Result is result of the game whose value can be either 'Won', 'Lost' or 'Tie'
For efficiently maintaining data of the event, Vedansh wants to write the following user defined
functions:
Accept() – to accept a record from the user and add it to the file Result.csv. The column
headings should also be added on top of the csv file.
wonCount() – to count the number of students who have won any event.
As a Python expert, help him complete the task.
56 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
ANSWER:
def Accept(): sid=int(input("Enter
Student ID ")) sname=input("Enter
Student Name") game=input("Enter
name of game")
res=input("Enter Result")
headings=["Student ID","Student Name","Game
Name","Result"] data=[sid, sname, game, res]
f=open("Result.csv", "a", newline="") csvwriter=csv.writer(f)
csvwriter.writerow(headings) csvwriter.writerow(data)
f.close()
def wonCount():
f=open("Result.csv","r")
csvreader=csv.reader(f,delimiter=",")
head=list(csvreader) print(head[0])
for x in head: if x[3]=="WON":
print (x)
f.close()
29. Kiran is a Python programmer working in a shop. For the employee’s tax collection, he has
created a csv file named protax.csv, to store the details of professional tax paid by the
employees. The structure of protax.csv is : [empid, ename, designation, taxpaid]
Where,
empid is employee id (integer) ename is
employee name (string) designation is
employee designation(string)
taxpaid is the amount of professional tax paid by the employee(string)
For efficiently maintaining data of the tax, Kiran wants to write the following user defined
functions:
Collection() – to accept a record from the employee and add it to the file protax.csv.
Totaltax() – to calculate and return the total tax collected from all the employees.
As a Python expert, help him complete the task.
ANSWER:
def Accept():
empid=int(input("Enter Employee ID "))
ename=input("Enter Employee Name")
designation=input("Enter the Designation")
taxpaid=input("Enter the tax amount")
data=[empid, ename, designation, taxpaid]
f=open("protax.csv", "a", newline="")
csvwriter=csv.writer(f) csvwriter.writerow(data)
f.close()
57 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
def Totaltax():
f=open("protax.csv","r")
csvreader=csv.reader(f,delimiter=",")
content=list(csvreader)
total=0 for row in content: total+=int(row[3]) f.close() return total 30. Arun of
class 12 was writing a program to read the CSV file “mydata.csv” which will contain user name
and password for some entries. As a programmer, help him to write the following user defined
functions: adddata() – to add a new entry to the file “mydata.csv.
display() – to display the content of the file “mydata.csv”.
ANSWER: def adddata():
userid=input("Enter Username:")
passwd=input("Enter th password: ")
entry=[userid,passwd]
f=open("mydata.csv", "a", newline="")
csvwriter=csv.writer(f)
csvwriter.writerow(entry)
f.close()
def display():
f=open("mydata.csv","r")
csvreader=csv.reader(f,delimiter=",")
content=list(csvreader) for rec in
content:
print(rec)
f.close()
DATA STRUCTURE
Data Structure: Data structures deal with how the data is organized and held in the memory.
Stack: Stack is a data structure in which insertion and deletion can take place only at one end
according to the Last-In-First-Out (LIFO) concept.
Applications of Stack
1. Reversing a word/line: This can be accomplished by pushing each character on to a stack as
it is read. When the line is finished, characters are popped off the stack and they will come
off in the reverse order.
2. The compilers use stacks to store the previous state of a program when a function is called
during recursion.
3. Backtracking is a form of recursion. But it involves choosing only one option out of
possibilities. Used in solving Puzzle Sudoku.
4. Undo mechanism in Text editors by keeping all the text changes in a stack.
58 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Implementation of stack – menu oriented program
def POP():
if L == []:
print("List is Empty - UNDERFLOW")
else:
N = L.pop()
print("The Element Deleted in Stack is :", N)
def DISPALL():
if L == []:
print("List is Empty")
else:
print("List in LIFO ORDER:")
for i in range(len(L)-1, -1, -1):
print(L[i], end='<--')
while True:
print("\n\n\tMENU:")
print("\t----")
print("1. PUSH")
print("2. POP")
print("3. DISPLAY
ALL") print("4.
EXIT") ch=
int(input("Enter the
Choice:")) if ch == 1:
PUSH() elif ch == 2:
POP() elif ch == 3:
DISPALL() elif ch
== 4: break
else:
print("Give correct choice")
59 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
1 A list, NList contains following record as list elements: 3
[City, Country, distance from Delhi]
Each of these records are nested together to form a nested list. Write the following user
defined functions in Python to perform the specified operations on the stack named
travel. (i) Push_element(NList): It takes the nested list as an argument and pushes a
list object containing name of the city and country, which are not in India and distance
is less than 3500 km from Delhi.
(ii) Pop_element(): It pops the objects from the stack and displays them. Also, the
function should display “Stack Empty” when there are no elements in the stack. For
example: If the nested list contains the following data:
NList=[["New York", "U.S.A.", 11734],
["Naypyidaw", "Myanmar", 3219],
["Dubai", "UAE", 2194],
["London", "England", 6693],
["Gangtok", "India", 1580],
["Columbo", "Sri Lanka", 3405]]
The stack should contain:
['Naypyidaw', 'Myanmar'],
['Dubai', 'UAE'],
['Columbo', 'Sri Lanka']
The output should be:
['Columbo', 'Sri Lanka']
['Dubai', 'UAE']
['Naypyidaw', 'Myanmar']
Stack Empty
A
n
s
A def POP(A):
n
if len(A) = = 0:
s
print(“UNDERFLOW”)
else:
60 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
val=A.pop( )
return val
3. Write a function PUSH(STACK,Name) to add new name to the STACK data structure . 3
Also display all the names having at least 4 characters from the stack.
A def PUSH(STACK,Name):
n
STACK.append(Name)
s
#code for displaying
if len(STACK)==0:
print(“Empty stack”)
else:
top=len(STACK)-1
for i in range(top,-1,-1):
if len(STACK[i])>=4:
print(STACK[i] )
5. UNSOLVED EXERCISE: 3
Coach Abhishek stores the races and participants in a dictionary. Write a program, with
separate user defined functions to perform the following operations:
a. Push() Push the names of the participants of the dictionary onto a stack, where the
distance is more than 100.
b. PoP() Pop and display the content of the stack.
For example:
If the sample content of the dictionary is as follows: Races ={100:'Varnika', 200 :'Jugal',
400:'Kushal', 800:'Minisha'}}
The output from the program should be: Minisha Kushal Jugal
SAMPLE QUESTIONS:
MCQ/Very Short Answer Type Questions(1-mark)
1. Which list method can be used to perform Push operation in a stack implemented by list?
a) append() b)extend() c) push() d) insert()
2. Which list method can be used to perform Pop operation in a stack implemented by list?
a) pop() b) pop(1) c) remove() d) pop(0)
61 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
8. Can we have nested list?
9. Name one linear data structure.
10. Name one non-linear data structure.
11. Name the operation for insertion in a stack.
12. Name the operation for deletion from a stack.
13. Name the function to find length of a list.
14. Indexing in list starts from?
62 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
X[1].append(10)
print(X)
11. Consider STACK=[‘a’,’b’,’c’,’d’]. Write the STACK content after each operations:
(a) STACK.pop( )
(b) STACK.append(‘e’)
(c) STACK.append(‘f’)
(d) STACK.pop( )
12. Write a program to implement a stack for the students(studentno, name). Just implement
Push.
13. Write a program to implement a stack for the students(studentno, name). Just implement
Pop and display.
14. If L=["Python", "is", "a", ["modern", "programming"], "language", "that", "we", "use"] ,
then find the output:
(a) L[0][0]
(b) L[3][0][2]
(c) L[3:4][0]
(d) L[3:4][0][1]
(e) L[3:4][0][1][3]
(f) L[0:9][0]
(g) L[0:9][0][3]
(h) L[3:4][1]
63 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
3. Write a function in Python nameadd(L), where L is a list of names. The function should
add all the names whose length is longer than 5 characters on to the stack. It should also display
the stack if it has at least one element, otherwise display “stack empty” message.
For example: nameadd( [‘Shyamlal’, ‘Gopi’, ‘Anand’, ‘Mritunjay’] )
The above function call should give output as: Stack is: [‘Shyamlal’, ‘Mritunjay’]
ANSWER KEY
6. Data Structure means organization of data. A data structure has well defined operations
or behaviour.
7. STACK
8. Yes
9. Lists
10. Graphs
11 PUSH
12 pop
13. len()
14. 0
65 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
(c) Ans: ['modern', 'programming']
(d) Ans: 'programming'
(e) Ans: 'g'
(f) Ans: 'Python'
(g) Ans: 'h'
(h) Ans: IndexError: list index out of range
15. Ans: pop() will delete the last element of a list whereas pop(0) will delete
element at index zero of a list
1.
stk=[] def
Push(nums):
for i in nums:
if i%2==1:
stk.append(i)
if stk==[]:
print('stack is empty')
else: print('stack is:',
stk[: :-1])
2
.
stk=[] def
push(pbook):
for k in d:
if 'a' in k:
stk.append(d[k])
if stk==[]:
print('stack empty')
else: print('stack
is:', stk)
3. stk=[] def
nameadd(L):
for i in L: if
len(i)>5:
stk.append(i)
if stk==[]:
66 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
print('stack empty')
else: print('stack
is:', stk)
4. stk=[] def
push(mydict):
phonebook=list(mydict.keys())
for mob in phonebook: if
len(str(mob)) == 10:
stk.append(mob) if stk==[]:
print('stack empty')
else:
print('stack is:', stk)
COMPUTER NETWORKS
A group of two or more similar things or people interconnected with each other is called
network. Examples are social network and mobile network
Computer Network: A Computer network is an interconnection among two or more
computers or computing devices. Th advantages of computer networks are:
● Resource Sharing
● Collaborative Interaction
● Cost Saving
● Increased storage
● Time Saving
Evolution of Network:
(I)ARPANET (Advanced Research Project Agency Network)
● It came into existence in 1960s
● A project for interconnecting, US department of defense with academic and research
organization across different places for scientific collaboration.
(II)NSFNET (National Science Foundation Networks)
● It came into existence in 1986
● It was the first large-scale implementation of Internet technologies in a complex
environment of many independently operated networks
(III) INTRANET
● It is a local or restricted communication system ● It is managed by a
person or organization.
● Intranet users can avail services from internet but Internet user
cannot access intranet directly
(III) INTERNET
● It came into existence in 1960s
● It is known as Network of Networks
● A global computer network providing variety of information and communication
facilities consisting of interconnected networks using standardized communication
protocols.
67 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
DATA COMMUNICATION TERMINOLOGIES
DATA: Data means information in digital form such as text, audio, video which is stored
processed and exchanged between digital devices like computer, mobile phones or laptop.
Computers process the raw data into meaningful information. Information is processed data.
COMMUNICATION: The exchange of information between two or more networked or
interconnected devices is called communication
COMPONENTS OF DATA COMMUNICATION
c) MESSAGE: message is the information being exchanged between a sender and a receiver
over a communication network.
e) PROTOCOLS: The set of standard rules which are followed in data communication are
known as Data Communication Protocols. All the communicating devices like sender receiver
and other connected devices in the network should follow these protocols .
BANDWIDTH: Bandwidth is the difference between the highest and lowest frequencies a
transmission media can carry. The unit of bandwidth is Hertz.
68 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
DATA TRANSFER RATES: Data transfer rate is the number of bits transmitted through a
channel per unit of time. Data transfer rate is measured in bits per second (bps). It is also
measured in Kilobits per second (Kbps), Megabits per second (Mbps) or Gigabits per second
(Gbps).
69 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
SWITCHING TECHNIQUES
In large networks, there may be more than one paths for transmitting data from sender to
receiver. The process of selecting a path of data out of the available paths is called switching.
There are two popular switching techniques – circuit switching and packet switching.
LAN (Local Area Network): Local Area Network is a group of computers connected to
each other in a small area such as a building, office through a communication medium such as
twisted pair, coaxial cable, etc to share resources.
WAN (Wide Area Network): A Wide Area Network is a network that extends over a large
geographical area such as states or countries through a telephone line, fiber optic cable or
satellite links. The internet is one of the biggest WAN in the world.
70 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Networking Topologies
Bus
It uses a single cable, called a trunk or segment, along which all the computers of the network
are connected
Star
All computers are connected using cable segments to a central component called a switch. The
signals from the transmitting computer go through the switch to all the others.
Tree
Tree Topology is a topology which is having a tree structure in which all the computers are
connected like the branches which are connected with the tree.
NETWORK PROTOCOL: A protocol means the rules that are applicable for a network.
Protocols defines standardized formats for data packets, techniques for detecting and correcting
errors etc.
TCP/IP (Transmission Control Protocol/ Internet Protocol
● The IP protocol ensures that each computer or node connected to the Internet is
assigned an IP address, which is used to identify each node independently.
71 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
● TCP ensures that the message or data is broken into smaller chunks, called IP packets.
Each of these packets are routed (transmitted) through the Internet, along a path from one
router to the next, until it reaches the specified destination. TCP guarantees the delivery of
packets on the designated IP address. It is also responsible for ordering the packets so that they
are delivered in sequence.
FTP (File Transfer Protocol): It is a standard internet protocol provided by TCP/IP used for
transmitting the files from one host to another. It is mainly used for transferring the web page
files from their creator to the computer that acts as a server for other computers on the internet.
It is also used for downloading the files to computer from other servers.
SMTP (Simple Mail Transfer Protocol.): SMTP is a set of communication guidelines that
allow software to transmit an electronic mail over the internet is called Simple Mail Transfer
Protocol.
Point-to-Point Protocol (PPP) is protocol that is used to directly connect one computer system
to another. Computers use PPP to communicate over the telephone network or the Internet.
Post Office Protocol version 3 (POP3) Protocol: (POP3) is a standard mail protocol used to
receive emails from a remote server to a local email client. POP3 allows you to download
email messages on your local computer and read them even when you are offline. en J, and
JVM Telnet Telnet is a program that allows a user to log on to a remote computer. Telnet
provides a connection to the remote computer in such a way that a local terminal appears to be
at the remote side.
VoIP : VoIP stands for Voice over Internet Protocol. It is also referred to as IP telephony,
internet telephony, or internet calling.
Web Services: Web Services means the services provided by World Wide Web. The World
Wide Web provides services like chatting, emailing, video conferencing, e-learning, e-
shopping, e-reservation, e-groups and social networking.
World Wide Web (WWW): The World Wide Web commonly referred to as WWW, W3, or
the Web is an interconnected system of public webpages accessible through the Internet.It was
invented by Tim Berners-Lee in 1989. Major components of WWW are:
1. Web Server – It is a computer that stores website resources (web pages, images, videos,
etc.).
2. Web Browser (Client) - A software application used to access the web resources.
3. Webpage - Hypertext documents formatted in Hypertext Mark-up Language (HTML)
and displayed in a web browser.
4. Website - A website is a collection of inter-linked web pages that is identified by a
common domain name (website name) and stored on a web server.
5. HTTP Protocol - It governs data (web page) transfer between a server and a client.
6. HTML- A mark-up language used to specify the structure of a webpage.
7. URL- Address used to identify documents and other web resources on the internet.
Web Architecture
Web is working based on a client-server architecture.
72 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Client: It is a computer capable of requesting, receiving & displaying information in the form
of web pages or using a particular service from the service providers (Servers).
Servers: It is a remote computer which provides/transfers information to the client (in the form
of web pages) or access to particular services.
HTML (Hypertext Mark-up Language): It is a mark-up language that tells web browsers
how to structure the web pages you visit. It has a variety of tags and attributes for defining the
layout and structure of the web document. A HTML document has the extension .htm or .html.
Hypertext is a text which is linked to another html document via clickable links known as
hyperlinks.
XML (eXtensible Mark-up Language): XML is a mark-up language like HTML but it is
designed to transport or store data. It does not have predefined tags but allows the programmer
to use customized tags. An XML document has the extension .xml.
73 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Closing tags are optional. Compulsory to use closing tags.
HTTP - Hyper Text Transfer Protocol: HTTP is used to transfer data across the web. HTTP
specifies how to transfer hypertext (linked web documents) between two computers. It allows
users of the World Wide Web to exchange information found on web pages.
Hypertext Transfer Protocol Secure (HTTPS) is an extension of the HTTP which is used for
secure communication over a computer network.
Domain Names: Every device connected to the Internet has a numeric IP address which is very
difficult to remember. Each computer server hosting a website or web resource is given a name
known as Domain Name corresponding to unique IP addresses. For example, IP addresses and
domain names of some websites are as follows:
Domain Name IP Address
ncert.nic.in 164.100.60.233
cbse.nic.in 164.100.107.32
The process of converting a hostname (such as www.google.com) into the corresponding IP
address (such as 172.217.14.196) is called domain name resolution. Specialized DNS servers
are used for domain name resolution (DNS resolution).
URL-Uniform Resource Locator: Every web page that is displayed on the Internet has a
specific address associated with it, this address is known as the URL. The structure of a URL
can be represented as follows:
http://www.example.com/planet/earth/river.jpg
74 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
visited. Web Server: A web server is a computer or a group of computers hosting one or more
websites. E.g., Apache, IIS etc.
Web Hosting: Web hosting is the process of uploading/saving the web content on a web server
to make it available on WWW.
76 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
26. ________________ is a computer software capable of requesting, receiving & displaying
information in the form of webpages.
(a) Web Servers (b) Web Browsers
(c) Web Designers (d) Web Camera
27. A ____________ is a program or automated script which browses the World Wide Web in
a methodical, automated manner.
(a) Web Servers (b) Web Browsers
(c) Web Designers (d) Web Crawler
28.________________ is a mark-up language that helps in developing web pages.
(a) HTTP (b) HTML (c) XML (d) C++
29. ________________ is a language used to transport data over internet.
(a) HTTP (b) HTML (c) XML (d) C++
30.___________ is a set of rules for communication between two computers over a network.
(a) Modem (b) Protocol
(c) Switch (d) IP address
31.In web services, the communication takes place between
(a) Two electronic devices (b) Two human beings
(c) Two spiders (d) None of the above
32.Web services means services provided by ________________________
(a) Microsoft (b) Google
(c) BSNL (d) World Wide Web
77 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
a. HTTP
b. XML
c. HTTPS
d. HTML
e. VoIP
21. Name any two common web browsers.
22. Full form of Email is ______________________
23.What out of the following, you will use to have an audio visual chat with an expert sitting in
a faraway place to fix-up technical issues?
(i) E-mail (ii) VoIP (iii) FTP
24. Match the following
Web Services Description
A Video conferencing P Without ever having to go booking office
Self-paced learning modules allow students to
B E-Shopping Q
work at their own speed
Each of the end user has a camera as well as
C E-mail R microphone to capture video and audio in real
time and it will be transmitted over internet
Purchasing products through computers/mobile
D E-reservation S
devices
Messages normally reaches a recipients account
E E-learning T
within seconds
78 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
An example IP Address format is given below:
192.158.12.38
3. Explain how an IP Address become helpful in investigating cyber-crimes.
IP address can be used to trace the physical location of a user connected to a network. By this
many cyber crime can be investigated and traced out efficiently tracking the exact location
from where the cybercrime is carried out.
9. What is the difference between domain name and IP address? IP addresses look like this:
192.168.12.134.
Domain names look like this: “www.google.com”
Domain names are easier for us to remember and use, while computers are quite handy with
numbers. Thus, we use DNS (Domain Naming System) to translate domain names into the IP
addresses.
IP address is a unique identifier for a computer or device on internet. A domain name (website
name) is a name that identifies one or more IP addresses (when hosted at different servers for
load balancing).
10. Give one suitable example of each URL and domain name?
URL: https://kvsangathan.nic.in/hq-gyan-kosh
Domain name: kvsangathan.nic.in
79 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
11. Differentiate between XML and HTML.
XML was designed to describe data and to focus on what data is.
HTML was designed to display data and to focus on how data looks.
HTML is about displaying information while XML is about describing information.
13. Differentiate between the terms Domain Name and URL in context of web services. Also
write one example of each to illustrate the difference.
Domain Name URL
A domain name or website name URL is a string that represents the complete web
is a human-friendly text form of address of any web page. It’s used to locate a
the IP address. webpage.
It is the part of the URL that is It is the string that represents a complete web
more human friendly. address that contains the domain name.
Example: kvsangathan.nic.in Example: https://kvsangathan.nic.in/contact-us
22.Differentiate between communication using Optical Fiber and Ethernet Cable in context of
wired medium of communication technologies.
Optical Fibre - Very Fast - Expensive - Immune to electromagnetic interference
Ethernet Cable - - Slower as compared to Optical Fiber - Less Expensive as compared
to Optical Fiber - prone to electromagnetic interference
4) Which of the following is not a network protocol? (i) HTML (ii) HTTP (iii) SMTP
(iv) FTP
5) Which of the following internet protocols provides secure data transmission between
server and browser with the help of encryption.
a) HTTP b) HTTPS c) TELNET d) ARPANET
80 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
6) Devanand, a student of Class XII, is not able to understand the difference between web
client and web-server. Help him in understanding the same by explaining their role and
giving suitable example of each.
7) Write the full form of Cc and Bcc (used in email communication). Explain the
difference between them.
8) Define Internet and write its two uses in our daily life. How is it different from the
World
Wide Web (WWW).
10) In a network, _____________ is a computer that provides data and resources to other
computers.
14) Among the following service available on the World Wide Web are?
i) Email ii) HTML iii) XML iv) Video conferencing
a) (i) and (ii) (b) (i) and (iv)
(c) (ii) and (iii) (d) None of the above
15) HTML and XML are _______________
a) Programming Languages (b) Scripting Languages
(c) Mark-up Languages (d) None of the above
16) XML uses _____________
a) User defined tags (b) Predefined Tags
(c) Both user defined and predefined tags (d) None of the above
17) XML was not designed to ____________________
a) store the data (b) present the data
(c) carry the data (d) both a & c
18) Which of the following will you suggest to establish the online face to face
communication between the people in the Regional Office Ernakulum and Delhi
Headquarter?
a) Cable TV (b) Email (c) Text chat
(d) Video Conferencing
19) What kind of data gets stored in cookies and how is it useful?
23) ____________ tags are case sensitive and _____________ tags are not case sensitive.
(a) HTML, XML (b) HTTP, XML
(c) XML, HTTP (d) XML,HTML
25) Which protocol helps us to browse through web pages using internet browsers?
30) 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 below: Study the following structure and answer
questions (a) to (e)
2. What happens to the Network with Star topology if the following happens:
(i) One of the computers on the network fails?
(ii) The central hub or switch to which all computers are connected, fails?
3. Two doctors have connected their mobile phones to transfer a picture file of a person
suffering from a skin disease. What type of network is formed?
4. SunRise Pvt. Ltd. is setting up the network in the Ahmadabad. There are four
departments named as MrktDept, FunDept, LegalDept, SalesDept.
i) Suggest a cable layout of connections between the Departments and specify topology.
ii) Suggest the most suitable building to place the server with a suitable reason. iii)
Suggest the placement of i) modem ii) Hub /Switch in the network. iv) The
83 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
organization is planning to link its sale counter situated in various part of the same
city/ which type of network out of LAN, WAN, MAN will be formed? Justify.
5. Name the protocol Used to transfer voice using packet switched network.
6. What is HTTP?
7. Write the purpose of the following devices:
(i). Network Interface Card
(ii). Repeater
3. The following is a 32 bit binary number usually represented as 4 decimal values, each
representing 8 bits, in the range 0 to 255 (known as octets) separated by decimal points. 192.158.1.38
What is it? What is its importance?
4. Dinsey has to share the data among various computers of his two offices branches situated in
the same city. Name the network (out of LAN, WAN, PAN and MAN) which is being formed in this
process.
5. . Global Pvt. Ltd. is setting up the network in the Bangalore . There are four departments
Distances between various buildings are as follows:
Accounts to Research Lab 55 m
Accounts to Store 150 m
Store to Packaging Unit 160 m
Packaging Unit to Research Lab 60 m
Accounts to Packaging Unit 125 m
Store to Research Lab 180 m
Number of Computers
Accounts 25
84 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Research 100
Lab
Store 15
Packaging 60
Unit
1. c 2. a 3. a 4. b 5. a
6. a 7. d 8. d 9. b 10. a
31. a 32. d
85 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
9. Web servers
10. hyperlinks
11. HTTP- HyperText Transfer Protocol
12. HyperText Transfer Protocol
13. World Wide Web(WWW) or Web
14. Refer comparison table
15. Chat
16. E-learning
17. Internet banking
18. E-reservation 19. Social networking websites 20.
a. HTTP- HyperText Transfer Protocol
b. XML – eXtensible Mark-up Language
c. HTTPS - HyperText Transfer Protocol Secure
d. HTML - HyperText Mark-up Language
e. VoIP-Voice over Internet Protocol
21. Google Chrome, Mozilla Firefox
22. Electronic mail
23. Ii.VoIP 24.
A Video conferencing P Each of the end user has a camera as well as
microphone to capture video and audio in real time
and it will be transmitted over internet
B E-Shopping Q Purchasing products through
computers/mobile devices
C E-mail R Messages normally reaches a recipients account within
seconds
D E-reservation S Without ever having to go booking office
E E-learning T Self-paced learning modules allow students to work at
their own speed
25.
Web Services Applications
A Video conferencing P VConSol
B E-Shopping Q GEM
C E-mail R Gmail
D E-reservation S IRCTC
E E-learning T Diksha App
F Social Networking U Instagram
86 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
For email communication, we use SMTP and POP.
For communication between browser and server HTTP and HTTPS protocols are used. We
can use TELNET to access services available on a remote computer.
5. b) HTTPS
6. Web-Client: An application that requests for services from a webserver. Example: Web
Browsers, Chatting Applications
Web-Server: Web-server is a software (or any dedicated computer running this software) that
serves the request made by web-clients. Example: Apache Server.
7. Cc : Carbon Copy: every recipient can check who else has received the mail. Bcc :
Blind Carbon Copy: no recipient can check who else has received the mail.
8. The Internet is a worldwide network that links many smaller computer-networks. Uses
of the Internet 1. E-learning 2. E-commerce
The difference between the internet and www:
Internet means interconnected networks that spread all over the world (i.e. the physical
infrastructure), while WWW means the information’s (available in the form of webpages) that
can be accessed through internet.
9. Web Browser
10. Server
11. A website is a collection of interlinked webpages.
12. Web Browsers
13. Role of server is to serve various clients (sharing data or resources among multiple
clients)
14. (b) (i) and (iv)
15. (c) Mark-up Languages
16. (a) User defined tags
17. (b) present the data
18. (d) Video Conferencing
19. Cookies can store a wide range of information, including personally identifiable
information (such as your name, home address, email address, or telephone number).
Cookies often store your settings for a website, such as your preferred language or location.
When you return to the site, browser sends back the cookies that belong to the site. This allows
the site to present you with information customized to fit your needs.
20. (a) .com - commercial
(b) .org - organization
21. XML tags are created by the user as there are no standard tags.
Ex : <name>Nayana<name>
22. The process of converting domain names (website names) into corresponding IP address
with the help of DNS servers is called domain name resolution.
23. (d) XML,HTML
24. (d) Photoshop
25. HTTP - Hyper Text Transfer Protocol
26. Google Chrome or any other valid browser name
27. (B) Extensible Markup Language
28. (D) FTP
29. Web Server
87 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
30 a. Most suitable place to install the server is HR center, as this center has maximum number
of computers. c. Switch
d. Repeater may be placed when the distance between 2 buildings is more than 70 meter.
e. WAN, as the given distance is more than the range of LAN and MAN.
3. PAN
ii) As per 80 – 20 rule, SalesDept because it has maximum no. of computers. iii)Each
building should have hub/switch and Modem in case Internet connection is required.
iv)MAN (Metropolitan Area Network)
5. VoIP
6. HTTP is a protocol that is used for transferring hypertext(i.e. text, graphic, image,
sound, video, etc,) between 2 computers and is particularly used on the World Wide
Web
(WWW) 7.
(i) Network Interface Card (NIC) is a network adapter used to set up a wired network. It acts
as an interface between computer and the network.
(ii) A repeater is a device that amplifies a signal being transmitted on the network.
88 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Test Yourself: PART II
1. LAN
2.
a. Star Topology
b. Bus Topology
3. It is an IP Address. It is used to identify the computers on a network
4. MAN
5. (i)
(ii)The most suitable place/ building to house the server of this organization would be building
Research Lab, as this building contains the maximum number of computers
(iii). a)Repeater : distance between Store to Research Lab is quite large, so a repeater
would ideally be placed.
b)Hub/Switch : Each would be needed in all the buildings to interconnect the group of
cables from the different computers in each building.
6.IP address 192.168.1.1
URL : https://www.apple.com/
89 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
DBMS-DATABASE MANAGEMENT SYSTEM
DBMS: A database management system (DBMS) is a software that is responsible for storing,
maintaining and utilizing databases.
Examples- MySQL, Oracle, PostgreSQL, SQL Server, Microsoft Access, MongoDB.
Relational model:
The relational model uses a collection of tables to represent both data and the relationships
among those data. Each table has multiple columns, and each column has a unique name.
The columns of the table correspond to the attributes of the record type and a row in a table
represents a relationship among a set of values.
90 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Candidate Key –It is an attribute or a set of attributes or keys participating for Primary Key,
to uniquely identify each tuples in that relation.
Alternate Key – A candidate key that is not the primary key is called alternate key or
secondary key.
Foreign Key – Foreign keys are the attributes of a relation that points to the primary key of
another relation
Model Questions
I. Multiple choice Questions(MCQ):
1. DBMS stands for_____________
a) Data Base Management Software
b) Data Base Maintenance System
c) Data Basic Management System
d) Data Base management system 2. In RDBMS, R stands for_________
a) Relational
b) Rotational
c) Rational
d) None of the above
15. Which of the following statements is not true about relational database?
a) Relational data model is the most widely used data model.
b) The data is arranged as a collection of tables in relational database.
c) Relational database increases data redundancy and inconsistency.
d) None of the above.
16. Which of the following is a disadvantage of file processing system?
a) Data redundancy
b) Data isolation
c) Data inconsistency
d) All of the above
c) Which column can be made as the primary key in the table Employee?
93 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
i) E
MPID
ii)
EMAIL
iii) Both i and ii
iv) None of the above
d) If two columns are added to the table Employee, then the cardinality and degree
of the table is …… and …… respectively. i) 4 , 7 ii) 7, 4 iii) 6,5 iv) 5,6
18. An attribute in a relation is a foreign key if it is the ________ key in any other relation.
a) Candidate
b) Primary
c) Super
d) Sub
19. A(n) ________ in a table represents a logical relationship among a set of values. a)
Column
b) Key
c) Row
d) Attribute
ANSWERS:
I. Multiple Choice Questions (MCQ )
94 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
1 d 2 a 3 b 4 b
5 a 6 b 7 b 8 a
9 b 10 a 11 b 12 d
13 b 14 a 15 c 16 d
17a) (ii) 17b) (iii) 17c) (iii) 17d) (ii)
18 b 19 c
2 A primary key is a column or set of columns that contain values that uniquely
identify each row in a table.
For example Rno can be primary key of the table student.
Table:Student
RNO NAME MARK
100 Tanay 30
101 Kiran 50
102 Manu 30
95 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
1.4 SQL Commands
SQL commands are used to communicate with the database to perform specific tasks,
functions, and queries of data.
1.5 Types of SQL Commands
There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.
1.5.1 DDL or Data Definition Language : DDL is a set of SQL commands used to create,
modify, and delete database structures/tables but not data. List of DDL commands:
CREATE: This command is used to create the database or its objects (like table, index,
function, views, store procedure, and triggers).
DROP: This command is used to delete objects from the database.
ALTER: This is used to alter the structure of the database.
1.5.2 DML (Data Manipulation Language): DML commands deal with the manipulation of
data present in the tables. List of DML commands:
INSERT : It is used to insert data into a table.
UPDATE: It is used to update existing data within a table.
DELETE : It is used to delete records from a database table.
1.6 DATATYPES
96 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
➢ Date data type Date
1.7 CONSTRAINT: A Constraint is a condition or check applicable on a field or set of fields.
Types of Constraints:
⮚ Unique Constraint :-This ensures that no rows have the same value in the specified
column(s). There can be many unique constraints defined on a table.
Syntax: Create table EMP (ecode integer unique, ename char(20),sex char(1) );
⮚ Primary key Constraint: This declares a column as the primary key of the table This is
similar to unique constraint except that a table can have only one primary key and also that,
a primary key does not allow NULL values but Unique key allows NULL values.
The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table is
created:
CREATE TABLE Persons ( ID int NOT NULL, LastName
varchar(255) NOT NULL, FirstName varchar(255), Age int, PRIMARY KEY (ID));
⮚ Not null: This constraint ensures column should not contain NULL
Syntax: Create table EMP(ecode integer Not null unique, ename char(20),sex char(1) );
1.8 DATABASE COMMANDS IN MYSQL
⮚ CREATE DATABASE: used for creating a database in MySQL. Syntax:
mysql>CREATE DATABASE movies;
⮚ SHOW TABLES: Display all the names of tables present in the database
Syntax: mysql> SHOW TABLES;
⮚ DESCRIBE TABLE : Shows the structure of the table, such as column names, constraints on
column names, etc. The DESC command is a short form of the DESCRIBE command. Both
DESCRIBE and DESC commands are equivalent.
Syntax mysql> DESCRIBE | DESC table_name;
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);
98 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
INSERT INTO table_name VALUES (value1, value2, value3, ...);
Example: DELETE FROM Customers; # Delete all rows from table Customers
SQL Aliases: SQL aliases are used to give a table, or a column in a table, a temporary name.
Aliases are often used to make column names more readable. An alias only exists for the
duration of that query. An alias is created with the AS keyword.
WHERE Clause: The WHERE clause is used to filter records and extract only those
records that fulfill the specified condition. It is used in select, update and delete SQL
statements
= Equal
99 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
<= Less than or equal
The WHERE clause can be combined with AND, OR, and NOT operators.
● The AND operator displays a record if all the conditions separated by AND are TRUE.
● The OR operator displays a record if atleast one of the conditions separated by OR is TRUE.
● The NOT operator displays a record if the condition(s) is NOT TRUE.
The BETWEEN operator selects values within a given range. The values can be numbers, text,
or dates. The BETWEEN operator is inclusive: begin and end values are included.
100 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
The SQL LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards often used in conjunction with the LIKE operator:
The percent sign and the underscore can also be used in combinations!
WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE CustomerName LIKE '%or Finds any values that have "or" in any position
%'
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second
position
WHERE CustomerName LIKE 'a_%' Finds any values that start with "a" and are at
least 2 characters in length
WHERE CustomerName LIKE Finds any values that start with "a" and are at
'a__%' least 3 characters in length
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends
with "o"
101 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
What is a NULL Value?
It is not possible to test for NULL values with comparison operators, such as =, <, or <>.
We will have to use the IS NULL and IS NOT NULL operators instead.
Example
WHERE condition;
102 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
WHERE CustomerID = 1;
Aggregate (Group) function
● Aggregate functions are the functions that operate on a set of rows to give one result
per group.
● These sets of rows on which group function is applied may be the whole table or the
table split into groups by the use of GROUP by clause. Types of Group Functions
Function Description
Q: Find the sum, average, minimum, maximum value of salaries of employees in the employee
table
Count() function
103 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Count () has got three formats:
Count(*) : This function returns the number of rows in the table that satisfy the criteria of
select statement. It includes duplicate rows and rows with NULL values in any of the column
Example: Count the number of employees in the employee table.
Count(<col name>): This function returns the number of not null values in the specified
column, but includes duplicate values in counting
Example: count the number of grades of employees in the employee table.
Count(DISTINCT <col name>): This function returns the number of unique, not null values
in the specified column.
Example: Count the number of different grades of the employee
NOTE -
104 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
● Group by expression specifies the columns whose values determine the basis for
grouping rows Example
Q. Display the no of employees in each zone.
Q. Display the no of employees in each zone whose salary is greater than 32000
Having clause
● This clause is used to restrict rows resulting after grouping.
● Steps followed in execution of select with group by and having clause- 1. Rows
are grouped according to the columns in the group by clause.
2. Then the group function is applied.
3. Groups matching with Having clauses are displayed.
Example
Q. Display only whose departments with sum of salaries whose total salary is greater than
70000
105 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Cartesian Product (Cross Join or unrestricted join)
Returns a result in which Each row of the first table is paired with all the rows in the second
table which is rarely useful.
Q: To display the cartesian product of the employee names and their department name
Joins in MySQL: A join is used when data from two or more tables is required based on the
common values existing in corresponding columns of two tables.There are many types of joins
such as:
106 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Equi join
● Specified columns from the joining tables are checked for equality.
● Values from joining tables are retrieved only if the condition in where clause is
satisfied.
SYNTAX:-
SELECT <column_name (s)>
FROM <table_name1>, <table_name2>, ...., <table_nameN>
WHERE <table_name1>.<column_name> = <table_name2>.<column_name>;
You should always qualify the common columns when joining tables by using the “.” (dot)
operator.
Natural Join
This clause is based on all the columns in the two tables that have the same name. It selects the
rows from two tables that have equal values in the matched columns. The Resulting table
displays the common columns only once in the result.
SYNTAX:-
SELECT [column_names | *]
FROM table_name1
NATURAL JOIN table_name2;
107 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Q : To display the name of employee and department of all employee
109 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
ANSWERS
1. (b)
2. (b)
3. (a)
4. (b)
5. (a)
6. (b)
7. (a)
8. (b)
9. (b)
10. (a)
110 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
I Interface Python with SQL database
Database connectivity
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
Before we connect the program with mysql , we need to install connectivity package
import mysql.connector
12
or
The connect statement creates a connection to the mysql server and returns a
111 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Syntax:
<Connection object> = mysql.connector.connect (host=<hostname>,user=<username>,
passwd=<password>, database=<database>)
Where,
Example:
import mysql.connector
con=mysql.connector.connect(host=”localhost”,user=”root”, passwd=”manager “ ,
database=”student12”)
Syntax:
<cursor object>=<connectionobject>.cursor()
cursor=con.cursor()
112 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
v) Execute SQL query:
Syntax:
The above code will execute the SQL query and store the retrieved records
Result set refers to a logical set of records that are fetched from the database
The records retrieved from the database using SQL select query has to be
extracted as record from the result set. We can extract data from the result
fetchone()
fetchmany()
❖ fetchall()
Fetches all the rows from the result set in the form of a tuple containing the records.
❖ fetchone()
Fetches only one row from the result set in the form of a tuple containing a record
Syntax:
<data>=<cursor>.fetchall()
<data>=<cursor>.fetchone()
data=cursor.fetchall()
113 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
for row in data:
print(row)
Syntax:
<connectionobject>.close()
con.close()
import mysql.connector
mycon=mysql.connector.connect(host="localhost",user="root",passwd="manager"
114 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
4 Python connectivity program to display the record from a table by using a parameterised
query.
import mysql.connector
mycon=mysql.connector.connect(host="localhost",user="root",passwd="manager",
115 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
5 Python connectivity program to insert a new record to a table by using a parameterised
query.
import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",password="manager",
database="class12") if con.is_connected(): print("successfully connected")
cur=con.cursor() empid=int(input("enter empid:")) ename=input("enter
name:") desg=input("enter designation:")
(empid,ename, desg,sex,salary))
cur.execute(str) con.commit()
print("successfully inserted")
con.close() else:
print("connection problem")
116 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
6 Python connectivity program to update a record of a table by using parameterised query.
(Update salary of employees using employee id)
import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",password="manager",
problem")
117 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
7 Python connectivity program to delete a record from table by using parameterised query.
(Delete employee details by using employee id)
import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",password="manager",database="cl
Questions
1 Write a python connectivity program to display only first three records from a table?
import mysql.connector
mycon=mysql.connector.connect(host="localhost",user="root",passwd="manager",
print(row)
118 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
mycon.close() else:
print("connection problem")
import mysql.connector
mycon=mysql.connector.connect(host="localhost",user="root",passwd="manager",
print("connection problem")
119 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
3 Write a python connectivity program to display the records of all female managers from a
table named employee and also find out the number of female managers. If the details are
not existing, then print “Record Not Found” message?
import mysql.connector
mycon=mysql.connector.connect(host="localhost",user="root",passwd="manager"
, database="class12") if mycon.is_connected(): cursor=mycon.cursor()
st="select * from employee where desg='Manager' and sex='F'"
cursor.execute(st) data=cursor.fetchall() count=cursor.rowcount if count>0:
found") else:
print("connection problem")
120 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
4 Write a python connectivity program to display the records of all managers from a table
named employee using parameterised query and also findout the number of managers. If
the details are not existing, then print “Record Not Found” message? import
mysql.connector
mycon=mysql.connector.connect(host="localhost",user="root",passwd="manager"
count=cursor.rowcount if count>0:
print("Number of Managers",count)
print("connection problem")
121 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
5 Write a python connectivity program to update salary from a table named employee .Use
parameterised query and count the number of updated record. If the details are not
existing,then print “Record Not Found” message?
import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",password="manager",
print("connection problem")
6 Write a python connectivity program to delete the record from a table named employee
using parameterised query and also count the number of deleted record. If the details are
not existing,then print “Record Not Found” message?
import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",password="manager",database="cl
a ss12") if con.is_connected():
122 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
cur=con.cursor() eid=int(input("enter empid:"))
problem")
123 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
7 Shyam has created a table named Student in MYSQL database, SCHOOL:
124 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
8 Shyam has created a table named ‘Student’ in MYSQL database, ‘SCHOOL’:
con=mysql.connector.connect(host="localhost",user="root",password="manager",
database="school") cur=con.cursor() rno=int(input("Enter the Roll number:"))
name=input("Enter the name") per=float(input("enter the percentage:"))
cur=con.cursor() str=("insert into student(rno,name,per)values({},'{}',
{})").format(rno,name,per) cur.execute(str) con.commit() print("successfully
inserted record:") con.close()
125 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Shyam, now wants to increase the percentage of students by 2% ,who got less than
40 percentage. Help Shyam to write the program in Python. import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",password="manager",
database="school") cur=con.cursor() per=40 cur=con.cursor()
126 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
**********************************************************
Sample Paper - 1
Computer Science (083)
Class : XII Maximum Marks: 70 Time Allowed: 3 hours
General Instructions:
• Please check this question paper contains 35 questions.
• The paper is divided into 4 Sections- A, B, C, D and E.
• Section A, consists of 18 questions (1 to 18). Each question carries 1 Mark.
• Section B, consists of 7 questions (19 to 25). Each question carries 2 Marks.
• Section C, consists of 5 questions (26 to 30). Each question carries 3 Marks.
• Section D, consists of 2 questions (31 to 32). Each question carries 4 Marks.
• Section E, consists of 3 questions (33 to 35). Each question carries 5 Marks.
• All programming questions are to be answered using Python Language only.
SECTION A
127 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
7. Choose the correct option from the following: 1
The tell() function
a) Places the file handle at the position that we specify
b) Sets the file handle at the beginning of the file
c) Returns the byte number of the position of the file handle.
d) Brings the file handle to the end of the file
8. The command used to insert a new column to an already existing table is: 1
a) Update
b) Alter
c) Insert
d) modify
9. Assuming the table emp to exist, what will the following command 1
do? Delete from emp;
a) Will delete the table emp
b) Will delete all the attributes in it
c) Will delete all the tuples in it.
d) Wrong syntax
10. Find the erroneous statement from the following: 1
Str=’Hard Work Is The Key To ess’
Succ print(Str) for I in len(str): # Statement 1
if Str[I]==’ ‘: # Statement 2
Str[I]=’ - ’ # Statement 3
# Statement 4
Str=’Good Luck’
(a) Statement 2 # Statement 5
(b) Statement 4
(c) Statement 5
(d) Statement 2 and 4
128 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
12. Identify the correct option(s) to open the text file in read mode. 1
i) sf =open('student.txt','w') ii) sf = open('student.txt','r')
iii) sf = open('student.txt') iv) sf = open('student.txt','rb')
a) Option i
b) both iii & iv
c) both ii and iii
d) both ii and iv
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct
choice as
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True
17. Assertion (A):- The default delimiter in CSV files is comma(,). 1
Reasoning (R):- The default delimiter of the CSV file can be overridden
129 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
with the help of the ‘delimiter’ attribute.
18. Assertion (A):- If the arguments in a function call statement match the 1
number and order of arguments as defined in the function definition, such
arguments are called positional arguments.
Reasoning (R):- During a function call, the argument list first contains
default argument(s) followed by positional argument(s).
SECTION B
19. (i) Expand the following terms: POP3 , URL 1+1
(ii) Give one difference between Web Server and Web Site.
OR
(i) Write down any one advantage of computer networks
(ii) Define Gateway
20. Roshan tried to define a function to input an integer and print its factors. But he 2
encountered certain syntax and logical errors in his code. Rewrite the corrected
code and underline the corrections made.
def factors():
n=input("Enter the
number") for i in range(
0,n) If
n% i = 0 :
print(i)
21. 1
Write a function countNow(STUDENT) in Python, that takes the dictionary,
STUDENT as an argument and displays the names (in uppercase) having 4
characters.
For example, Consider the following dictionary
STUDENT={1:"ARUN",2:"AVINASH",3:"PRIYA",4:"NIHA",5:"JEWEL"}
The output should be:
ARUN
NIHA
OR
Write a function, JUMBLE(STRING), that takes a string as an argument and
returns another string where uppercase letter is converted to lowercase and vice
versa.
For example, if the string is "HeLlO", then the output will be :hElLo
22. Predict the output of the Python code given below: 2
D = ["P",20,"R",10,"S",30]
T=0
A = "" B = 0 for C in
range(1,6,2):
T= T + C
A= A + D[C-1]+"$"
B = B + D[C]
130 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
23 Write the Python statement for each of the following tasks using BUILT-IN 1+1
functions/methods only:
(i) To delete last element in the list L1.
(ii) To find the length of a string named message
OR
A list named MARK stores marks obtained by a student in 5 subjects. Write the
Python command to import the required module and (using built-in function) to
display the average mark of the student.
24. Ms. Shalu has just created a table named “Staff” containing Columns Sname, 2
Department and Salary.
After creating the table, she realized that she has forgotten to add a primary key
in the table. Help her in writing an SQL command to add a primary key -
StaffId of integer type to the table Staff.
Thereafter, write the command to insert the following record in the table:
StaffId - 111
Sname- Shalu
Department: Marketing
Salary: 45000
OR
Kiran is working in a database named SCHOOL, in which he has created a table
named “STUDENT” containing columns UID, SName, Gender and Category.
After creating the table, he realized that the attribute, Category has to be deleted
from the table and a new attribute Stream of data type string has to be added.
This attribute Stream cannot be left blank. Help him to write the commands to
complete both the tasks.
25. Predict the output : 2
R =380
S= 120
R=Find(R, S)
print(R,"*",S)
S=Find(S)
print(R,"*",S)
print (T,B,sep='#')
print(A)
SECTION C
26. 3
Predict the Output :
131 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Text1="ChandraYAAN-3"
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]) elif
Text1[I]>="a" and Text1[I] <="z":
Text2=Text2 + Text1[I].upper() else:
Text2=Text2 + "*"
I=I+1
print (Text2)
27 Consider the given table Employee and answer the following questions
132 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
OR
Write a function AMCount() to display the no.of occurrences of
‘A’ and ‘M’ ( ‘a’ and ‘m' also)separately of a text file
STORY.TXT.
29. Consider the table EMPLOYEES shown below and write SQL 3
commands for (i) to (iii)
SECTION D
Consider the following tables DOCTOR and SALARY. Write SQL commands 4
31 for the following statements.
TABLE : DOCTOR
109 K MEDICINE F 4
GEORGY
105 JOHNSON ORTHOPEDI M 7
C
117 LUCY ENT F 8
133 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
111 BILL G MEDICINE F 15
134 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Approximate distance between these units is as follows:
WIN NO.COMPUTERS
G
PRODUCTION UNIT 15
0
FINANCE UNIT 35
MEDIA UNIT 10
CORPORATE UNIT 30
Suggest the kind of network required (out of LAN, MAN, WAN) for each of
the following units:
(a) Production Unit and Media Unit
(b) Production Unit and Finance Unit
(ii) Name the device you suggest for connecting all computers within each
unit?
(iii) Which of the following communication media, will you suggest to be
procured by the company for connecting their local office units in Chennai
for very effective (high speed) communication?
(a) Telephone cable
(b) Optical fiber
(c) Ethernet cable
(iv) Among the different units in Chennai, which unit can be made the
Server. Justify your reason.
(v) Suggest a cable/wiring layout for connecting the company’s local
office units located in Chennai.
135 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
34 i)Differentiate between binary file and csv file: 2+3
ii)Raghav is a Python programmer , created a binary file record.dat with
employee id, ename and salary. The file contains 10 records. He now has to
update a record based on the employee id entered by the user and update the
salary. The updated record is then to be written in the file temp.dat. The
records which are not to be updated also have to be written to the file
temp.dat. If the employee id is not found, an appropriate message should to
be displayed.
OR
i)Differentiate between seek( ) and tell( ) functions
ii)Anushka wants to increase the price by 10% for those items which are less
than 250. The details of the items (itemno, iname and price) are stored in a
file named ‘items.dat’. She wants to store the modified data in another file
named
items_copy.dat. Anushka has written a function named Price_Change() . Help
Anushka to accomplish the task
136 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
35 Define the term Domain with respect to RDBMS. Give one example to
support your answer.
Sunil wants to write a program in Python to read a record from the table
named student and displays only those records who have marks between 80
and 95: RollNo – integer
Name – string
Clas – integer
Marks – integer
Note the following to establish connectivity between Python and MYSQL:
∙ Username is root
∙ Password is tiger
The table exists in a MYSQL database named vidyalaya.
OR
i)Define Candidate Key ii)Write a program to insert 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 abcd
The table exists in a MYSQL database named XIICS.
The details (RollNo, Name, Class and Marks) are to be accepted from the
user.
Class : XII
SECTION A
1. State True or False 1
Python supports dynamic typing
Ans: True
2. Identify the odd one from this list: 1
a)Tuple b) Dictionary c) List d)
String
137 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
3. Choose the correct option. 1
d = { “Naturals”:100 , “Amul” : 200, “BR”: 300 , “Amul” : 500 }
print(sorted(d))
a) { “Naturals”:100 , “Amul” : 200, “BR”: 300 , “Amul” : 500 }
b) [“Amul”, “Amul”, “BR”, “Naturals”]
c) [“Amul”, “BR”, “Naturals”]
d) {“Amul”:500, “BR”:300, “Naturals”:100}
138 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
10. Find the erroneous statement from the 1
following:
139 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
d) 1
16. Which of the following is an optional argument 1
of the connect() function in python
mysql.connector module?
a) Host
b) User
c) Password
d) database
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct
choice as
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True
17. Assertion (A):- The default delimiter in CSV files is comma(,). 1
Reasoning (R):- The default delimiter of the CSV file can be overridden
Ans with the help of the ‘sep’ attribute.
(a) Both A and R are true and R is the correct explanation for A
18. Assertion (A):- If the arguments in a function call statement match the 1
number and order of arguments as defined in the function definition, such
arguments are called positional arguments.
Reasoning (R):- During a function call, the argument list first contains
Ans default argument(s) followed by positional argument(s).
(c) A is True but R is False
SECTION B
19. (i) Expand the following terms: HTTP , URL 1+1
HTTP – Hyper Text Transfer Protocol
URL – Uniform Resource Locator
(ii) A web server is a computer system that stores and delivers web pages
to users when they request them.
A website is a collection of web pages, images, videos, and other digital assets
that are hosted on a web server.
Or
i)Write down any one advantage of computer networks
File Sharing / Resource Sharing
ii)Define Gateway
A gateway is a device which connects dissimilar networks
140 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
20 Roshan tried to define a function to input an integer and print its factors. But 2
he encountered certain syntax and logical errors in his code. Rewrite the
corrected code and underline the corrections made.
def factors():
n=input("Enter the
number") for i in range(
0,n)
If n% i = 0
: print(i)
Ans:
def factors():
n=int(input("Enter the
number")) for i in range( 1,n+1):
if n% i = = 0
: print(i)
21 def countNow(STUDENT) : for
name in STUDENT.values():
if len(name)= =4:
print(name)
STUDENT={1:"ARUN",2:"AVINASH",3:"PRIYA",4:"NIHA",5:"JEW
EL"} countNow(STUDENT)
or def
Jumble(str):
n=len(str) str2=""
for i in range(0,n):
if str[i].isupper():
str2=str2+str[i].lower()
elif str[i].islower():
str2=str2+str[i].upper()
else: str2=str2+str[i]
return str2
22 9#60 2
P$R$S$
( 1 mark for each correct line with the appropriate symbol)
141 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
24 ALTER TABLE Staff ADD StaffId INT PRIMARY KEY; 2
INSERT INTO Staff VALUES("Shalu","Marketing",45000,111); Or
To delete the attribute, category:
ALTER TABLE STUDENT DROP category;
To add the attribute, Stream
ALTER TABLE Sports ADD stream varchar(10) NOT
NULL ;
25 500 @ 380 2
500 * 120
140 @ 120
500 * 140
26 hHANDRAAAN-*4 3
27 3
(i) select EmpName, Designation from Employee where EmpName
like '_
_ _';
EmpName Designation
Sam Systems Engineer
Mia Lead Consultant
Sen Manager
distinct Designation
Systems Engineer
Technical Lead
Lead Consultant
Manager
print(i,end=' ')
f.close()
or def
CountAM():
with open("Story.txt") as f:
A=M=0
s=f.read()
for ch in
s:
if ch in "Aa":
A+=1 elif ch
in "Mm":
M+=1
f.close()
print("No.of A and M is", A ," & ", M)
31 4
(i) SELECT NAME FROM DOCTOR WHERE
DEPT=”ORTHOPEDIC” AND EXPERIENCE>10;
(ii) SELECT AVG(BASIC + ALLOWANCE) FROM DOCTOR,
SALARY WHERE DOCTOR.ID=SALARY.ID AND
DEPT=”ENT”;
(iii) SELECT MIN(ALLOWANCE) FROM DOCTOR, SALARY
143 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
WHERE DOCTOR.ID=SALARY.ID AND SEX=”F”;
(iv) SELECT MAX(CONSULTATION) FROM DOCTOR,
SALARY WHERE DOCTOR.ID=SALARY.ID AND SEX=”M”;
def search():
fin=open("furdata.csv","r",newline='\n')
data=csv.reader(fin) found=False
print("The Details are") for i in data:
if int(i[2])>10000:
found=True
print(i[0],i[1],i[2]) if
found==False:
print("Record not found")
fin.close()
add()
print("Now displaying")
search()
33 i) a) MAN
b) LAN
ii) Switch/hub iii) Optical Fibre iv) Production Unit- It
contains the maximum no.of computers Star Topology
34 a)Ans : 2+3
Binary file:
• Extension is .dat
• Not human readable
• Stores data in the form of 0s and 1s
CSV file
∙ Extension is .csv
∙ Human readable
∙ Stores data like a text file Program
b)def update_data():
rec={}
fin=open("record.dat","rb")
144 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
fout=open("temp.dat",”wb”)
found=False eid=int(input("Enter employee id to update
their salary :: ")) while True: try:
rec= pickle.load(fin)
if rec["Employee id"]==eid:
found=True
rec["Salary"]=int(input("Enter new salary :: "))
pickle. dump(rec,fout)
else: pickle.dump(rec,fout)
except: break if found==True: print("The
salary of employee id ",eid," has been updated.") else:
print("No employee with such id is not
found") fin.close() fout.close() or
i)Differentiate between seek( ) and tell( ) functions
Ans : The tell function is used to determine the current position of the file
pointer, and the seek function is used to move the file pointer to the specified
position of the file
ii)Anushka wants to increase the price by 10% for those items which
are less than 250. The details of the items (itemno, iname and price) are stored
in a file named ‘items.dat’. She wants to store the modified data in another file
named items_copy.dat. Anushka has written a function named Price_Change()
. Help Anushka to accomplish the task
145 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
35 i)In relational database terminology, a domain defines the permitted range
of values for an attribute of an entity
ii) import mysql.connector as mysql def sql_data():
con=mysql.connect(host="localhost",user="root",password="tiger",
database="vidyalaya") mycursor= con.cursor()
print("Students with marks between 80 and 95 are : ")
mycursor.execute("select * from vidyalaya where Marks between 80 and
95")
data=
mycursor.fetchall() for i
in data: print(i) or
con1=mysql.connect(host="localhost",user="root", passwd="abcd",
database="XIICS")
mycursor= con1.cursor()
rno=int(input("Enter Roll Number :: "))
name=input("Enter name :: ")
class=int(input("Enter class :: "))
marks=int(input("Enter Marks :: "))
s="insert into student values ({},'{}',{},
{})".format(rno,name,class,marks) mycursor.execute(s) con1.commit()
print("Data Added successfully")
146 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
147 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
KENDRIYA VIDYALAYA SANGATHAN: ERNAKULAM REGION
SAMPLE QUESTION PAPER - 2
COMPUTER SCIENCE (083)
Maximum Marks: 70 Time Allowed: 3 hours
General Instructions:
1. This question paper contains five sections, Section A to E.
3. Section A have 18 questions carrying 01 mark each.
4. Section B has 07 Very Short Answer type questions carrying 02 marks each.
5. Section C has 05 Short Answer type questions carrying 03 marks each.
6. Section D has 02 Long Answer type questions carrying 04 marks each.
7. Section E has 03 questions carrying 05 marks each.
8. All programming questions are to be answered using Python Language only.
SECTION A
1. State True or False 1
A variable in python is defined only when some value is assigned to it.
2. …………………..command is used to remove primary key from the table in SQL.
a) delete b)remove c) alter d)drop
3. What will the following expression be evaluated to in Python? 1
print(25 // 4 + 3**1**2 * 2)
a) 24 b) 18 c) 6 d) 12
4. What will be the output of the following Python 1
code? string = "my name is x" for i in string.split():
print (i, end=", ")
a)m, y, , n, a, m, e, , i, s, , x, b)m, y , n, a, m, e , i, s , x,
c)my, name, is, x, d)error
5. Suppose a dictionary D is declared as D={1:"John",2:"Dev",3:"Bob"} 1
which of the following is incorrect? State the reason.
(a) print(D[3]) (b) D[[1,2,3]] = “Python”
(c) D[‘Bob’]=3 (d) print(D[3][1])
6. Observe the following table: 1
148 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
a)FTP b)SMTP c)VOIP d)HTTP
8. Consider the statements given below and then choose the correct output from the 1
given options:
example="snow world" print(example[-2:1:-3])
a)lo b)lwn c)lwo d)lwn
import random
val=[20,30,40,50,60,70]; Low
=random.randint(2,4) High
=random.randint(3,5) for i in
range(Low, High +1): print
(val[i],end="#")
149 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
16 f = open("test.txt", "w+") 1
. L = ["First Line\n", "Second Line\n", "Third Line"]
f.writelines(L)
f.flush()
f.seek(0)
O = f.readlines()
print(len(O))
a) 33 b) 31 c) 28 d) 3
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct choice as
(a) Both A and R are true and R is the correct explanation for A.
(b) Both A and R are true and R is not the correct explanation for A.
(c) A is True but R is False.
(d) A is false but R is True
17 Assertion(A): The pop() method can be used to delete elements from a dictionary. 1
. Reason(R): The pop() method deletes the key-value pair and returns the value of deleted
element
18 Assertion (A): Leading whitespace at the beginning of a statement in Python is called 1
. indentation.
Reason (R): In Python, the same level of indentation associates statements into a different
blocks of code.
SECTION B
19 (i) Expand the following terms: 1+1
. (a)NIC (b)SIM (2)
(ii)What is HTML? Where it is used?
OR
(i) Define the term bandwidth. Give any one unit of bandwidth.
(ii) Give one difference between FTP and HTTP.
20 Observe the following code carefully and rewrite it after rmoving all syntax and logical 2
. errors. Underline each correction done in the code.
def execmain():
x = input("Enter a number:")
if (abs(x)=x):
print ("You entered a positive number")
else:
x=*-1
print("Number made positive:"x)
execmain()
150 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
21 Write a function frequencyCount( ), which takes the list ( Marks) and empty dictionary 2
. (dict) as arguments. Update the dictionary, each marks as key and frequency of its
occurrence as value and return the dictionary .
Consider the following list Marks=[4,5,6,5,10,6,5,5,40,30,2,4] and dict
The function will return {4: 2, 5: 4, 6: 2, 10: 1, 40: 1, 30: 1, 2: 1}
OR
Write a function LeftShift(lst,x) in python which accepts number in a list (lst) and all the
elements of the list should be shifted to left according to the value of x entered by the
user.
Sample list lst=[20,40,60,30,10,50,90,80,45,29] value of x is 3
Then lst will be [30,10,50,90,80,45,29 20,40,60]
22 Predict the output of the following Python code: 2
. 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)
23 Write the python statement for each of the following tasks using BUILT-IN 2
. functions/methods only
Consider the list L=[15,25,35,45,65,75,85]
L=[32,10,21,54,43]
151 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
for c in range (4,0,-1):
a=L[c] b=L[c-
1]
print(Bigger(a,b),'@', end=' ')
SECTION C
EmpI Gende
Name DoJ City Salary
d r
Londo
101 Leonard 1995-06-06 M 9500
n
102 Priya 1993-05-07 F Delhi 4500
103 Howard 1994-05-06 M Paris 8500
Londo
104 Penny 1995-08-08 F 11000
n
Londo
105 Raj 1995-10-08 M 10000
n
152 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
28 Write a function countline() in python to count the number lines in a text 3
. file ‘Country.txt’, which is starting with an alphabet ‘W’ or ‘H’. If the file
contents are as follows:
153 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
The dictionary should be as follows: d={“Ramesh”:58, “Umesh”:78,
“Vishal”:90, “Khushi”:60, “Ishika”:95} Then the output will be:
Umesh Vishal Ishika
SECTION D
31 a) Consider the table VEHICLE and TRAVEL given below: 4
. Table: TRAVEL
CNO CNAME TRAVELDATE KM VCODE NOP
Table: VEHICLE
VCODE VEHICLETYPE PERKM
V01 VOLVO BUS 150
V02 AC DELUXE BUS 125
V03 ORDINARY BUS 80
V04 CAR 18
V05 SUV 30
154 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
SECTION E
33 Oasis Public School, Coimbatore is setting up the network between its different wings of 5
. school campus. There are 4 wings namely SENIOR(S), JUNIOR (J), ADMIN (A) and
HOSTEL (H).
155 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
34 i)What is the difference between “w” and “a” modes in python? 2+3
. ii) Consider a file, University.dat, containing records of the following structure: (5)
[Universityname ,collegename, noofstaff]
Write a function CopyCollege(), that reads contents from the file University.dat and copies
the records with University name as Calicut to the file name Calicut.DAT. The function
should return the total number of records copied to the file Calicut.DAT.
OR
i)What is the difference between readline() and readlines() functions? ii)Write a menu
driven program InsertRec() and Searchroll() for adding and searching for a particular roll
number using dictionary on student binary file “student.DAT”. Structure of dictionary is
{Rollno:rollno,”Name”:name,”Marks”:marks}
35 i) Define the term Domain with respect to RDBMS. Give one example to support your 5
. answer
ii) Swaraj wants to write a program in Python to insert the following record in the table
named ‘Employee’ in MYSQL database, COMPANY:
• EID(Employee ID )- integer
• name(Name) - string
• DOB (Date of birth) – Date
• Salary – float
Note the following to establish connectivity between Python and MySQL:
• Username - root
• Password - tiger
• Host - localhost
The values of fields EID, name, DOB and Salary has to be accepted from the user. Help
Swaraj to write the program in Python.
OR
i)what is the difference between primary key and foreign key?
ii) Nayana has created a table named ‘Employee’ in MYSQL database, COMPANY:
• EID(Employee ID )- integer
• name(Name) - string
• DOB (Date of birth) – Date
• Salary – float
Note the following to establish connectivity between Python and MySQL:
• Username - root
• Password - tiger
• Host - localhost
Nayana , now wants to display the records of employees whose salary is more than 25000.
Help Nayana to write the program in python
156 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
157 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS