100% found this document useful (1 vote)
638 views150 pages

Student Support Material Class Xii - Cs

Uploaded by

Avi A
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
638 views150 pages

Student Support Material Class Xii - Cs

Uploaded by

Avi A
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 150

KENDRIYA VIDYALAYA SANGATHAN

AHEDABAD CLUSTER

STUDENT SUPPORT MATERIAL


CLASS XII

SUBJECT - COMPUTER SCIENCE (083)


SESSION - 2020-21
STUDENT SUPPORT MATERIAL FOR CLASS XII
(COMPUTER SCIENCE)

CONTRIBUTORS

1. Sh. Ashvin Modi (PGT, CS) KV No.1, Shahibaug, A’bad


2. Mrs. Manisha Tripathi (PGT, CS), KV Cantt., A’bad
3. Mrs. Sonia Nehra (PGT, CS), KV Cantt., A’bad
4. Sh. Jitendra Vartiya (PGT, CS), KV ONGC, A’bad
5. Dr. Parminder Mangal (PGT, CS) KV Wadsar, A’bad
6. Sh. Mohammad Raheesh Khan (PGT-CS, KV Dhrangadhra)
7. Mrs. Raksha Parmar (PGT,CS) KV Sabarmati, A’bad
8. Sh. Gaurav Chavda (PGT, CS) KV Viramgam, A’bad

COMPILED BY
Renu Baheti (PGT,CS), KV SAC, Vastrapur, A’bad
Salient features of this Study Material
 This study material is in the form of Question Bank comprising of solved
questions from each chapter of the syllabus.
 It is a collection of a number of challenging questions based on Minimum
Learning Skill of the students.
 It aims at providing help to very high scorer students who may miss 100 out of
100 because of not being exposed to new type of questions, being used to only
conventional types of questions and not paying attention towards the topics
which are given in the reference books and syllabus of Computer Science as per
CBSE guidelines.
 It contains guidelines, hints and solutions for really challenging questions and
topics.
 It contains a number of fresh/new questions (solved), which shall increase the
confidence level of the students when they will solve them as per CBSE
guidelines.
 Such kind of questions shall draw the attention of both the students and the
teachers, and will help all of us in achieving the aim of 100% result with healthy
PI.

“Things work out best for those who make the best of how things work out.”

ALL THE BEST TO OUR DEAR STUDENTS…..


Note : This blue print is designed on the basis of Sample Question Paper provided by
CBSE in Sept. 2020.
INDEX
S. UNIT TOPIC/CHAPTER Page No.
No.
1. I – Programming & Python Revision Tour – I & II 1 to 16
Computational
Thinking-2 Working with Functions 17 to 24
(Weightage – 40 Using Python Libraries
Marks) File Handling 25 to 70
Data Structures – I : Linear 71 to 74
Lists
Data Structures – II : Stacks
2. II – Computer Computer Networks I & II 75 to 90
Networks (Weightage
– 10 Marks)

3. III – Data MySQL SQL Revision Tour 91 to 94


Management-2 More on SQL
(Weightage – 20
Marks) Interface Python with MySQL 95 to 99

5. Sample Papers (with Complete Syllabus 2020-21 100 to 145


solution based on
CBSE Sample Paper)
Page : 1

REVIEW OF PYTHON BASICS

SN QUESTIONS/ANSWERS MARKS
ALLOTE
D
Q1 What is None literal in Python? 1
Ans Python has one special literal called “None”. It is used to indicate something
that has not yet been created. It is a legal empty value in Python.
Q2 Can List be used as keys of a dictionary? 1
Ans No, List can’t be used as keys of dictionary because they are mutable. And a
python dictionary can have only keys of immutable types
Q3 Name the Python Library modules which need to be imported to invoke the 1
following functions:
(i) floor()
(ii) randn()

Ans (i) math


(ii) random
Q4 What type of objects can be used as keys in dictionaries? 1
Ans Only immutable type objects (i.e. Numbers, Strings, Tuples) can be used as
keys in dictionaries.
Q5 What are two ways to remove something from a list? Write syntax only for 1
both.
Ans • pop() method to remove single element using index
• remove() method to remove single element using value
Q6 Identify and write the name of the module to which the following functions 1
belong:
(i) ceil() (ii) dump()
Ans (i) ceil() – math module (ii) dump() – json module or pickle
Q7 Write the type of tokens from the following: 1
(i) if (ii) roll_no
Ans (i) Key word (ii) Identifier
Q8 Which of the following is a valid arithmetic operator in Python: 1
(i) // (ii) ? (iii) < (iv) and
Ans (i) //
Q9 Which command is used to convert text into integer value? 1
Ans int()
Q10 Which is the correct form of declaration of dictionary? 1
(i) Day={1:'monday',2:'tuesday',3:'wednesday'}
(ii) Day=(1;'monday',2;'tuesday',3;'wednesday')
(iii) Day=[1:'monday',2:'tuesday',3:'wednesday']
(iv) Day={1'monday',2'tuesday',3'wednesday']
Ans (i) Day={1:'monday',2:'tuesday',3:'wednesday'}
Q11 Identify the valid declaration of L: 1
L = [1, 23, 'hi', 6]
(i) List, (ii) Dictionary, (iii) Array, (iv) Tuple
Page : 2
Ans (i) List

Q12 What is a python variable? Identify the variables that are invalid and state the 2
reason Class, do, while, 4d, a+
Ans
- A variable in python is a container to store data values.
a) do, while are invalid because they are python keyword
b) 4d is invalid because the name can’t be started with a digit.
c) a+ is also not validas no special symbol can be used in name except
underscore ( _ ).
Q13 Predict the output 2
for i in range( 1, 10, 3):
print(i)
Ans 1
4
7

Q14 Rewrite the code after correcting errors: - 2


if N=>0
print(odd)
else
Print("even")
Ans if N>=0:
print(“odd”)
else:
print("even")
Q15 What problem occurs with the following code 2
X=40
while X< 50 :
print(X)

Ans The given code does not have


the incrementing value of X,
thus the loop becomes endless.
Q16 What will be the output of the following code snippet? 2
values =[ ]
for i in range (1,4):
values.append(i)
print(values)
Ans [1]
[1,2]
[1,2,3]
Q17 Find the error in following code. State the reason of the error. 2
aLst = { ‘a’:1 ,' b':2, ‘c’:3 }
print (aLst[‘a’,’b’])
Ans The above code will produce Ke yError, the reason being that there is
no ke y same as the list [‘a’,’b’] in dictionary aLst.
Q18 Find output of the following code fragment. 2
Page : 3
x=”hello world”
print(x[:2],x[:-2],x[-2:])
print(x[6],x[2:4])
print(x[2:-3],x[-4:-2])
Ans he hello wor ld
w ll
llo wo or
Q19 Rewrite the following programs after removing syntactical errors: 2
for=20
for1=50:
for3=for+for1+for2
print(for3)
Ans f=20 #( as for is a keyword in python)
for1 = 50 #(: can not be used here)
for3 = f+for1 #(for2 not defined)
print(for3)
Q20 Observe the following Python code very carefully and rewrite it after 2
emoving all syntactical errors with each correction underlined.
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()
Ans 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()
Q21 Find the output of the following: 2
L1 = [100,900,300,400,500]
START = 1
SUM=0
for C in range(START,4):
SUM = SUM + L1[C]
print(C, ":", SUM)
SUM = SUM + L1[0]*10
print(SUM
Ans 1 : 900
1900
2 : 2200
3200
3 : 3600
4600
Page : 4

Q22 Write the output of the following Python program code:

A = [10,12,15,17,20,30]
for i in range(0,6):
if (A[i] % 2 == 0):
A[i] /= 2
elif (A[i] % 3 == 0):
A[i] /= 3
elif (A[i] % 5 == 0):
A[i] /= 5
for i in range(0,6):
print(A[i],end= "#")

Ans Output is:


5.0#6.0#5.0#17#10.0#15.0#
Q23 What are the possible outcomes executed from the following code?
Also, specify the maximum and minimum values that can be assigned
to variable COUNT
. (2)
import random
TEXT = "CBSEONLINE"
COUNT = random.randint(0,3)
C=9
while TEXT[C] != 'L':
print(TEXT[C]+TEXT[COUNT]+'*',end=" ")
COUNT= COUNT + 1
C=C-1

1 EC* NB* IS*


2 NS* IE* LO*
3 ES* NE* IO*
4 LE* NO* ON*
Ans The possible outcomes are: 1 and 3
Minimum value of count is 0
Maximum value of count is 3
Page : 5

WITH SOLUTION
PYTHON – REVISION TOUR

1 „Welcome‟ is literals
Ans. string
2 $ symbol can be used in naming an identifier (True/False)
Ans. False
3 Write any 2 data types available in Python
Ans. int, bool
4 „Division by zero‟ is an example of error.
Ans. Runtime Error
5 range(1,10) will return values in the range of to
Ans. 1 to 9
6 randint(1,10) will return values in the range of to
Ans. 1 to 10
“Computer Science”[0:6] =
“Computer Science”[3:10] =
“Computer Science”[::-1] =
7 “Computer Science”[-8:]=
“Computer Science”[0:6] = Comput
“Computer Science”[3:10] = puter S
“Computer Science”[::-1] = ecneicS retupmoC
Ans. “Computer Science”[-8:] = Science
8 Output of : print(“Ok”*4 + “Done”)
Ans. OkOkOkOkDone
9 Output of : print(print(“Why?”))
Why?
Ans. None
Raj was working on application where he wanted to divide the two
number (A and B) , he has written the expression as C = A/B, on
execution he entered 30 and 7 and expected answer was 4 i.e. only
integer part not in decimal, but the answer was 4.285 approx, help
Raj to correct his expression and achieving the desired output.
10 Correct Expression :

Ans. C = A//B
Page : 6
Can you guess the output?
C = -11%4
11 print(C)
Ans. 1
12 Write 2 advantages and disadvantages of Python programming language
Advantages
1) Easy to Use
2) Expressive Language
Ans.
Disadvantages
Identify
1) Slowthe validof
because and Invalid identifiers names:
interpreted
13 Emp-Code, _bonus, While, SrNo. , for, #count, Emp1, 123Go, Bond007
2) Not strong on type binding
Valid: _bonus, While, Emp1,Bond007
Ans. Invalid : Emp-code, SrNo., for,#count,123Go

Identify the type of literals for each:


(i) 123
(ii) „Hello‟
(iii) „Bye\nSee You‟
14 (iv) „A‟
(i) Int
(v) 345.55
(ii) String
(vi) 10+4j
(iii)
(vii) String
0x12
(iv) String
(v) Float
(vi) Complex
Ans.
(vii) Int
What is the size of each string?
(i) „Python‟
15
(ii) „Learning@\nCS‟
(i) 6
(iii) „\table‟
(ii) 12
Ans. (iii) 5
Output of :
(i) True + True =
(ii) 100 + False =
16 (iii) -1 + True =
(iv) bool(-1
(i) 2 + True) =
(ii) 100
(iii) 0
Ans. (iv) False
Page : 7
Output of
(i) 2 * 7 =
(ii) 2 ** 7 =
(iii) 2**2**3 =
(iv) 17 % 20 =
17
(v) not(20>6) or (19>7) and (20==20) =
(i) 14
(ii) 128
(iii) 256
Ans. (iv) 17
(v) True
Output of :
a,b,c = 20,40,60
b+=10
18
c+=b
Ans. 20 50 110
print(a,b,c)
19 Write a program to enter 2 number and find sum and product
n1 = int(input('Enter num1 '))
n2 = int(input('Enter num2 '))
s = n1 + n2
p = n1 * n2
Ans.
print('Sum=',s)
Write a program to enter temperature in Fahrenheit and convert it
20 print('Product
in Celsius =',p)
f = int(input('Enter temperature (Fahrenheit) '))
Ans. c = (f-32)*5/9
Write a program
print('Celcus =',c)to enter any money and find out number of
denominations can be used to make that money. For e.g. if the money
entered is 2560
Then output should be
500 = 1
2000==01
200
100 =0
50 =1
20 = 0
10 = 1
5 = 0
2 = 0
21 1 = 0
Hint : use % and // operator (Without Loop / Recursion)
amount = int(input('Enter Amount '))
n2000 = amount//2000
amount = amount % 2000
Page : 8
n500 = amount//500
amount = amount % 500
n200 = amount//200
amount = amount %200
n100 = amount//100
amount = amount %100
n50 = amount//50
amount = amount %50
n20 = amount//20
amount = amount %20
Ans. n10 = amount // 10
amount = amount %10
n5 = amount // 5
n1 = amount//1
amount = amount % 5
amount = amount % 1
n2 = amount//2
amount = amount % 2

print('2000=',n2000)
print('500=',n500)
print('200=',n200)
print('100=',n100)
print('50=',n50)
print('20=',n20)
print('10=',n10)
print('5=',n5)
print('2=',n2)
Consider a list:
print('1=',n1)
MyFamily = [“Father”,”Mother”,”Brother”,”Sister”,”Jacky”]

a) write statement to print “Brother”


b) write statement to print all items of list in reverse order
22
c) write statement to check “Sister” is in MyFamily or not
d) write statement to update “Jacky” with “Tiger”
e) write statement remove “Jacky” from MyFamily and also print it
f) write statement to add “Tommy” in MyFamily at the end

a) print(MyFamily[2])
b) print(MyFamily[::-1])
Page : 9
c) 'Sister' in MyFamily
d) MyFamily[len(MyFamily)-1]='Tiger' OR
MyFamily[4]=‟Tiger‟
Ans.
e) MyFamily.pop()
f) MyFamily.append(„Tommy‟)
Consider a Tuple:
Record = (10,20,30,40)
Raj wants to add new item 50 to tuple, and he has written
expression as
23
Record = Record + 50, but the statement is giving an error, Help
Raj in writing correct expression.
Ans. Record
Correct=Expression
Record + (50,)
:
24 What is the difference between List and Tuple?
Ans. List is mutable type whereas Tuple is Immutable.
25 What is the difference between List and String?
List is mutable type whereas String is immutable. List can store
elements of any type like-string, list, tuple, etc. whereas String
Ans.
can store element of character type only.
26 What is ordered and unordered collection? Give example of each
Ordered collection stores every elements at index position starts
from zero like List, Tuples, string whereas unordered collection
stores elements by assigning key to each value not by index like
Ans.
dictionary
Consider a Dictionary
27
Employee = {„Empno‟:1,‟Name‟:‟Snehil‟,‟Salary‟:80000}
Write statements:
(i) to print employee name
(ii) to update the salary from 80000 to 90000
(i) print(Employee['Name'])
(iii)
(ii) to get all the values only from the dictionary
Employee['Salary']=90000
Ans.
(iii) print(Employee.values())
Num = 100
Isok = False
print(type(Num)) =
print(type(Isok)) =
28
<class 'int'>
Ans.
<class 'bool'>
Page : 10
Name the Python Library module which need to be imported to invoke
the following function:
a) floor()
29
b) randrange()
a) math
c) randint()
b) random
d) sin()
Ans. c) random
Rewrite the following code in python after removing all syntax
d) math
error(s). Underline each correction done in the code.
30=To
for K in range(0,To)
30 IF k%4==0:
To=30 print (K*4)
Else:
for K in range(0,To):
print (K+3)
if K%4==0:
Ans. print(K*4)
Rewrite the following code in python after removing all syntax
else:
error(s). Underline each correction done in the code:
print(K+3)
a=5
work=true
b=hello
c=a+b
FOR i in range(10)
if i%7=0:
31
continue
a=5
Ans. work=True
c = a + b
b='hello'
for i in range(10):
if i%7==0:
Rewrite the following code in python after removing all syntax
continue
error(s). Underline each correction done in the code:

32 for Name in [Ramesh,Suraj,Priya]


IF Name[0]='S':
print(Name)
Page : 11
for Name in [„Ramesh‟,‟Suraj‟,‟Priya‟]:
Ans. if Name[0]=='S':
Rewrite the following code in python after removing all syntax
print(Name)
error(s). Underline each correction done in the code:
a=b=10
c=a+b
33 While c=<20:
print(c,END="*")
c+=10
a=b=10
c=a+b
while c<=20:
Ans.
print(c,end="*")
Choose the correct possible answer(s)
c+=10
a = random.randint(1,5)
b = random.randint(1,3)
c = random.randint(2,6)
34 print(a,b,c)
(i) 2 1 3 (ii) 4 4 4 (iii) 3 2 1 (iv) 5 3 5
Ans. (i) (iv)
What is type conversion in Python? What are different types of
35 conversion? Illustrate with example.
Type conversion refers to conversion of one data type to another
data type for e.g. string is converted to int. There are 2 types of
conversion:
1) Implicit: in this of conversion, it is automatically done by
the interpreter without user intervention.
Example:
Num = [10,20,30]
print(type(Num[1])) # int
Num[1] = Num[1] + 4.5 # it will automatically convert to float
Ans. Print(type(Num[1])) # float

2) Explicit: in this type of conversion, user will convert any type of


value to its desired type. For example string to int.
Example:
Fill in
num the blanks to execute
= int(input(„Enter infinite
number „)) loop:
36 while#in the above
: code input of string type will be converted explicitly
while in int.
True:
print(“spinning”)
Ans. print(“spinning”)
Page : 12
Write a program to enter any number and check it is divisible by 7
37 or not
num = int(input('Enter any number '))
if num % 7 == 0:
print('Divisible by 7')
Ans.
else:
print('Not divisible by 7')
Fill in the blanks to execute loop from 10 to 100 and 10 to 1
(i)
for i in range( ):
print(i)

38
(ii)
for i in range( ):
print(i)

(i)
for i in range(10,101):
print(i)
Ans.
(ii)
for i in range(10,0,-1):
print(i)
What will be the output if entered number (n) is 10 and 11
i=2
while i<n:
if num % i==0:
break
39 print(i)
i=i+1
else:
If n is 10 then when program control enter in loop the if condition
print("done")
will be satisfied and break will execute cause loop to terminate.
The else part of while will also be not executed because loop
terminated by break. (NO OUTPUT)
Ans.
If n is 11 it will print 2 to 10 and then it will execute else part
of while loop and print „done‟ because loop terminate normally
without break
Page : 13
What will be the difference in output
(i)
for i in range(1,10):
if i % 4 == 0:
break
print(i)
(ii)
40 for i in range(1,10):
if i % 4 == 0:
continue
print(i)

(i)
1
2
3
(ii)
1
2
Ans. 3
5
What possible outputs(s) are expected to be displayed on screen at
6
the time of execution of the program from the following code? Also
specify
7 the maximum values that can be assigned to each of the
variables FROM and TO.
9
import random
10
AR=[20,30,40,50,60,70];
FROM=random.randint(1,3)
TO=random.randint(2,4)
41 for K in range(FROM,TO+1):
print (AR[K],end=”#“)
Maximum Value of FROM = 3
(i) 10#40#70#
Ans. Maximum Value of TO =(ii)
4 30#40#50#
(iii) 50#60#70# (iv) 40#50#70#
Output : (ii)
Page : 14
What possible outputs(s) are expected to be displayed on screen at the
time of execution of the program from the following code? Also specify
the minimum and maximum value that can be assigned to the variable
PICKER.
import random

PICKER=random.randint(0,3)
COLORS=["BLUE","PINK","GREEN","RED"] for I
in COLORS:

for J in range(1,PICKER):

print(I,end="")

print()

(i) (ii)
BLUE BLUE
PINK BLUEPINK
42 GREEN BLUEPINKGREEN
RED BLUEPINKGREENRED
(iii) (iv)
PINK BLUEBLUE
PINKGREEN PINKPINK
PINKGREENRED GREENGREEN
REDRED
Minimum Value of PICKER = 0
Ans. Maximum Value of PICKER = 3
43 Output:
What are(i)
theand
correct
(iv) ways to generate numbers from 0 to 20

range(20) (ii) range(0,21) (iii) range(21) (iv) range(0,20)

Ans. (ii) And (iii)


Which is the correct form of declaration of dictionary?
(i) Day={1:‟monday‟,2:‟tuesday‟,3:‟wednesday‟}
(ii) Day=(1;‟monday‟,2;‟tuesday‟,3;‟wednesday‟)
44 (iii) Day=[1:‟monday‟,2:‟tuesday‟,3:‟wednesday‟]
(iv) Day={1‟monday‟,2‟tuesday‟,3‟wednesday‟]
Ans. (i)
Choose the correct declaration from the following code:
Info = ({„roll‟:[1,2,3],‟name‟:[„amit‟,‟sumit‟,‟rohit‟]})
45 List (ii) Dictionary (iii) String (iv) Tuple
Ans. (iv) Tuple
Which is the valid dictionary declaration?
i) d1={1:'January',2='February',3:'March'}
ii) d2=(1:'January',2:'February',3:'March'}
46 iii) d3={1:'January',2:'February',3:'March'}
iv) d4={1:January,2:February,3:March}
Ans. (iii)
Page : 15
What is/are not true about Python‟s Dictionary?
(i) Dictionaries are mutable
(ii) Dictionary items can be accessed by their index position
47
(iii) No two keys of dictionary can be same
(iv) Dictionary
Ans. (ii) and keys must be of String data type
(iv)
x="abAbcAba"
for w in x:
if w=="a":
print("*")
48
else:
* print(w)
b
A
b
c
A
Ans. b
Convert
* the following „for‟ loop using „while‟ loop
49 for k in range (10,20,5):
k = 10print(k)
while k<=20:
Ans. print(k)
Give Output
k+=5
50 colors=["violet", "indigo", "blue", "green", "yellow", "orange", "red"]
colors.remove("blue")
del colors[4]
p=colors.pop(3)
print(p, colors)
Ans. orange ['violet', 'indigo', 'green', 'red']
Output of following code:
A=10
B=15
S=0
while A<=B:
51 S = A + B
A = A + 10
B = B + 10
Ans. 65 if A>=40:

A = A + 100
print(S)
Page : 16
Output of the following code:
X = 17
if X>=17:
X+=10
52
else:
Ans. 27
X-=10
How many times loop will execute:
print(X)

P=5
Q=35
53
while P<=Q:
P+=6
Ans. 6 times
Find and write the output of the following python code:
Msg="CompuTer"
Msg1=''
for i in range(0, len(Msg)):
if Msg[i].isupper():
Msg1=Msg1+Msg[i].lower()
elif i%2==0:
54
Msg1=Msg1+'*'
Ans. cO*P*t*R
else:
A=10 Msg1=Msg1+Msg[i].upper()
B=10
print(Msg1)
print( A == B) = ?
print(id(A) == id(B) = ?
55
True
print(A is B) = ?
True
Ans.
True
Page : 17
FUNCTIONS AND PYTHON LIBRARIES
Very Short Answer Type Questions (1-Mark)
Q1. What is default parameter?
Ans: A parameter having default value in the function header is known as a default parameter.
Q2. Can a function return multiple values in python?
Ans: YES.
Q.3 What will the following function return?
def addEm(x, y, z):
print(x + y + z)
Ans: None object will be returned, (no return statement).
Q.4 What does the rmdir() method do?
Ans: The rmdir() method deletes an empty directory, which is passed as an argument in the
method. Before removing a directory, all the contents in it should be deleted, i.e. directory should
be empty. OSError will be raised if the specified path is not an empty directory.
Q.5 How can we find the names that are defined inside the current module?
Ans: The names defined inside a current module can be found by using dir () function.
Q.6 How is module namespace organized in a Package?
Ans: Module namespace is organized in a hierarchical structure using dot notation.
Q.7 Which variables have global scope?
Ans: The variables that are defined outside every function(local scope) in the program have a
global scope. They can be accessed in the whole program anywhere (including inside functions).
Q.8 Why do we define a function?
Ans: We define a function in the program for decomposing complex problems into simpler pieces
by creating functions and for reducing duplication of code by calling the function for specific task
multiple times
Q.9 What is an argument?
Ans: An argument is a value sent onto the function from the function call statement. e.g.
sum(4,3) have 4 and 3 as arguments which are passed to sum() function.
Q. 10 What is the use of return statement?
Ans: The return statement is used to exit a function and go back to the place from where it was
called.
Page : 18

Short Answer Type Questions (2-Marks)


Q1. Rewrite the correct code after removing the errors: -
def SI(p,t=2,r):
return (p*r*t)/100
Ans: - def SI(p, r, t=2):
return(p*r*t)/100
Q2. Consider the following function headers. Identify the correct statement: -
1) def correct(a=1,b=2,c):
2) def correct(a=1,b,c=3):
3) def correct(a=1,b=2,c=3):
4) def correct(a=1,b,c):
Ans: - 3) def correct(a=1,b=2,c=3)
Q3.What will be the output of the following code?
a=1 def f():
a=10
print(a)
Ans: The code will print 1 to the console.
Q.4 Differentiate between fruitful functions and non-fruitful functions.
Ans: Fruitful function - The functions that return a value i.e., non-void functions are also known
as fruitful functions. Non - fruitful function - The functions that do not return a value, i.e., void
functions are also known as non-fruitful functions.
Q.5 Predict the output of the following code:
a = 10
y=5
def myfunc():
y=a
a=2
print "y =", y ,",a =",a
print "a + y = ", a + y
return a + y
print "y =", y,"a =",a
Page : 19
print myfunc()
print "y =",y,"a =",a
Ans: Output of the code is: Name a not defined. Since, a was declared after its use in myfunc()
function a = 2 is declared, after the statement y = a, resulting in the not defined error.
Q.6 Explain the Scope of Variables.
Ans: There are two basic scopes of variables in Python :
i. Global variables that are accessible throughout the program anywhere inside all functions
have global scope.
ii. Local variables that are accessible only inside the function where they are declared, have
local scope.
Q.7 How can we import a module in Python?
Ans: i. using import statement
Syntax: import [,,...]
Example:
import math, cmath
import random, math, numpy
ii. using from statement
Syntax: from import [,,... ]
Example:
from math import sqrt, pow
from random import random, randint, randrange
Q.8 Find and write the output of the following python code:
def Change(P, Q = 30):
P=P+Q
Q=P-Q
print(P,"#",Q)
return (P)
R = 150
S = 100
R = Change(R,S)
print(R, "#",S)
S = Change(S)
Page : 20
Ans:
250 # 150
250 # 100
130 # 100
The R = Change(R,S) prints the value of R and S from the function and updates variable R.
Then, next print(R, "#",S) statement prints the updated value of R and value of S. Then, S =
Change(S) prints the value of S and Q(=30) in the function.
Q.9 What is the utility of:
i. default arguments
ii. keyword arguments
Ans: i. The default parameters are parameters with a default value set to them. This default
value is automatically considered as the passed value WHEN no value is provided for that
parameter in the function call statement. Thus default arguments are useful when we want to
skip an argument in a function call statement and use the default value for it instead.
ii. The keyword arguments give complete control and flexibility over the values sent as
arguments for the corresponding parameters. Irrespective of the placement and order of
arguments, keyword arguments are correctly matched. A keyword argument is where you
provide a name to the variable as you pass it into the function.
Q.10 Why do we need packages in Python?
Ans: As the application program grows larger in size with a lot of modules, we place similar
modules in one package and different modules in different packages. This makes a project easy
to manage and conceptually clear.
Application Based Questions ( 3 Marks)

Q1. Write a python program to sum the sequence given below. Take the input n from the user.

Solution:
def fact(x):
j=1 , res=1
while j<=x:
res=res*j
j=j+1
return res
n=int(input("enter the number : "))
i=1, sum=1
Page : 21
while i<=n:
f=fact(i)
sum=sum+1/f
i+=1
print(sum)
Q2. Write a program to compute GCD and LCM of two numbers.
Solution:
def gcd(x,y):
while(y):
x, y = y, x % y
return x
def lcm(x, y):
lcm = (x*y)//gcd(x,y)
return lcm
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2))
print("The G.C.D. of", num1,"and", num2,"is", gcd(num1, num2))
Q3. How many values a python function can return? Explain how?
Ans: Python function can return more than one values.
def square_and_cube(X):
return X*X, X*X*X, X*X*X*X
a=3
x,y,z=square_and_cube(a)
print(x,y,z)

Q4. Find the output of the following code: -


def CALLME(n1=1,n2=2):
n1=n1*n2
n2+=2
print(n1,n2)
Page : 22
CALLME()
CALLME(2,1)
CALLME(3)
Ans: -
24
23
64
Q5. Predict the output of the following code fragment ?
def check(n1=1, n2=2):
n1=n1+n2
n2+=1
print(n1,n2)
check()
check(2,1)
check(3)
Ans:
33
32
53
Q.6 Write a function which takes two string arguments and returns the string comparison result
of the two passed strings.
Ans:
def stringCompare(str1, str2):
if str1.length() != str2.length() :
return False
else:
for i in range (str1.length()):
if str1[i] != str2[i]:
return False
else: return True
first_string = raw_input("Enter First string:")
Page : 23
second_string = raw_input("Enter Second string:")
if stringCompare(first_string, second_string):
print ("Given Strings are same.")
else:
print ("Given Strings are different.")
Q.7 Write a program that reads a date as an integer in the format MMDDYYYY. The program will
call a function that prints print out the date in the format , .
Sample run :
Enter date: 12252019
December 25, 2019
Ans: date = input ("Enter date in MMDDYYYY format: ")
def prettyPrint(date):
months={1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8:
'August',
9: 'September', 10: 'October', 11: 'November', 12: 'December'}
month = months[int(date[:2])]
day = date[2:4]
year = date[4:]
prettyDate = month + " " + day + ", " + year
print(prettyDate)
print(prettyPrint(date))
Q.8 What is a package? How is a package different from the module?
Ans: A module in python is a .py file that defines one or more function/classes which you intend
to reuse in different codes of your program. To reuse the functions of a given module, we simply
need to import the module using the import command. A Python package is a collection of
python modules under a common namespace created by placing different modules on a
directory along with some special files. This feature comes in handy for organizing modules of
one type in one place.
Q. 9 From the program code given below, identify the parts mentioned below :
1. def processNumber(x):
2. x = 72
3. return x + 3
4.
Page : 24
5. y = 54
6. res = processNumber(y)
Identify these parts: function header, function call, arguments, parameters, function body, main
program.

Ans:
Q. 10 Write a function called removeFirst that accepts a list as a parameter. It should remove the
value at index 0 from the list. Note that it should not return anything (returns None). Note that
this function must actually modify the list passed in, and not just create a second list when the
first item is removed. You may assume the list you are given will have at least one element.
Ans:
def removeFirst (input_list):
"""This function will remove first item of the list"""
input_list.pop(0)
#pop removes and returns item of list

return
Page : 25

FILE HANDLING
A file in itself is a bunch of bytes stored on some storage device like hard disk, thumb
drive etc.

TYPES OF FILE
a. Text File b. Binary File
TEXT FILE
1) A text file stores information in ASCII or unicode characters
2) each line of text is terminated, (delimited) with a special character known as EOL

BINARY FILES
1) A binary file is just a file that contains information in the same format in which the
information is held in memory i.e the file content that is returned to you is raw.
2) There is no delimiter for a line
3) No translation occurs in binary file
4) Binary files are faster and easier for a program to read and write than are text files.
5) Binary files are the best way to store program information.

Steps to process a FILE


1) Determine the type of file usage :
in this section we determine whether file need to be open or not
Sno Method Syntax Description
1 Read() <filehandle>.read( [n] ) Reads at most n bytes ;If no n is specified,
reads the entire file.
Returns the read bytes in the form of a
string . In [11]:file
1=ope n(“E:\\m ydata\\in fo.txt”)
In [12]:readInfo=file1.read(15)
In [13]:print(readInfo)#prints firt 15
#characters of file
In [14]:type(readInfo)
Out[14]:str
2 Readline( ) <filehandle>.readline([n] Reads a line of input ;if in is specified reads at
) most n bytes.
Returns the read bytes in the form string
ending with in(line)character or returns a
blank string if no more bytes are left for
reading in the file.
In [20]:file1 =
open(“E:\\mydata\\info.txt”) In [20]:
readInfo =file1.readline()
In [22]:print (readInfo)
Page : 26
3 readlines() <filehandle>.readlines() Read all lines and returns them in a list
In [23]:file1 =open(“E:\\mydata\\info
text”) In [24]:readInfo =file1.readlines()
In [25]:print
(readInfo) In
[26]:type (readInfo)
Out[26]:list
2) open the file and assign its references to a file object or file handle
3) Process as required
4) close the file

OPENING AND CLOSING FILES


1) open() function is used to open a file
Syntax: file variable/file handle=open(file_name,acce ss
mode) Example F= open('abc.txt,'w')
this statement opens abc.txt in write mode
Note : if file mode is not mentioned in open function then default file mode i.e 'r' is used,

2) close() : the close( ) method of a file object flushes any unwritten information and
3) close the file object after which no more writing can be done
SYNTAX: fileobject.close()
Example F.close( )
FILES MODE
it defines how the file will be accessed
Text Binary File Description Notes
File Mode
Mode
‘r’ ‘rb’ Read only File must exist already ,otherwise python raises I/O error
‘w’ ‘wb’ Write only *If the file does not exist ,file is created.
*If the file exists, python will truncate existing data and
overwrite in tne file. So this mode must be used with
caution.
‘a’ ‘ab’ append *File is in write only mode.
*if the file exists, the data in the file is retained and new
data being written will be appended to the end.
*if the file does not exist ,python will create a new file.
‘r+’ ‘r+b’ or ‘rb+’ Read and *File must exist otherwise error is raised.
write *Both reading and writing operations can take place.
‘w+’ ‘w+b’ or ‘wb+’ Write and *File is created if doesn’t exist.
read *If the file exists, file is truncated(past data is lost).
*Both reading and writing operations can take place.
‘a+’ ‘a+b’ or Write and *File is created if does not exist.
‘ab+’ read *If file exists, files existing data is retained ; new data is
appended.
*Both reading and writing operations can take place.
Page : 27
TEXT FILE H ANDLING
Methods to re ad data from file s

Writing data into files


Sno Name Syntax Description
1 Write() <filehandle>.write(str1) Write string str1 to file
referenced by<filehandle>
2 Writelines() <filehandle>.writelines Writes all strings in list L as lines
(L) to file referenced by <filehandle>

BINARY FILE HANDLING:


1) in binary file data is in unreadable format and to work on binary file we have to
convert the data into readable form for read as well as write operation
2) pickling refers to the process of converting the structure to a byte stream before
writing to a file.while reading the content of the file a reverse process called unpickling
is used to convert the byte stream back to the original strstrstructure
3) we have to import pickle module for binary file handling
4) two main method of pickle modules are‐ dump() and load()
5) Syntax of dump():‐ dump(object, fileobject)
6) Syntax of load():‐load(fileobject)

RELATIVE AND ABSOLUTE P AT H


1) The os module provides functions for working with files and directories ('os' stands for
operating system). os.getcwd returns the name of the current directory
()
print(cwd)#cwd is current working directory
2) A string like cwd that identifies a file is called path. A relative path starts from the current
directory whereas an absolute path starts from the topmost directory in file system.
3) Example of Absolute path:E:\project\myfolder\data.txt

ST AND ARD FILE STRE AM


We have to import module sys for standard I/O
stream the standard stream available in python are :
1) standard input stream(sys.stdin)
2) standard output stream(sys.stdout)
3) standard error stream(sys.stderr)
Page : 28

Q1. What is the difference between 'w' and 'a' m odes?


Q2. BINARY file is unreadable and open and close through a function only so what are the
advantages of using binary file
Q3. Write a statement to open a binary file name sample.dat in read mode and the file
sample.dat is placed in a folder ( name school) existing in c drive
Q4. Which of the following function returns a list datatype
A) d=f.read()
B) d=f.read(10)
C) d=f.readline()
D) d=f.readlines()
Q5, How many file objects would you need to manage the following situations :
(a) To process four files sequentially
(b) To process two sorted files into third file
Q6. When do you think text files should be preferred over binary files?
Page : 29
Page : 30

1.
Page : 31

3
Page : 32

6
Page : 33
Page : 34
Page : 35

1. #Program to find number of He and She in file name poem.txt


f=open("c:\\main\\poem.txt","r")
data=f.read()
data=data.split()
print(data)
c=0
c1=0
for ch in data:
ch=ch.upper()
if ch=="HE" :
c=c+1
elif ch=="SHE":
c1+=1
print("No of She",c1)
print("No of he",c)

2. #function to find number of Vowels in file name poem.txt

def countvowel():

L=["A","E","I","0","U","a","e","i","o","u"]
f=open("c:\\main\\poem.txt","r")
data=f.read()
print(data)
c=0
c1=0
for ch in data:
#ch=ch.upper()
if ch in L:
Page : 36
c=c+1
print("No of vowel",c)
countvowel()

3. #to write user given values in file in different lines


f=open("c:\\main\\newfile.bat","w")
s=[]
n=int(input("enter the terms to be written"))

for i in range(n):
Rollno=input("enter Rollno")
s.append(Rollno)
name=input("enter to be written in file")
s.append(name+"\n")
f.writelines(s)
f.close()

4. #program to copy the content of one file into another


f=open("c:\\main\\poem.txt","r")
f1=open("c:\\main\\poem1.txt","w")
rs=" "
while rs:
rs=f.readline()
print(rs)
f1.write(rs)
f.close()
f1.close()

5. #To search for the occurrence of particular word entered by user


def wordsearch(word):
file=open("c:\\main\\poem.txt","r")
data=file.read()
#data=data.upper()
data=data.split()
c=0

for i in data:

#word=word.upper()
if i==word:
c+=1
print("Word found", c,"times")

w=input("enter word to be searched")


wordsearch(w)

6. #Print those word whose first character starts with T


def startwithT():
Page : 37
file=open("c:\\main\\poem.txt","r")
data=file.read()
data=data.split()
for i in data:
if i[0]=="T":
print(i)
file.close()
startwithT()

7. #counting length without new line character


file=open("c:\\main\\myfile1.txt","r")

data=""
while True:
rs=file.readline()
data=data+rs.strip()
print(data)
a=len(data)
print(a)
Page : 38
BINARY FILES:-
1. #program to write, read and search students details in binary files using dictionary

import pickle
def writingb():

file=open("c:\\main\\newbfile.dat","ab")
d={}
a=int(input("enter range"))
for i in range(a):
#d["name"]="Tanuj"
d["Rollno"]=int(input("enter rollno"))
d["name"]=input("enter name")
d["marks"]=int(input("enter marks"))
pickle.dump(d,file)
print("written successfully")
file.close()
def readingb():

file=open("c:\\main\\newbfile.dat","rb")
while True:
data=pickle.load(file)
print(data)

file.close()
def search(n):

f=0
try:

file=open("c:\\main\\newbfile.dat","rb")
while True:
data=pickle.load(file)
if data["Rollno"]==n:
print("Data Found")
print(data)
f=1
break

except EOFError:
pass
if f==0:
print("Not Found")

file.close()
writingb()
Page : 39
readingb()
a=int(input("enter no"))
search(a)

2. #Program to read, write and updation in list


import pickle
f=open("c:\\main\\list.dat","wb+")
a=eval(input("enter list elements"))
pickle.dump(a,f)
f.seek(0)

data=pickle.load(f)
print(data)
f.close()

f=open("c:\\main\\list.dat","rb+")
L1=[]
data=pickle.load(f)
f.seek(0)
L1=data
a=input("enter value to be replaced")
a1=input("new value")
for i in range(len(L1)):

if str(L1[i])==a:
L1[i]=a1
print("updated list",L1)
pickle.dump(L1,f)
f.close()

f=open("c:\\main\\list.dat","rb")
data=pickle.load(f)
print("New file",data)
f.close()

Q 1) Write a python program to create binary file dvd.dat and write 10 records in it Dvd
id,dvd name,qty,price Display those dvd details whose dvd price more than 25.
SOURCE CODE:
import pickle
f=open("pl.dat","ab")
ch="Y"
while ch=="Y":
l=[]
pi=int(input("enter dvd id "))
pnm=input("enter dvd name ")
sp=int(input("enter qty "))
p=int(input("enter price(in rupees) "))
l.append(pi)
l.append(pnm)
l.append(sp)
Page : 40
l.append(p)
pickle.dump(l,f)
ch=input("do you want to enter more rec(Y/N): ").upper()
if ch=="Y":
continue
else:
break
f.close()
f=open("pl.dat","rb+")
try:
while True:
l=pickle.load(f)
if l[3]>25:
print(l)
except EOFError:
pass
f.close()

OUTPUT:::

Q 2) Write a python program to create binary file stud.dat and write 10 records in it Stud
id,Done on 9 Nov 2020 name,perc,total Display those student details whose perc more
than 50.

SOURCE CODE::

import pickle
f=open("stu.dat","ab")
ch="Y"
while ch=="Y":
l=[]
si=int(input("ENTER STUDENT ID "))
snm=input("ENTER STUDENT NAME")
sp=int(input("ENTER PERCENTAGE "))
Page : 41
m=int(input("ENTER MARKS"))
l.append(si)
l.append(snm)
l.append(sp)
l.append(m)
pickle.dump(l,f)
ch=input("DO WANT TO ENTER MORE RECORDS ?(Y/N): ").upper()
if ch=="Y":
continue
else:
break
f.close()
f=open("stu.dat","rb+")
try:
while True:
g=pickle.load(f)
if g[2]>50:
print(g)
except EOFError:
pass
f.close()
OUTPUT::

Q3:- Write a python program to create binary file emp.dat and enter 10 records in it empid
empnm desg sal city. Display those employee details whose Name starts with R and ends with
P.

Source Code:-
import pickle
f=open("C:\\Games\\emp.dat","wb+")
ch="Y"
while ch=="Y":
L=[]
empno=int(input("Enter employee number:"))
empnm=input("Enter employee name:")
sal=int(input("Enter employee salary:"))
desg=input("Enter the designation of the employee:")
city=input("Enter the city where the employee lives:")
L.append(empno)
L.append(empnm)
L.append(sal)
Page : 42
L.append(desg)
L.append(city)
print("The content which will be written in the file is",L)
pickle.dump(L,f)
ch=input("Do you want to add more(y,n)=").upper()
if ch=="Y":
continue
else:
break
f.close()
f=open("C:\\Games\\emp.dat","rb")
f.seek(0)
try:
while True:
c=pickle.load(f)
a=c[1]
if a[0].upper()=="R" and a[-1].upper()=="P":
print(c)
except EOFError:
pass
f.close()
Output:-

Q.Write a Python program to create binary emp.dat and write 10 records in it.
Structure empid,empname,desg,sal and display no of records in the file.
CODE:-
import pickle
ch='Y'
f=open("emp.dat","wb")
while ch=="Y":
l=[]
empid=input("enter employee id")
ename=input("enter emp name")
desg=input("DESIGNATION?")
sal=input("enter salary")
l.append(empid)
l.append(ename)
l.append(desg)
Page : 43
l.append(sal)
pickle.dump(l,f)
ch=input("WANT TO ADD MORE RECORDS?(Y/N)").upper()
if ch=="Y":
continue
else:
break
f.close()
f.seek(0)
f=open('emp.dat','rb')
c=0
try:
while True:
e=pickle.load(f)
print(e)
c=c+1
print(c)
except EOFError:
pass
f.close()
Output:-

Q:Write a python program to create binary file e mp.dat and write 10 records in it
Emp id,e mp name,desg,sal Display those emp details whose salary more than 50000.
SOURCE CODE:

import pickle
f=open("emp.dat","ab+")
ch="Y"
while ch=="Y":
l=[]
eid=int(input("enteremploye id"))
enm=input("enter employe name")
ed=input("enter employe designation")
esal=int(input("enter employe salary"))
Page : 44
l.append(eid)
l.append(enm)
l.append(ed)
l.append(esal)
pickle.dump(l,f)
ch=input("do you want to add more records?(Y/N)").upper()
if ch=="Y":
continue
else:
break
f.close()
f=open("emp.dat","rb+")
try:
while True:
a=pickle.load(f)
if a[3]>50000:
print(a)
except EOFError:
pass
f.close()

OUTPUT:

Q:Write a python program to create binary file player.dat and write 10 records in it Player
id,pl name,sports,city . Display those details who belongs to Surat city

Ans:-

import pickle
f=open("player.dat","ab+")
ch='Y'
while ch=='Y':
l=[]
playerid=input("enter player id")
plnm=input("enter player name")
sports=input("enter the name of sports played by that player:")
Page : 45
city=input("enter the name of player's city")
l.append(playerid)
l.append(plnm)
l.append(sports)
l.append(city)
pickle.dump(l,f)
ch=input("do you want to add more records=more y/n").upper()
if ch=='Y':
continue
else:
break
f.close()
f.seek(0)
f=open("player.dat","rb+")
try:
while True:
p=pickle.load(f)
if p[3]=="surat":
print(p)
except EOFError:
pass
f.close()

OUTPUT:-

-------------------------------------------------------------------------------------
WRITE A PYTHON PROGRAM TO CREATE BINARY FILE stu.dat AND WRITE 10
RECORDS IN IT STUD ID,MANE,PERCENT AGE,TOTAL MARKS. DISPLAY THOSE
STUDENT DETAILS WHOSE STUD ID LESS THAN 20.
code
import pickle
f=open("stu.dat","ab")
ch="Y"
while ch=="Y":
l=[]
Id=int(input("Enter Id "))
Page : 46
nm=input("Enter Name")
perc=int(input("Enter percentage "))
marks=int(input("Enter marks"))
l.append(Id)
l.append(nm)
l.append(perc)
l.append(marks)
pickle.dump(l,f)
ch=input("Do you want to enter more records ?(Y/N): ").upper()
if ch=="Y":
continue
else:
break
f.close()
f=open("stu.dat","rb+")
try:
while True:
a=pickle.load(f)
if a[0]<20:
print(a)
except EOFError:
pass
f.close()
OUTPUT
Enter Id 12
Enter Name abc
Enter percentage 45
Enter marks200
Do you want to enter more records ?(Y/N): Y
Enter Id 01
Enter Name pqr
Enter percentage 77
Enter marks365
Do you want to enter more records ?(Y/N): Y
Enter Id 234
Enter Name xyz
Enter percentage 95
Enter marks475
Do you want to enter more records ?(Y/N): N
[1, 'gk', 92.6, 457]
[1, 'gk', 92.6, 456]
[1, 'gk', 92.6, 456]
[2, 'gg', 45.0, 245]
Q-Write a python program to create binary file player.dat and write 10 records in it ,Player
id,pl name,sports
Display those player details whose sports is athletic.

SOURCE CODE-
import pickle
f=open(“player.dat”, “ab+”)
ch=’Y'
Page : 47
while ch==’Y':
l=[]
playerid=int(input(“enter player id –“))
playernm=input(“enter playernm-“)
sports=input(“enter sports”)
place=input(“enter place”)
l. append(playerid)
l. append (playernm)
l. append(sports)
l. append(place)
pickle. Dump(l, f)
ch=input(“do you want to add more records(Y/N)”). upper()
if ch==’Y':
continue
else:
break
f. close()
f=open(“player.dat”, “rb+”)
try:
while True
e=pickle.load(f)
if e[2]==”athletic”:
print(e)
except EOFError:
pass
f. close()
OUTPUT-

Question -Write a python program to create binary file player.dat and write 10 records in it
,Player id, pl name,sports
Display those player details whose sports is athletic.

Source Code:-
Page : 48

import pickle
ch='Y'
f=open("player.dat","wb")
while ch=="Y":
l=[]
playid=input("enter player id")
pname=input("enter player name")
sports=input("sport name")
l.append(playid)
l.append(pname)
l.append(sports)
pickle.dump(l,f)
ch=input("WANT TO ADD MORE RECORDS?(Y/N)").upper()
if ch=="Y":
continue
else:
break
f.close()
f.seek(0)
f=open("player.dat","rb")
try:
while True:
e=pickle.load(f)
if e[2].capitalize()=="Athletics":
print(e)

except EOFError:
pass

Output:-

Q-Write a python program to create binary file player.dat and write 10 records in it ,Player
id,pl name,sports Display those player details whose sports is chess.
Page : 49

SOURCE CODE-

import pickle
f=open(“player.dat”, “ab+”)
c=’Y'
while c==’Y':
l=[]
playerid=int(input(“enter player id –“))
playernm=input(“enter playernm-“)
sports=input(“enter sports”)
place=input(“enter place”)
l. append(playerid)
l. append (playernm)
l. append(sports)
l. append(place)
pickle. Dump(l, f)
c=input(“do you want to add more records(Y/N)”). upper()
if c==’Y':
continue
else :
break
f. close()

f=open(“player.dat”, “rb+”)
try:
while True:
s=pickle.load(f)
if s[2]==”chess”:
print(s)
except EOFError:
pass
f. close()
● OUTPUT-

#Enter custname,custcode,city in binary file Read file search custcode


import pickle
f=open("cust.dat","ab+")
ch='Y'
Page : 50
while ch=='Y':
l=[]
ccd=input("enter custcode")
cnm=input("enter custname and")
ccity=input("enter city")
l.append(ccd)
l.append(cnm)
l.append(ccity)
# load list into file
pickle.dump(l,f)
ch=input("do you add= more y/n").upper()
if ch=='Y':
continue
else:
break
# read file set pointer
f.seek(0)
flag=False
# Read file
ccdsearch=input("enter custcode to be search from file")
search=[]
try: #Remove Eof Ranout error
while True:
c=pickle.load(f)
print(c)
c1cd=c[0]
c1nm=c[1]
c1city=c[2]
if ccdsearch.upper()==c1cd:
flag=True
search=c
break
except EOFError: #Remove Eof Ranout error
pass #Remove Eof Ranout error
if flag==True:
print("customer found")
print("customer name is:",search[1])
else:
print("customer not found")

CSV FILE :-

Q)Write a python program to create a csv file dvd.csv and write 10 records in it Dvd
id,dvd name,qty,price. Display those dvd details whose dvd price is more than 25.

SOURCE CODE::

import csv
f=open("pl.csv","w")
cw=csv.writer(f)
ch="Y"
Page : 51
while ch=="Y":
l=[]
pi=int(input("enter dvd id "))
pnm=input("enter dvd name ")
sp=int(input("enter qty "))
p=int(input("enter price(in rupees) "))
l.append(pi)
l.append(pnm)
l.append(sp)
l.append(p)
cw.writerow(l)
ch=input("do you want to enter more rec(Y/N): ").upper()
if ch=="Y":
continue
else:
break
f.close()
f=open("pl.csv","r+")
cw=list(csv.reader(f))
for i in cw:
if l[3]>25:
print(i)
f.close()

OUTPUT::

QUESTIONS AND ANSWERE AS PER CBSE SAMPLE PAPER


Q.23
Page : 52

ANS

Anis of class 12 is writing a program to create a CSV file “mydata.csv” which will contain user name
and password for some entries. He has written the following code. As a programmer, help him to
successfully execute the given task.

import _____________ # Line 1


def addCsvFile(UserName,PassWord): # to write / add data into the CSV file
f=open(' mydata.csv','________') # Line 2
newFileWriter = csv.writer(f)
newFileWriter.writerow([UserName,PassWord])
f.close() #csv file reading code
def readCsvFile(): # to read data from CSV file
with open('mydata.csv','r') as newFile:
Page : 53
newFileReader = csv._________(newFile) # Line 3
for row in newFileReader:
print (row[0],row[1])
newFile.______________ # Line 4
addCsvFile(“Aman”,”123@456”)
addCsvFile(“Anis”,”aru@nima”)
addCsvFile(“Raju”,”myname@FRD”)
readCsvFile() #Line 5

(a) Give Name of the module he should import in Line 1.


(b) In which mode, Aman should open the file to add data into the file
(c) Fill in the blank in Line 3 to read the data from a csv file.
(d) Fill in the blank in Line 4 to close the file.
(e) Write the output he will obtain while executing Line 5.

(a) Line 1 : csv


(b) Line 2 : a
(c) Line 3 : reader
(d) Line 4 : close()
(e) Line 5 : Aman 123@456
Anis aru@nima
Raju myname@FRD
Priti of class 12 is writing a program to create a CSV file “emp.csv”. She has written the
following code to read the content of file emp.csv and display the employee record whose
name begins from “S‟ also show no. of employee with first letter “S‟ out of total record. As
a programmer, help her to successfully execute the given task.
Consider the following CSV file (emp.csv):

1,Peter,3500
2,Scott,4000
3,Harry,5000
4,Michael,2500
5,Sam,4200

import ________ # Line 1


def SNAMES():
with open(_________) as csvfile: # Line 2
myreader = csv._______(csvfile, delimiter=',') # Line 3
count_rec=0
count_s=0
for row in myreader:
Page : 54
if row[1][0].lower()=='s':
print(row[0],',',row[1],',',row[2])
count_s+=1
count_rec+=1
print("Number of 'S' names are ",count_s,"/",count_rec)
(a) Name the module he should import in Line 1 1
(b) In which mode, Priti should open the file to print data. 1
(c) Fill in the blank in Line 2 to open the file. 1
(d) Fill in the blank in Line3 to read the data from a csv file. 1
(e) Write the output he will obtain while executing the above program. 1
(a) csv 1
(b) read mode 1
(c) 'emp.csv' 1
(d) reader 1
(e) 2,Scott,4000
5,Sam,4200 1
Number of “S” names are 2/5
Sanjay Dalmia of class 12 is writing a program to create a CSV file “contacts.csv” which
will contain Name and Mobile Number for some entries. He has written the following
code. As a programmer, help him to successfully execute the given task.

import # Line 1
def addCsvFile(Name,Mobile): # to write / add data into the CSV file

f=open('contacts.csv',' ') # Line 2


newFileWriter = csv.writer(f)
newFileWriter.writerow([Name,Mobile])
f.close()
#csv file reading code
def readCsvFile(): # to read data from CSV file with
open('contacts.csv','r') as newFile:

newFileReader = csv. (newFile) # Line 3 for row in


newFileReader:

print (row[0],row[1])
newFile. # Line 4

addCsvFile(“Arjun”,”8548587526”)
Page : 55
addCsvFile(“Arunima”,”6585425855”)
addCsvFile(“Frieda”,”8752556320”)
readCsvFile() #Line 5
a) Name the module he should import in Line 1. (1)
import csv
b) In which mode, Sanjay should open the file to add data into the file (1)
a or a+
c) Fill in the blank in Line 3 to read the data from a csv file. (1)
reader

d) Fill in the blank in Line 4 to close the file. (1)


close()

a) Write the output he will obtain while executing Line 5. (1)


Arjun 8548587526
Arunima 6585425855
Frieda 8752556320
Page : 56
Page : 57

ans
Page : 58

Write a function AMCount() in Python, which should read each character of a text file
STORY.TXT, should count and display the occurance of alphabets A and M (including small
cases a and m too). Example:

If the file content is as follows:


Updated information
As simplified by official websites.
The EUCount() function should display the output as:
A or a:4
M or m :2
Write a function in Python that counts the number of “The” or “This” words present in a text file
“MY_TEXT_FILE.TXT”.

Note: (The comparison should be case insensitive)


Ans
def displayMeMy():
um=0
Page : 59
f=open("story.txt","rt")
N=f.read()
M=N.split()
for x in M:
if x=="Me" or x== "My":
print(x)
num=num+1
f.close()
print("Count of Me/My in file:",num)
Or
def count_A_M():
f=open("story.txt","r")
A,M=0,0
r=f.read(
)
for x in
r:
if x[0]=="A" or x[0]=="a" :
A=A+1
elif x[0]=="M" or x[0]=="m":
M=M+1
f.close()
print("A or a: ",A)
print("M or m: ",M)
Note : Using of any correct code giving the same result is also
accepted.
num_words = 0
with open('MY_TEXT_FILE.TXT', 'r') as f:
for line in f:
words = line.split()
for word in words:
if word.upper()== 'THE' or word.upper()== 'THIS' :
num_words+=1
Page : 60
print(num_words)
OR
Write a function VowelCount() in Python, which should read each character of a text file
MY_TEXT_FILE.TXT, should count and display the occurrence of alphabets vowels.

Example:
If the file content is as follows: Updated information

As simplified by official websites.


The VowelCount() function should display the output as:
A or a:4
E or e :4
I or I :8
O or o : 0
U or u: 1

def VowelCount():

count_a=count_e=count_i=count_o=count_u=0
with open('MY_TEXT_FILE.TXT', 'r') as f:
for line in f:
for letter in line:
if letter.upper()=='A':
count_a+=1
elif letter.upper()=='E':
count_e+=1
elif letter.upper()=='I':
count_i+=1
elif letter.upper()=='O':
count_o+=1
elif letter.upper()=='U':
count_u+=1

print("A or a:", count_a)


Page : 61
print("E or e:", count_e)
print("I or i:", count_i)
print("O or o :", count_o)
print("U or u:", count_u)

or any other correct logic


Page : 62

Write a function in Python that counts the number of “Me” or “My” words present in a text file
“STORY.TXT”. If the “STORY.TXT” contents are as follows:
My first book was Me and My Family.
It gave me chance to be Known to the world.

The output of the function should be: Count of Me/My in file: 4

OR

Write a function AMCount() in Python, which should read each character of a text file STORY.TXT,
should count and display the occurrences of alphabets A and M (including small cases a and m too).
Example: If the file content is as follows:
Updated information As simplified by official websites.

The AMCount() function should display the output as: A or a: 4 M or m :2


def displayMeMy():
num=0
f=open("story.txt","rt")
N=f.read()
M=N.split()
for x in M:
Page : 63
if x=="Me" or x== "My":
print(x)
num=num+1
f.close()
print("Count of Me/My in file:",num)

OR

def AMCount():
f=open("story.txt","r")
A,M=0,0
r=f.read()
for x in r:
if x[0]=="A" or x[0]=="a" :
A=A+1

elif x[0]=="M" or x[0]=="m":


M=M+1
f.close()
print("A or a: ",A)
print("M or m: ",M)
Page : 64
Page : 65

A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].


i. Write a user defined function CreateFile() to input data for a record and add to Book.dat .
ii. Write a function CountRec(Author) in Python which accepts the Author name as parameter
and count and return number of books by the given Author are stored in the binary file
“Book.dat”

OR

A binary file “STUDENT.DAT” has structure (admission_number,


Name, Percentage). Write a function countrec() in Python that
would read contents of the file “STUDENT.DAT” and display the
details of those students whose percentage is above 75. Also
display number of students scoring above 75%

Ans
import pickle
def createFile():
fobj=open("Book.dat","ab")
BookNo=int(input("Book Number : "))
Book_name=input("Name :")
Author = input("Author:" )
Price = int(input("Price : "))
rec=[BookNo,Book_Name,Author,Price]
pickle.dump(rec,fobj)
fobj.close()

def CountRec(Author):
fobj=open("Book.dat","rb")
num = 0
Page : 66
try:
while True:
rec=pickle.load(fobj)
if Author==rec[2]:
num = num + 1
except:
fobj.close()
return num

OR

import pickle
def CountRec():
fobj=open("STUDENT.DAT","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[2] > 75:
print(rec[0],rec[1],rec[2],sep="\t")
num = num + 1
except:
fobj.close()
return num

40 Write a function SCOUNT( ) to read the content of binary file “NAMES.DAT‟ and
display number of records (each name occupies 20 bytes in file ) where name begins
from “S‟ in it.
For. e.g. if the content of file is:
SACHIN
AMIT
AMAN
SUSHIL
DEEPAK 5

HARI SHANKER
Function should display
Total Names beginning from “S” are 2
OR
Consider the following CSV file (emp.csv):

Sl,name,salary

1,Peter,3500
Page : 67
2,Scott,4000
3,Harry,5000
4,Michael,2500
5,Sam,4200
Write Python function DISPEMP( ) to read the content of file emp.csv and display only
those records where salary is 4000 or above
Ans

def SCOUNT( ):
s=' '
count=0
with open('Names.dat', 'rb') as f:
while(s):
s = f.read(20)
s=s.decode( )
if len(s)!=0:
if s[0].lower()=='s':
count+=1
print('Total names beginning from "S" are ',count)
OR
import csv
def DISPEMP():
with open('emp.csv') as csvfile:
myreader = csv.reader(csvfile,delimiter=',')
print("%10s"%"EMPNO","%20s"%"EMP NAME","%10s"%"SALARY")
for row in myreader:
if int(row[2])>4000:

print("%10s"%row[0],"%20s"%row[1],"%10s"%row[2])

A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].

i. Write a user defined function CreateFile() to input data


for a record and add to Book.dat .

ii. Write a function CountRec(Author) in Python which


accepts the Author name as parameter and count and
return number of books by the given Author are stored in
the binary file

“Book.dat”

OR
Page : 68

A binary file “STUDENT.DAT” has structure (admission_number,


Name, Percentage). Write a function countrec() in Python that would
read contents of the file “STUDENT.DAT” and display the details of
those students whose percentage is above 75. Also display number of
students scoring above 75%

import pickle

def createFile():

fobj=open("Book.dat","ab")

BookNo=int(input("Book Number : "))

Book_name=input("Name :")

Author = input(“Author: “)

Price = int(input("Price : "))

rec=[BookNo,Book_Name,Author,Price]

pickle.dump(rec,fobj)

fobj.close()

(ii)
def CountRec(Author):

fobj=open("Book.dat","rb")

num = 0

try:

while True:
rec=pickle.load(fobj)
Page : 69
if Author==rec[2]:
num = num + 1
except:
fobj.close()
return num
OR
import pickle
def CountRec(:
fobj=open("STUDENT.DAT","rb")
num = 0
try

while True:
rec=pickle.load(fobj)
if rec[2] > 75:
print(rec[0],rec[1],rec[2],sep="\t")
num = num + 1
except:
fobj.close()
return num
Page : 70
Page : 71
Computational Thinking and Programming -2
Data Structure in Python ( marks 3 x 2 questions = 6 marks)
Basic concepts of Data Structure
Definition: The logical or m athem atical m odel of a particular organization of data is called
data structure. It is a way of storing, accessing, m anipulating data.

TYPES OF DAT A STRUCTURE:


There are two types of data structure:
1. Linear data structure: It is sim ple data structure. The elem ents in this data
structure creates a sequence. Exam ple: Array, linked list, stack, queue.
2. Non‐Line ar data structure: The data is not in sequential form . These are
multilevel data structures. Exam ple: Tree, graph.

OPERATION ON D AT A STRUCTURE:
There are various types of operations can be perform ed with data structure:
1. Traversing: Accessing each record exactly once.
2. Insertion: Adding a new elem ent to the structure.
3. Deletion: Rem oving elem ent from the structure.
4. Searching: Search the element in a structure.
5. Sorting: Arrange the elem ents in ascending and descending order.
6. Merging: Joining two data structures of sam e type.
Stack : It is a linear data structure which follow the operation LIFO ( Last In First Out ) operation.
Page : 72
Marks - 3 ( Programs)
1. Write a Python function to sum all the numbers in a list and return a total.
Sample List : (8, 2, 3, 0, 7)
Expected Output : 20
Ans.
def sum(numbers):
total = 0
for x in numbers:
total += x
return total
print(sum((8, 10, 3, 0, 7)))
2 Write a function in REP which accepts a list of integers and its size as
arguments and replaces elements having even values with its half and
elements
having odd values with twice its value .
eg: if the list contains
3, 4, 5, 16, 9
then the function should rearranged list as
6, 2,10,8, 18
Ans. def REP (L, n):
for i in range(n):
if L[i] % 2 == 0:
L[i] /= 2
else:
L[i] *= 2
print (L)

3 Write code in Python to calculate and display the frequency of each item in a list.
Ans. L=[10,12,14,17,10,12,15,24,27,24]
L1=[ ]
L2=[ ]
for i in L:
if i not in L2:
c=L.count(i)
L1.append(c)
L2.append(i)
print('Item','\t\t','frequency')
for i in range(len(L1)):
print(L2[i],'\t \t', L1[i])

4. Write a function bubble_sort (Ar, n) in python, Which accepts a list Ar of


numbers and n is a numeric value by which all elements of the list are sorted
by Bubble sort Method.
Ans: def bubble_sort(Ar, n):
print ("Original list:", Ar)
for i in range(n-1):
for j in range(n-i-1):
if Ar[j] > Ar[j+1]:
Page : 73
Ar[j], Ar[j+1] = Ar[j+1], Ar[j]
print ("List after sorting :", Ar)

5 Write function insertinSort(arr) to sort the elements.


Ans. def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key

# Driver Code
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print (arr[i])

6. Write a function binary_search (arr, x) in python to search an element using


binary method,
Ans. def binary_search(arr, x):
low = 0
high = len(arr) - 1
mid = 0
while low <= high:

mid = (high + low) // 2


if arr[mid] < x:
low = mid + 1
elif arr[mid] > x:
high = mid - 1
else:
return mid
return -1
arr = [ 2, 3, 4, 10, 40 ]
x = 10
result = binary_search(arr, x)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")
7. Write a program for linear search.

Ans def linear_search(L, item) :


n=len(L)
f=1
for i in range(n):
if L[i]==item :
Page : 74
print("Elem ent found at the position :", i+1)
f=0
break
if f==1 :
print("Element not Found")

8 Write a function AddCustomer(Customer) in Python to add a new Customer


information NAME into the List of CStack and display the information.

Ans def AddCustomer(Customer):


CStake.append(Customer)
If len(CStack)==0:
print (“Empty Stack”)
else:
print (CStack)
9 Write a function DeleteCustomer() to delete a Customer information from a list
of CStack. The function delete the name of customer from the stack

Ans def DeleteCustomer():


if (CStack ==[]):
print(“There is no Customer!”)
else:
print(“Record deleted:”,CStack.pop())
10 Write a function in Python PUSH(Arr), where Arr is a list of numbers. From this
list push all numbers divisible by 5 into a stack implemented by using a
list.Display the stack if it has at least one element, otherw ise display
appropriate error message.

Ans. def PUSH(Arr):


s=[ ]
for x in range(0,len(Arr)):
if Arr[x]%5==0:
s.append(Arr[x])
if len(s)==0:
print("Empty Stack")
else:
print(s)
11 Write a function in Python popStack(st), where st is a stack implemented by a
list of numbers. The function returns the value deleted from the stack
Ans. def popStack(st) :
if len(st)==0:
print("Underflow")
else:
L = len(st)
val=st[L-1]
print(val)
st.pop(L-1)
Page : 75

Computer Networks- I
1. What are the components required for networking ?
2. What is spyware?
3. What is Ethernet?
4. Write two advantage and disadvantage of networks.
5. What is ARPAnet ?
6. What is NSFnet ?
7. What is communication channel?
8. Define baud, bps and Bps. How are these interlinked?
9. What do you understand by InterSpace?
10. Name two switching circuits and explain any one
11. What is communication channel? Name the basic types of communication channels
available
12. What are the factors that must be considered before making a choice for the topology?
13. What are the similarities and differences between bus and tree topologies?
14. What are the limitations of star topology?
15. When do you think, ring topology becomes the best choice for a network?
16. Write the two advantages and two disadvantages of Bus Topology in network.
17. What is modem?
18. Define the following:
(i)RJ-45 (ii)Ethernet (iii) Ethernet card (iv)hub (v)Switch

Answers for Computer Network-1

Ans 1. Routers. Routers are devices on the network which is responsible for forwarding data
from one device to another. ...
Switches.
Network hubs.
Wireless access points.
Network Cables.
Network Server.
Network Interface Cards (NIC)

Ans 2. Spyware is software that is installed on a computing device without the end user's
knowledge. Any software can be classified as spyware if it is downloaded without the user's
authorization. Spyware is controversial because even when it is installed for relatively innocuous
reasons, it can violate the end user's privacy and has the potential to be abused.

Ans 3. Ethernet is the traditional technology for connecting wired local area networks (LANs),
enabling devices to communicate with each other via a protocol -- a set of rules or common
network language.
As a data-link layer protocol in the TCP/IP stack, Ethernet describes how network devices can
format and transmit data packets so other devices on the same local or campus area network
segment can recognize, receive and process them. An Ethernet cable is the physical, encased
wiring over which the data travels
Page : 76
Ans 4. Advantage:  We can share resources such as printers and scanners.  Can share data
and access file from any computer.
Disadvantage:  Server faults stop applications from being available.  Network faults can cause
loss of data.

Ans 5. ARPAnet (Advanced Research Project Agency Network is a project sponsored by U. S.


Department of Defense.

Ans 6. NSFnet was developed by the National Science Foundation which was high capacity
network and strictly used for academic and engineering research.

Ans 7. Name the basic types of communication channels available. Communication channel
mean the connecting cables that link various workstations. Following are three basic types of
communication channels available: a) Twisted-Pair Cables b) Coaxial Cables c) Fiber-optic
Cables

Ans 8. Baud is a unit of measurement for the information carrying capacity of a communication
channel. bps- bits per second. It refers to a thousand bits transmitted per second. Bps- Bytes per
second. It refers to a thousand bytes transmitted per second. All these terms are measurement

Ans 9. Interspace is a client/server software program that allows multiple users to communicate
online with real-time audio, video and text chat I dynamic 3D environments.

Ans10. The two switching circuits are  Circuit Switching  Message Switching Circuit Switching
- In this technique, first the complete physical connection between two computers is established
and then data are transmitted from the source computer to the destination computer.

Ans 11. Communication channel mean the connecting cables that link various workstations.
Following are three basic types of communication channels available: a) Twisted-Pair Cables b)
Coaxial Cables c) Fiber-optic Cables.

Ans 12. There are number of factors to consider in before making a choice for the topology, the
most important of which are as following : (a) Cost. (b) Flexibility (c) Reliability .

Ans.13. Similarities : In both Bus and Tree topologies transmission can be done in both the
directions, and can be received by all other stations. In both cases, there is no need to remove
packets from the medium.
Differences : Bus topology is slower as compared to tree topology of network. Tree topology is
expensive as compared to Bus Topology

Ans 14.. Requires more cable length than a linear topology. If the hub, switch, or concentrator
fails, nodes attached are disabled. More expensive than linear bus topologies because of the
cost of the hubs, etc.

Ans 15. Ring topology becomes the best choice for a network when, short amount of cable is
required. No wiring closet space requires.

Ans 16. Advantage: Easy to connect a computer or peripheral to a linear bus. Requires less
cable length than a star topology.
Disadvantage : Slower as compared to tree and star topologies of network. Breakage of wire at
any point disturbs the entire
Page : 77

Ans 17. Name two categories of modems. Modem is a device that converts digital
communication signals to analog communication digital signals and vice versa. Follow ing are the
two categories of modems. 1) Internal Modem (Fixed with computer) 2) External Modem
(Connect externally to computer).

Ans 18. (i) RJ-45: RJ45 is a standard type of connector for network cables and networks. It is an
8-pin connector usually used with Ethernet cables. (ii)Ethernet: Ethernet is a LAN architecture
developed by Xerox Corp along with DEC and Intel. It uses a Bus or Star topology and supports
data transfer rates of up to 10 Mbps. (iii)Ethernet card: The computers parts of Ethernet ar e
connected through a special card called Ethernet card. It contains connections for either coaxial
or twisted pair cables. (iv)Hub: In computer networking, a hub is a small, simple, low cost device
that joins multiple computers together. (v)Switch: A Switch is a small hardware device that joins
multiple computers together within one local area network (LAN).
Page : 78

COMPUTER SCIENCE – NEW (083)

SAMPLE QUESTION PAPER – SET-1

(2020-21) CLASS- XII


Q3 A) ----------- is a set of rules used for communication 1
B) -------------protocol is used for sending email 1
C) Define modulation and write name of two modulation techniques 1
D) Define IOT 1
E) Explain the working of Email 2
F) Differentiate between IPv4 and IPv6 2
G) Expand the following terms 3
i)NFC ii)IMAP iii)CDMA
iv)MAC v)VoIP vi)URL
H) Standard Bank has set up its new center in India for its office and 5
web based activities. It has five buildings as shown in the
diagram below:

A B C

D E

Distance between various


buildings
A to B 50 Mts
B to C 30 Mts
C to D 30 Mts
D to E 35 Mts
E to C 40 Mts
D to A 120 Mts
D to B 45 Mts
E to B 65 Mts
No of computers
A 55
B 180
C 60
D 55
E 70

(a) Suggest a possible cable layout for connecting the


Page : 79
buildings.
(b) Suggest the most suitable place to install the server of this
organization.
(c) Suggest the placement of the following devices with
justification.
(i.) Hub/Switch
(ii.) Repeater
(d) The company wants to link its head office in ‘A’ building to
its Office in Sydney
(i) Which type of transmission medium is appropriate for
such a link?
(ii) What type of network this connection result into?

(e) Suggest topology used for above networking.

Marking Scheme
Q3 A) PROTOCOL 1
B) SMTP 1
C) Modulation is the process of modulating message signal .Two 1
Types of modulation are :Amplitude modulation and Frequency
Modulation
D) It is the network of physical objects or things embedded with 1
electronics,software,sensors and network connectivity which
enables these objects to collect and exchange data
E) Email System comprises of following components 2
 Mailer
 Mail Server
 Mailbox

Mailer:It is also called mail program,mail application or mail client


.It allows us to manage ,read and compose email
Mail Server:The function of mail Server is to receive ,store and
deliever the email.It is a must for mail server to be running all the
time because if it crashes or is down,email can be lost
Mailboxes :Mailboxes is generally a folder that contains emails and
information about them.
F) IPV4 Internet is protocol version 4 and IP6 is Internet protocol 2
version 6
IPv4 is 32 bit and IPv6 is 128 bit
IPv6 is still in transition phase and it will expected to replace IPV4
G) Expand the following terms 1/2×6=3
i) NFC (Near Field Communication)
ii) IMAP (Internet Message Access Protocol)
iii) CDMA (code division multiple access)
iv) MAC (Media Access Control)
v) VoIP (Voice Over Internet Protocol)
vi) URL (Uniform resourse locator)
Page : 80

H) a) 1+1+1+1+1

A B C

D E

b)Building B
c) i)Hub/Switch is placed in each building
ii)Repeater is placed between D TO A
d) i)Satellite Communication
ii) WAN
e.) STAR
Page : 81
COMPUTER SCIENCE – NEW (083)
SAMPLE QUESTION PAPER – SET-2

(2020-21) CLASS- XII

Q.3 a Expand the following 2


(i) PPP (ii) TDMA
(ii) TCP/IP (iv) VOIP

b What is MAC address ? Give example. 2


c What is Cloud Computing? Write two advantages of Cloud Services. 2
d Name the network tools used in the given situation 2
(i) to troubleshoot internet connection problem
(ii) to see the IP address associated with a domain name
(iii) to look up registration record associated with a domain name
(iv) to test the speed of internet connection
e Define the terms i) Cladding ii) attenuation iii) Telnet 3
g ABC company is planning to set up their new offices in India with its hub at 5
Hyderabad . As a Network advisor ,understand their requirements and
suggest to them best solution.

Block to Block distance (in Meters):


Block From Block Distance
Human Resource Conference 60
Human Resource Finance 60
Conference Finance

Expected Number of Computer installed in each building block:


Block Computer
Human Resource 125
Finace 25
Confrence 60
i) What is the most suitable block to install server?
ii) What will be the best possible connectivity out of the following to
connect its new office in Bengaluru
With its London-based office ?
Page : 82
i)Infrared ii)Satellite iii) Ethernet Cable
iii) Which of the following devices will you suggest to connect each
computer in each of the above blocks?
i) Gateway ii) Switch iii) Modem
iv) Write the name of any two popular Open Source Software which are
used as Operating Systems.
v) Which topology used for above networking.

Marking Scheme
SECTION B
Q.3 a PPP: Point to Point Protocol 2
TDMA:Time division multiple Access
TCP/IP: Transmission Control Protocol/Internet Protocol
VOIP:Voice Over Internet Protocol
½ marks for each correct expansion
b Medium access control Physical Address of NIC Card assigned by 2
manufacturer stored on ROM. (1+1=2)
e.g 00:0d:83:b1:c0:8e
1 mark for correct definition and 1 mark for example
c Cloud computing is an internet based new age computer technology. It 2
is the next stage technology that uses the cloud to provide the services
whenever and wherever the user needs it. It provides a method to
access several servers worldwide

Two advantages of Cloud Computing:


i) Data backup and storage ii) Powerful server capability

2 marks for correct explanation.


d (i)ping 2
nslookup
(ii)
whois
(iii)
speedtest.net
(iv)
½ mark for each correct answer
e Cladding: Layer of glass surrounded the Centre fibre of glass in fibre 3
optics cable. Attenuation: Degeneration of signal over a
distance on network cable.
Telnet: Service to log in remotely on any computer over network.

½ mark for each correct line (Max 2 marks for correct answer)
g i) Human Resource Block 5
Page : 83
ii) Ethernet Cable
iii) Switch
iv) Linux and Open Solaris
v) Star topology

1 mark for each correct answer

COMPUTER SCIENCE – NEW (083)

SAMPLE QUESTION PAPER – SET-3

(2020-21) CLASS- XII

Q.3 a ………………….. is an example of cloud. 1


b ………………….. is a network of physical objects embedded with 1
electronics, software, sensors and network connectivity.
c ………………….. is a device to connect two dissimilar network. 1
d ………………….. describes the measuring unit of data transfer rate . 1
e Give the full forms of the following : 2
(i) SMTP
(ii) SIM
(iii) Lifi
(iv) GPRS
f How many pair of wires are there in a twisted pair cable (Ethernet)? What 2
is the name of the port, which is used to connect Ethernet cable to a
computer or a laptop?
g Identify the type of cyber crime for the following situations: 3
(i) A person complains that Rs. 4.25 lacs have been fraudulently
stolen from his/her account online via some online transactions in
two days using NET BANKING.
(ii) A person complains that his/her debit/credit card is safe with him
still somebody has done shopping /ATM transaction on this card.
(iii) A person complains that somebody has created a fake profile of
Facebook and defaming his/her character with abusive comments
and pictures.
h Sharma Medicos Center has set up its new center in Dubai. It has four 5
buildings as shown in the diagram given below:

Distance between various building are as follows:


Page : 84

As a network expert, provide the best possible answer for the following
queries:
i) Suggest a cable layout of connections between the buildings.
ii) Suggest the most suitable place (i.e. buildings) to house the server
of this
organization.
iii) Suggest the placement of the following device with justification:
i. a) Repeater b) Hub/Switch
iv) Suggest a system (hardware/software) to prevent unauthorized
access to or from the network.
v) Suggest best topology use for above networking.
Marking Scheme
Q.3 a ………………….. is an example of cloud. 1
ANS Google Drive or any other correct example
b ………………….. is a network of physical objects embedded with 1
electronics, software, sensors and network connectivity.
ANS The internet of things OR Internet
c ………………….. is a device to connect two dissimilar network. 1
ANS Router
d ………………….. describes the measuring unit of data transfer rate . 1
ANS megabit per second
e Give the full forms of the following : 2
(v) SMTP
(vi) SIM
(vii) Lifi
(viii) GPRS
ANS SIMPLE MAIL TRANSFER PROTOCOL
SUBSCRIBER IDENTITY MODULE OR SUBSCRIBER
IDENTIFICATION MODULE
LIGHT FIDILITY
GENERAL PACKET RADIO SERVICES
f How many pair of wires are there in a twisted pair cable (Ethernet)? What 2
is the name of the port, which is used to connect Ethernet cable to a
computer or a laptop?
ANS TWO INSULATED COPPER WIRES , ETHERNET PORT
g Identify the type of cyber crime for the following situations: 3
(iv) A person complains that Rs. 4.25 lacs have been fraudulently
stolen from his/her account online via some online transactions in
two days using NET BANKING.
(v) A person complains that his/her debit/credit card is safe with him
still somebody has done shopping /ATM transaction on this card.
(vi) A person complains that somebody has created a fake profile of
Facebook and defaming his/her character with abusive comments
and pictures.
Page : 85
ANS (i) Bank Fraud
(ii) Identity Theft
(iii) Cyber Stalking
h SHARMA Medicos Center has set up its new center in Dubai. It has four 5
buildings as shown in the diagram given below:

Distance between various building are as follows:

As a network expert, provide the best possible answer for the following
queries:
i) Suggest a cable layout of connections between the buildings.
ii) Suggest the most suitable place (i.e. buildings) to house the server of
this organization.
iii) Suggest the placement of the following device with justification:
a) Repeater b) Hub/Switch
iv) Suggest a system (hardware/software) to prevent unauthorized
access to or from the network.
v) Suggest best topology use for above networking.
ANS i)

ii) Research Lab.


iii) Hub/Switch is required in each buildings. Repeater may be used
in between store to research Lab due to long distance.
iv) Use firewell for security issues.
v) Star topology
Page : 86
Chapter: Network Security Concepts
1 Mark
1. What is virus?
Ans. Viruses are small programs that are written intentionally to damage the data and files on a
system. These programs are spread from one computer system to another which interrupts the
normal functioning of a computer.
2. What is the difference between Virus and Worm?
Ans. The Virus attaches itself to executable files and transfers from one system to the other.
While, A Worm is a malicious program that replicates itself and can spread to different
computers via Network.
For Virus, Host is needed for spreading, While Worm doesn’t need a host to replicate from
one computer to another computer.

3. What is Cookies?
Ans. A cookie is basically small file containing data that is stored by the website on the user’s
hard disk. Cookie identifies users based on information stored in it and prepares web pages
according to user.

4. What is firewall?
Ans. A firewall is software that protects the private network from unauthorized user access. The
firewall filters the information coming from the internet to the network or a computer to protect
the system.
5. What is Hacking?
Ans. Hacking is an attempt to exploit a computer system or a private network inside a com puter
by gaining unauthorized access to data in a system or compute.

6. Differentiate between cracking and hacking.


Ans. Cracking is defined as an attempt to remove the copy protections inserted into software
programs by editing a programs source code, whereas Hacking is gaining unauthorized access
to data in a system or compute.
7. What is cyber crime?
Ans. When any crime is committed over the internet, it is referred to as Cyber Crime.
2 Marks
1. What do you mean by IP Address? How is it useful in Computer
Ans. An IP address is an address assigned to the computer, when it is connected to the network
or internet. During communication over networks, It is used to uniquely identify the computer or
device on the network to route the message to particular device in the network.
2. How are Trojan Horses different from Worms?
Ans. A Worm is a form of malware that replicates itself and can spread to different computers
via Network. While Trojan Horse is a form of malware that capture some important information
about a computer system or a computer network.
Worm doesn’t need a host to replicate from one computer to another. Whereas Trojan
Horse require host is needed for spreading.
3. Define India’s IT Act
Ans. The Information Technology Act 2000 (also known as ITA-2000 or IT Act) is an Act of the
Indian Parliament (No. 21 of 2000) notified on October 17, 2000.
“An Act to provide legal recognition for transactions carried out by means of electronic data
interchange and other means of electronic communication, commonly referred to as ‘electronic
commerce”, which involve the use of alternatives to paper-based methods of communication and
Page : 87
storage of information to facilitate electronic filing of documents with the Government agencies
and further to amend the Indian Penal Code, the Indian Evidence Act 1872, the Banker’s Book
Evidence Act,1891 and the Reserve Bank of India Act,1934 and for matters connected therewith
of incidental thereto.”
3 Marks
1. What is IPR? Explain IPR.
Ans. IPR stands for intellectual property rights which is the right to intangible property such as
music, literature and artistic work created by a person. Intellectual property (IP) is a legal term
that refers to creations of the mind. Intellectual property rights may be protected by p atents,
copyrights, industrial design rights, trademarks, trade dress and, in some jurisdictions, trade
secrets. The owner of intellectual property is the person who has developed the product or the
organization which has funded it. Safeguarding intellectual property from illegal use can be done
by giving some exclusive rights to the owner of that property. These rights also promote
creativity and dissemination and application of its result and encourage fair trading which helps
in developing social and economic areas of a country.
2. Write Characteristics of Virus
Ans.
(a) Speed of a computer system becomes slower than normal.
(b) Computer system frequently hangs up.
(c) Computer restarts automatically after every few minutes.
(d) Various applications of computer do not function properly.
(e) Dialog boxes, menus and other error message windows are distorted.

3. Write Characteristics of Worm


Ans.
(a) It replicates itself.
(b) Unlike virus, worm does not require host and it is self-contained.
(c) It spreads across networks through email, instant messaging or junk mails.
(d) Worms run independently.

5 Marks
1. Explain various types of Cyber Crimes.
Ans. When any crime is committed over the internet, it is referred to as cyber crime. There are
many types of cyber crimes and the most common ones are explained below:

1. Hacking: Gaining knowledge about someone’s private and sensitive information by getting
access to their computer system illegally is known as hacking. This is different from ethical
hacking, which many organizations use to check their internet security protection. In hacking, a
criminal uses a variety of software so as to enter a person’s computer and that person may not
be aware of his computer being accessed from a remote location

2. Cyber Stalking: Cyber stalking is a kind of online harassment where the victim gets unwanted
abusive online messages and emails. Typically, these stalkers know their victims and instead of
resorting to offline stalking, they use the internet to stalk. If they notice that cyber stalking is not
having the desired effect, they begin offline stalking along with cyber stalking to make their
victim’s life miserable.

3. Identity Theft: This has become a major problem with people using the internet for cash
transactions and banking services. In this cyber crime, a criminal accesses data about a
person’s bank account, credit card, social security card, debit card and other sensitive
Page : 88
information to gain money or to buy things online in the victim’s name that can result in major
financial loss for the victim and even spoil the victim’s credit history

4. Malicious Software: These are internet-based software or programs known as pirated


software that are used to disrupt proper functioning of the network. The software is used to steal
sensitive information or data that can cause damage to existing software in a computer system.

5. Electronic Funds Transfer Fraud: A cyber crime occurs when there is a transfer of funds
which may be intercepted and diverted. Valid credit card numbers can be hacked electronically
and then misused by a fraudulent person or organization.

6. Defamation: It involves a cyber crime with the intent of lowering the dignity of someone by
hacking into their email account and sending mails using vulgar language to an unknown
person’s account.

7. Denial of Service (DoS) Attacks: A DoS attack is an attack by which legitimate users of a
computer are denied access or use of the resources of that computer. Generally, DoS attacks do
not allow the attacker to modify or access information on the computer.
Chapter: Introduction to web services
1 Mark
1. URL stands for ______________________
Ans. Uniform Resource Locator

2. What is WWW?
Ans. WWW stands for World Wide Web. It is an information service that can be used for sending
and receiving information over the internet through interlinked hypertext documents.

3. What is spam?
Ans. Spam is an unwanted bulk mail which is sent by an unauthorized or unidentified person in
order to eat the entire disk space. In non-malicious form, it floods the internet with many copies
of the same message to be sent to a user which he may not otherwise receive.
4. What is website?
A website is a collection of various web pages, images, videos, audios or other kinds of digital
assets that are hosted on one or several web servers. The web pages of a website are written
using HTML.

2 Marks
1. Differentiate between HTML and XML
Ans. In HTML, both tag semantics and the tag set are fixed, whereas XML is a meta-language
for describing markup language.HTML is case insensitive, whereas XML is case sensitive.HTML
is used for presentation of the data, whereas XML is used for transfer of information.
2. What is Web Page? Which are its types?
Ans. A web page is an electronic document/page designed using HTML. It displays information
in textual or graphical form.
A web page can be classified into two types:
Static web page: A web page which displays same kind of information whenever a user visits it
is known as a static web page. A static web page generally has .htm or .html as extension.
Dynamic web page: An interactive web page is a dynamic web page. A dynamic web page
uses scripting languages to display changing content on the web page. Such a page generally
Page : 89
has .php, .asp, or .jsp as extension.

3. Define web browser and web server.


Ans. Web Browser: A web browser is a software which is used for displaying the content on
web page(s). It is used by the client to view websites. Examples of web browser—Google
Chrome, Firefox, Internet Explorer, Safari, Opera, etc.
Web Server: A web server is a software which entertains the request(s) made by a web
browser. A web server has different ports to handle different requests from web browser, like
generally FTP request is handled at Port 110 and HTTP request is handled at Port 80. Example
of web server is Apache.

4. Write a sample XML program.


Ans.

3 Marks
1. What is HTTP protocol? Write main features of an HTTP.
Ans. HTTP stands for Hyper Text Transfer Protocol. It is a protocol is used to transfer hypertext
documents over the internet. HTTP defines how the data is formatted and transmitted over the
network. When an HTTP client (a browser) sends a request to an HTTP server (web server), the
server sends responses back to the client.
The main features of an HTTP document are:
1. It is a stateless protocol; this means that several commands are executed simultaneously
without knowing the command which is already executing before another command. 2. It is an
object-oriented protocol that uses client server model. 3. The browser (client) sends request to
the server, the server processes it and sends responses to the client. 4. It is used for displaying
web pages on the screen.
2. Explain Domain Names
Ans.
Domain names make it easier to resolve IP addresses into names, for example, cbse.nic.in,
google.com, meritnation.com, etc.
It is the system which assigns names to some computers (web servers) and maintains a
database of these names and corresponding IP addresses.

A domain name consists of the following parts.


Page : 90
1. Top-level domain name or primary domain name, and
2. Sub-domain name(s).

For example,
In the domain name cbse.nic.in: in is the primary domain name nic is the sub-domain of in cbse
is the sub-domain of nic. The top-level domains are categorized into following domain names:
Generic Domain Names
·com - commercial business
·edu - Educational institutions
·gov - Government agencies
·mil - Military
·net - Network organizations
·org - Organizations (non-profit)
Country Specific Domain Names
.in - India
·au - Australia
·ca - Canada
.ch - China
.nz - New Zealand
.pk - Pakistan
.jp - Japan
.us - United States of America

3. Explain Web Hosting.


Ans.
Web hosting is a service which is provided by companies to its clients to allow them to
construct their own websites which are accessible to the internet users via World Wide Web.
Such companies are known as web hosts. These companies provide space on a web server
they own for use by their clients as well as provide internet connectivity.
The websites which are constructed display information for their organization in the form of
web pages. The host may also provide an interface or control panel for managing the web server
so as to add news and events related to their organization or for uploading some information
which may be valuable for the internet users. A client can also use control panel for installing
scripts as well as other modules and service applications like email. webhostingsitesindia.co.in is
one of the top domain name registration and web hosting companies in India. It is the only
hosting company which provides support in regional languages
Page : 91

Topic : RDBMS & SQL

1 Which command is used to add new column in existing table? 1


Ans. ALTER TABLE
2 Which clause is used to search for NULL values in any column? 1
Ans. IS NULL
3 Which command is used to see information like name of columns, data type, size etc. ? 1
Ans. DESCRIBE OR DESC
4 Which clause is used for pattern matching? What are the 2 main characters used 1
matching the pattern?
Ans. LIKE
% (percent) and _ (underscore)
5 Which clause is used to see the output of query in ascending or descending order? 1
Ans. ORDER BY
6 Which clause is used to eliminate the duplicate rows from output? 1
Ans. DISTINCT
7 What is the minimum number of column required in MySQL to create table? 1
Ans. ONE (1)
8 Which command is used to remove the table from database? 1
Ans. DROP TABLE
9 Which command is used to add new record in table? 1
Ans. INSERT INTO
10 Which option of ORDER BY clause is used to arrange the output in descending order? 1
Ans. DESC
11 Which command is used to change the existing information of table? 2
Ans. UPDATE
12 What is Primary Key? 2
Ans. Primary key is used to uniquely identify each tuple of a relation. Any relation can have only one
primary key.
13 Raj is a database programmer, He has to write the query from EMPLOYEE table to search for the
employee whose name begins from letter „R‟, for this he has written the query as: SELECT *
FROM EMPLOYEE WHERE NAME=‟R%‟;
But the query is not producing the correct output, help Raj and correct the query so that he gets the
desired output. 2
Ans. SELECT * FROM EMPLOYEE WHERE NAME LIKE ‟R%‟;
14 Raj is a database programmer, He has to write the query from EMPLOYEE table to search for the
employee who are not getting any commission, for this he has written the query as: SELECT *
FROM EMPLOYEE WHERE commission=null;
But the query is not producing the correct output, help Raj and correct the query so that he gets the
desired output. 2
Ans. SELECT * FROM EMPLOYEE WHERE commission IS null;
15 Raj is a database programmer, has to write the query from EMPLOYEE table to search for the
employee who are working in „Sales‟ or „IT‟ department, for this he has written the query as:
SELECT * FROM EMPLOYEE WHERE department=‟Sales‟ or „IT‟;
But the query is not producing the correct output, help Raj and correct the query so that he gets the
desired output. 2
Ans. SELECT * FRO M EMPLOYEE WHERE department=‟Sales‟ or departmen t=„IT‟; OR
SELECT * FROM EMPLOYEE WHERE department IN (‘Sales’,’IT’)
Page : 92

16 The following query is producing an error. Identify the error and also write the correct query. SELECT *
FROM EMP ORDER BY NAME WHERE SALARY>=5000; 3
Ans. As per MySQL, ORDER BY must be the last clause in SQL QUERY, and in this query ORDER BY is
used before WHERE which is wrong, the correct query will be:
SELECT * FROM EMP WHERE SALARY>=5000 ORDER BY NAME;
17 If Table Sales contains 5 records and Raj executed the following queries; find out the output of both
the query.
(i) Select 100+200 from dual;
(ii) Select 100+200 from Sales; 3
Ans. (i) 300
(ii) 300
300
300
300
300
18 What is the difference between Equi-Join and Natural Join? 3
Ans. In Equi join we compare value of any column from two tables and it will return matching rows. In Equi-
join common column appears twice in output because we fetch using (*) not by specifying column
name. for e.g.
In Equi-join it is not mandatory to have same name for column to compare of both table In natural
join also the matching rows will return. In natural join column will appear only
once in output. Then name of column must be same in both table if we are performing natural join
using the clause NATURAL JOIN.
19 Observe the given Table TEACHER and give the output of question (i) and (ii)
TEACHER_CODE TEACHER_NAME DOJ
T001 ANAND 2001-01-30
T002 AMIT 2007-09-05
T003 ANKIT 2007-09-20
T004 BALBIR 2010-02-15
T005 JASBIR 2011-01-20
T006 KULBIR 2008-07-11
(i) SELE CT TEA CHE R_NA ME,DOJ F RO M TEA CHE R WHE RE TEA CHE R_NA ME LIKE „%I% ‟
(ii) SELE CT * F RO M TEA CHER W HE RE DOJ LIKE „% -09- % ‟; 3
Ans (i)
TEACHER_NAME DOJ
-------------------------------------------------------
AMIT 2007-09-05
ANKIT 2007-09-20
BALBIR 2010-02-15
JASBIR 2011-01-20
KULBIR 2008-07-11
(ii)
TEACHER_CODE TEACHER_NAME DOJ
----------------------------------------------------------------------
T002 AMIT 2007-09-05
T003 ANKIT 2007-09-20

20 Which SQL function is used to get the average value of any column? 2
Ans. AVG()
21 What is the difference between COUNT() and COUNT(*) function 3
Ans. COUNT() function will count number of values in any column excluding the NULLs
COUNT(*) will count number of rows in query output including NULLs
Page : 93
22 What is the full form of SQL? 1
Ans. Structured Query Language
23 Query to delete all record of table without deleting the table:
a. DELETE TABLE TABLE_NAME
b. DELETE FROM TABLE_NAME
c. DROP TABLE TABLE_NAME
d. DELETE TABLE FROM TABLE_NAME 2
Ans. b. DELETE FROM TABLE_NAME
24 Identify the wrong statement about UPDATE command
a. If WHERE clause is missing all the record in table will be updated
b. Only one record can be updated at a time using WHERE clause
c. Multiple records can be updated at a time using WHERE clause
d. None of the above 2
Ans. b. Only one record can be updated at a time using WHERE clause
25 Identify the correct statement(s) to drop a column from table
a. DELETE COLUMN COLUMN_NAME
b. DROP COLUMN COLUMN_NAME
c. ALTER TABLE TABLE_NAME DROP COLUMN COLUMN_NAME
d. ALTER TABLE TABLE_NAME DROP COLUMN_NAME 3
Ans. c. ALTER TABLE TABLE_NAME DROP COLUMN COLUMN_NAME
d. ALTER TABLE TABLE_NAME DROP COLUMN_NAME
26 Suppose a table BOOK contain columns (BNO, BNAME, AUTHOR, PUBLISHER), Raj is assigned a
task to see the list of publishers, when he executed the query as:
SELECT PUBLISHER FROM BOOK;
He noticed that the same publisher name is repeated in query output. What could be possible solution to
get publisher name uniquely? Rewrite the following query to fetch unique
publisher names from table. 4
Ans. Solution is to use DISTINCT clause.
Correct Query : SELECT DISTINCT PUBLISHER FROM BOOK;
27 HOTS
Consider a database table T containing two columns X and Y each of type integer. After the creation of
the table, one record (X=1, Y=1) is inserted in the table.
Let MX and MY denote the respective maximum values of X and Y among all records in the table at any
point in time. Using MX and MY, new records are inserted in the table 128 times with X and Y values
being MX+1, 2*MY+1 respectively. It may be noted that each time after the insertion, values of MX and
MY change. What will be the output of the following SQL query after the steps mentioned above are
carried out?
SELECT Y FROM T WHERE X = 7
A. A . 127
B. 255
C. 129
D. 257 4
Ans. A. 127
28 Which SQL function is used to find the highest and lowest value of numeric and date type
column? 4
Ans. MAX() and MIN()
29 What is the default order of sorting using ORDER BY? 2
Ans. Ascending
30 What is the difference between CHAR and VARCHAR? 4
Page : 94
Ans. CHAR is fixed length data type. For example if the column „name‟ if of CHAR(20) then all name will
occupy 20 bytes for each name irrespective of actual data.
VARCHAR is variable length data type i.e. it will occupy size according the actual length of data
Page : 95
INTERFACE PYTHON WITH SQL

Functions to execute SQL queries

# CREATE DAT ABASE


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user=
"root",passwd="12345") mycursor=mydb.cursor()
mycursor.execute("CREATE DATABASE SCHOOL")

# SHOW DAT ABASE import mysql.connector


mydb=mysql.connector.connect(host="localhos
t",user="root",passwd="12345")
mycursor=mydb.cursor()
mycursor.execute("SHOW DATABASE") for x in
mycursor:
print (x)

# CREATE TABLE
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",
database="student")
mycursor=mydb.cursor()
mycursor.execute("CREATE TABLE FEES (ROLLNO INTEGER(3),NAME
VARCHAR(20),AMOUNT INTEGER(10));")

# SHOW T ABLES
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd=
"12345",database="student") mycursor=mydb.cursor()
mycursor.execute("SHOW TABLES") for x in
mycursor:
print(x)

# DESCRIBE TABLE
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",
database="student")
mycursor=mydb.cursor()
mycursor.execute("DESC STUDENT")
for x in mycursor:
print(x)
# SELECT QUERY
import mysql.connector
conn=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="stu
dent")
Page : 96
c=conn.cursor()
c.execute("select * from student") r=c.fetchone()
while r is not None: print(r) r=c.fetchone()

#WHERE CLAUSE
import mysql.connector
conn=mysql.connector.connect(host="localhost",user="root",passwd="12345",
database="student")
if conn.is_connected==False:
print("Error connecting to MYSQL DATABASE")
c=conn.cursor()
c.execute("select * from student where marks>90")
r=c.fetchall()
count=c.rowcount
print("total no of rows:",count)
for row in r:
print(row)
# DYNAMIC INSERTION
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",
database="student") mycursor=mydb.cursor()
r=int(input("enter the rollno")) n=input("enter name") m=int(input("enter marks"))
mycursor.execute("INSERT INTO student(rollno,name,marks) VALUES({},'{}',{})".format(r,n,m))
mydb.commit()
print(mycursor.rowcount,"RECORD INSERTED")

# UPDATE COMMAND
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",
database="student")
mycursor=mydb.cursor()
mycursor.execute("UPDATE STUDENT SET MARKS=100 WHERE MARKS=40")
mydb.commit()
print(mycursor.rowcount,"RECORD UPDATED")

# DELETE COMMAND
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",
database="student") mycursor=mydb.cursor()
mycursor.execute("DELETE FROM STUDENT WHERE MARKS<50") mydb.commit()
print(mycursor.rowcount,"RECORD DELETED")

# DROP COMMAND

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",
Page : 97
database="student")
mycursor=mydb.cursor()
mycursor.execute("DROP TABLE STUDENT")

# ALTER COMMAND import mysql.connector


mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",
database="student")
mycursor=mydb.cursor()
mycursor.execute("ALTER TABLE STUDENT ADD GRADE CHAR(3)")

SN QUESTIONS/ANSWERS MARKS
ALLOTED
Q1 What is database. 1
Ans The database is a collection of organized information that can easily be used,
managed, update, and they are classified according to their organizational
approach
Q2 Write command to install connector 1
Ans pip install mysql-connector-python
Q3 Write command to import connector. 1
Ans import mysql.connector
Q4 What is MySQLdb? 1
Ans MySQLdb is an open-source freely available relational database management
system that uses Structured Query Language.
Q5 What is resultset? 1
Ans Result set refers to a logical set of records that are fetched from the database
by executing a query.
Q6 What is database cursor? 1
Ans Database cursor is a special control structure that facilitates the row by row
processing of records in the result set
Q7 What is database connectivity? 1
Ans Database connectivity refers to connection and communication between an
application and a database system.
Q8 Which function do use for executing a SQL query? 1
Ans Cursor. execute(sql query)
Q9 Which package must be imported to create a database connectivity 1
application?
Ans Mysql.connector
Q10 Differentiate between fetchone() and fetchall() 1
Ans fetchone() − It fetches the next row of a query result set. A result set is an
object that is returned when a cursor object is used to query a table.
fetchall() − It fetches all the rows in a result set. If some rows have already
been extracted from the result set, then it retrieves the remaining rows from
the result set.
Q11 How we can import MYSQL database in python? 1
Page : 98
Ans Use the mysql.connector.connect() method of MySQL Connector Python with
required parameters to connect MySQL. Use the connection object returned
by a connect() method to create a cursor object to
perform Database Operations. The cursor.execute() to execute SQL queries
from Python.
Q12 write the steps of connectivity between SQL and Python. 2
Ans import,connect,cursor,execute

Q13 What is result set? Explain with example. 2


Ans Fetching rows or columns from result sets in Python. The fetch
functions in the ibm_db API can iterate through the result set. If your
result set includes columns that contain large data (such as BLOB or
CLOB data), you can retrieve the data on a column-by-column basis to
avoid large memory usage.
Q14 Use of functions in connectivity - INSERT, UPDATE, DELETE, 2
ROLLBACK
Ans It is an SQL statement used to create a record into a
INSERT table.

It is used update those available or already existing


UPDATE record(s).

DELETE It is used to delete records from the database.

It works like "undo", which reverts all the changes that you
ROLLBACK have made.

Q15 Write code for database connectivity 2


Ans # importing the module
import mysql.connector
# opening a database connection
conn = mysql.connector.connect ("localhost","testprog","stud","PYDB")
# define a cursor object
mycursor = conn.cursor
# drop table if exists
mycursor.execute("DROP TABLE IF EXISTS STUDENT”)
Page : 99
# query
sql = "CREATE TABLE STUDENT (NAME CHAR(30) NOT NULL,
CLASS CHAR(5), AGE INT, GENDER CHAR(8), MARKS INT)"
# execute query
cursor.execute(sql)
#close object
cursor.close()
#close connection
conn.close()
Q16 Which method is used to retrieve all rows and single row? 2
Ans Fetchall(),fetchone()
Q17 Write python-mysql connectivity to retrieve all the data of table student. 2
Ans import mysql.connector
mydb=mysql.connector.connect(user="root",host="localhost",passwd="
123", database="inservice")
mycursor=mydb.cursor()
mycursor.execute("select * from student")
for x in mycursor:
print(x)
Q18 Write a query to rename the name of the artist from Towang to 2
Tauwang.
Ans updateSql = "UPDATE Artists SET NAME= 'Tauwang' WHERE ID = '1' ;"
cursor.execute(updateSql)
Q19 Write a query to delete an entity from the table Artists whose id is 1 2
Ans deleteSql = "DELETE FROM Artists WHERE ID = '1'; "
cursor.execute(deleteSql)
Q20 Write a small python program to insert a record in the table books with 2
attributes (title ,isbn).
Ans import mysql.connector as Sqlator
con = sqlator.connect(host=”localhost”,user=”root”,passwd=””,
database=”test”)
cursor=con.cursor()
query=”INSERT into books(title,isbn)
values(‘{}’{})”.format(‘Neelesh’,’5143’)
cursor.execute(query)
con.close()
Q21 Write a small python program to retrieve all record from the table 2
books with attributes (title ,isbn).
Ans import mysql.connector as Sqlator
conn =sqlator.connect(host=”localhost”,user=”root”,passwd=””,
database=”test”)
cursor=con.cursor()
query=”select * from query”
cursor.execute(query)
data=cursor.fetchall()
for row in data:
print(row)
conn.close()
Page : 100

CBSE
CLASS12

SET OF 2 SAMPLE PAPERS

COMPUTER SCIENCE

 BASED ON LATEST PATTERN AS


PER CBSE SAMPLE QUESTION
PAPER
 INCLUDES CASE BASED QUESTIONS
 ALONG WITH DETAILED SOLUTIONS
Page : 101

CBSE SAMPLE PAPER-01 (2020-21)

Class 12 Compute r Science

Max im um Marks : 70
Time Allowe d: 3 hours

Ge ne ral I ns tructions:
1. T his ques tion paper c ontains tw o parts A and B. Eac h part is c ompuls ory.
2. Both Part A and Part B have c hoic es.
3. Part-A has 2 s ec tions :
a. Sec tion – I is s hort ans w er ques tions , to be answ ered in one w ord or one line.
b. Sec tion – II has tw o c as e s tudy ques tions. Eac h c as e s tudy has 4 c as e-bas ed s ubparts.
An examinee is to attempt any 4 out of the 5 subparts .
4. Part - B is the Desc riptive Paper.
5. Part- B has three s ections
a. Sec tion-I is s hort answ er ques tions of 2 marks eac h in w hic h tw o ques tions have
int erna l opt ions .
b. Sec tion-II is long answ er ques tions of 3 marks eac h in w hic h tw o ques tions have
int erna l opt ions .
c. Sec tion-III is very long ans w er ques tions of 5 marks eac h in w hic h one ques tion has
a n interna l opt ion.
6. All programm in g ques tions are to be ans w ered us ing Python Lan guag e only

Part-A

(Se ction -I )

Atte mpt any 15 Que stions from Ques tions 1 to 21.

1. You have the follow ing c ode s egment:


String1 = "my"

String2 = "work"
print(String1 + String2. upper())
Wha t is the output of this c ode?

a. My Work

b. m yw or k

c. myWORK
Page : 102

d. MY Work

2. Wh at w ill the follow ing func tion return?


def addEm(x, y, z):
print(x + y + z)

3. Wh at does the rmdir () method do?

4. What is the output of s ys. platform [:2] if the c ode runs on w indow s operating s ys tem?
a. 'w i'

b . Error

c. 'op'

d. 's y'

5. T o open a file c :\res .txt for reading, w e c an us e (s elect all c orrec t options):

a. file = open("c : \res.txt", "r")


b. file = open("c :\ \res.txt", "r")
c. file = open(r"c : \res. txt", "r")

d. file = open(file = "c :\res. txt", "r")


e. file = open(file = "c :\ \res. txt", "r")
f. file = open("c :\ \res .txt")

a. d, e, f
b. a, e, f
c. b, d, f
d. b, c, f

6. How c an w e find the na mes that are defined ins id e the c urrent modu le ?

7. What is Connec tion? What is its role?

8. How is module names pac e organized in a Pac kage?

9. What is the output of the follow ing?


dry = {0: 'a', 1: 'b', 2: 'c'}
for x, y in dry. items ():
print(x, y, end = ' ' )

10. Whic h variables have globa l sc ope?

1 1. W h en w o u ld yo u g o for lin ear s earc h in an array an d w h en for binary s earc h?

12. Write a query to dis play the Sum, Average, Highes t and Low es t s alary of the
employees .

1 3. W h at are lin ear data s truc tures ?


Page : 103

14. Cons ider the table w ith s truc ture as :


Student(ID, name, dept name, tot_cred) Wh ic h
attribute w ill form the primary key?

a. Dept

b. ID

c. T otal c redits

d. N am e

15. Identify the Domain name and UR L from the follow ing:
http ://w w w . inc ome. in/hom e. abou tus . htm

16. SQL applies conditions on the groups through ________ c laus e after groups have been
formed.

a. Wh er e

b. Group by

c. Having

d. With

17. W ha t is databas e c onnec tivity?

18. What is the us e of w ildc ard?

19. Wh at is a repeater?

20. What is MySQLdb?

21. The c hecks um of 1111 and 1111 is ________.

a. 0000

b. 1111

c . 1110

d. 0111
Page : 104

Se ction-II (Case study bas e d Ques tions )

22. Give output for follow ing SQ L queries as per given table(s ):

Table: GRADUAT E
S.NO. NAME STIPEND SUBJECT AVERAGE DIV

1. KARAN 400 PHYSICS 68 1

2. DIVAKAR 450 COMPUTER SC 68 1

3. DIVYA 300 CHEMISTRY 62 2

4. ARUN 350 PHYSICS 63 1

5.
SABINA 500 MAT HEMATICS 70 1

6. JOHN 400 CHEMISTRY 55 2

7. ROBERT 250 PHYSICS 64 1

8. RUBINA 450 MAT HEMATICS 68 1

9. VIKAS 500 COMPUTER SC 62 1

10. MOHAN 300 MAT HEMATICS 57 2

i. SELECT MIN (AVERAGE) FROM GRADUATE


WHERE SUBJECT = "PHYSICS";
ii. SELECT SUM(STIPEND) FROM GRADUATE WHERE DIV = 2;
iii. SELECT AVG(STIPEND) FROM GRADUATE WHERE AVERAGE >= 65; iv.
SELECT COUNT (distinct SUBJ ECT) FROM GRADUAT E;
v. Write c ode to rename a table in S Q L

23. If the file ' poemBT H. txt' c ontains the follow ing poem (by Paramhans Yoganand) :
G od made the Earth; Man-m ade
c onfining c ountries
An d their fanc y-frozen boundaries .
But w ith unfound boundles s Love
I behold the borderla nd of m y India
Exp and ing into the World.
Ha il, mother of religions , Lotus, sc enic beauty and s ages!
W ha t outputs w ill be produc ed b y both the c ode fragments given be low :

i. What outputs w ill be produc ed by the c ode fragment given be low :


my_file =open(' poemBT H. txt', 'r')
my_file. read()
ii. Wh at outputs w ill be produc ed b y the c ode fragment given be low :
Page : 105

my_file = open(' poemBT H. txt', ' r')


my_file. read(100)
iii. A __________ s ymbol is us ed to perform reading as w ell as writing on files in
python.
iv. T o open file data. txt for reading, open function w ill be written as f = _______.

v. T o open file data.txt for writing, open func tion w ill be written as f = ________.
Part – B (Se ction-I )
24. Write a program that rotates the elem ents of a lis t s o that the elem ent at the firs t index
moves to the s ec ond index, the element in the s ec ond index m ov es to the third index, etc.,
and the element in the las t index m ov es to the firs t index.

25. What is Phis hing? Explain w ith examples .


OR
Give the full form for the follow ing:
i. FM
ii. AM
iii. NFS
iv. FTP

26. What do you mean by IP Addres s ? How is it us eful in Computer Sec urity?
27. Differentiate betw e en fruitful func tions and non-fruitful func tions .
OR
Predic t the output of the follow ing c ode: a =
10

y=5

def myfunc ():


y=a

a=2

print "y =", y , ", a =", a


print "a + y = ", a + y
return a + y

print "y =", y, "a =", a


print myfunc ()

print "y =", y, "a =", a


28. Write a program that reads an integer N from the keyboard c omputes a nd dis plays
Page : 106

the s um of the numbers from N to (2 * N) if N is nonnegative. If N is a negative number,


then it's the s um of the numbers from (2 * N) to N. T he s tarting and ending po ints are
inc lud ed in the s um.

29. Explain the Sc ope of Variables .


30. Mr. Mittal is us ing a table w ith follow ing c olumns :

Name, Clas s , Streamed, Stream_name

He needs to dis play names of s tudents w h o have not been as s igned any s tream or ha v e
b e en

as s igned s tre am_ nam e that ends w ith "c omputers

He w rote the follow ing c omma nd, w hic h did not give the des ired result.
SELEC T Name , Class FROM Students

WHER E Stre am_name = NULL OR Stre am_name = “%compute rs ” ;

He lp Mr. M itta l to run the query b y remov ing the error a nd w rite c orrec t query.
31. W ha t are data types ? W ha t are the main objec tiv es of datatypes ?
32. W ha t do you unders tand by Degree and Cardina lity of a table?
33. Find the errors in follow ing c ode and w rite the c orrec t c ode.

if v < 5:

for j in range(v):

print "ABC"

els e:

print "XYZ"
i. Under lin e the c orrec tions

ii. Write the reas on!error next to it in c omm en t form.

Se ction- I I
34. Create file phonebook. dat that s tores the details in follow ing format:
N a m e P h on e
J ivin 86666000
Kriti 1010101
Page : 107
Obta in the details fro m the us er.

3 5. Write a func tion w h ic h takes tw o s tring arguments an d returns the s tring c ompar is on

res ult of the tw o pass ed s trings .


OR
Write a program that reads a date as an integer in the format M M DD YYYY. T he
program w ill c all a func tion that prints print out the date in the format < Mo nth
Name><day>, <year>.

Samp le run :

Enter date: 12252019


Dec ember 25, 2019

36. What is a pac kage? Ho w is a pac kage different from the module?

37. Fro m the program c ode given below , identify the parts mentioned be low :

1. def proc es s Number(x):

2. x = 72

3. return x + 3

4.

5. y = 54

6. res = proc es s Number(y)

Identify thes e parts : func tion header, func tion c all, arguments , parameters , func tion body,
m a in program.

Se ction-II I

38. Uplifting Skills Hu b India is a know ledge and s kill c ommunit y w hic h has an aim to uplift
the s tandard of know ledg e and s kills in s oc iety. It is plann ing to s et up its training c entres
in mult ip le tow ns and villages pan India w ith its head offic es in the neares t c ities . T hey
have c reated a model of their netw ork w ith a c ity, a tow n, and 3 villages as follows.

As a netw ork c ons ultant, yo u have to s ugges t the bes t netw ork related s olutions for their
is s ues / problems rais ed in (i) to (iv) keeping in min d the dis tanc e betw een var ious
loc at ions a n d given param eters .
Page : 108

Th e shortes t dis tance be twe e n various location:

VILLAGE 1 to B_TOWN 2 KM

VILLAGE 2 to B_TOWN 1.0 KM

VILLAGE 3 to B_TOWN 1.5 KM

VILLAGE 1 to VILLAGE 2 3.5 KM

VILLAGE 1 to VILLAGE 3 4.5 KM

VILLAGE 2 to VILLAGE 3 2.5 KM

A_CIT Y Head Office to B_HUB 25 KM

T he number of Computers ins talled at various loc ations is as follow s :

B_TOWN 120

VILLAGE 1 15

VILLAGE 2 10

VILLAGE 3 15

A_CITY Head OFFICE 6

Note :
In Villages , there are c ommunit y c enters , in w hic h one room has been given as a
train ing c enter for this organiza t ion to ins tall c omputers .

T he organiz at ion has got financ ia l s upport from the government an d top IT
c ompan ies .

i. Suggest the mos t appropriate loc ation of the SERVER in the B_ HUB (out of the 4

loc ations ), to get the bes t and effec tive c onnec tivity. J us tify your answ er.
Page : 109

ii. Sugges t the bes t-w ired me d ium and draw the c able layout (loc ation to loc ation) to

effic iently c onnec t various loc ations w ithin the B_ HUB.

iii. Wh ic h hardw are devic e w ill you s ugges t to c onnec t all the c omputers w ithin eac h

loc ation of B_HUB?

iv. Whic h s ervic e/protoc ol w ill be mos t helpful to c onduc t live interac tions of Experts

from Head Offic e and people at all loc ations of B_ HUB?

39. Cons ider the follow ing tables ST ORE and SUPPLIERS and answ er (a) and (b) parts of

this ques tion :


Table: STORE

I temNo I te m Scode Qty Rate LastBuy

2005 Sharpener Clas s ic 23 60 8 31-Jun-09

2003 Ball Pen 0. 25 22 50 25 01-Feb-10

2002 Gel Pen Premium 21 150 12 24-Feb-10

2006 Gel Pen Class ic 21 250 20 11-Mar-09

2001 Eras er Small 22 220 6 19-J an-09

2004 Eras er Big 22 110 8 02-Dec-09

2009 Ball Pen 0. 5 21 180 18 03-Nov-09

Table: SUPPLI ERS

Scode Sname

21 Pr em ium Stationers

23 Soft Plas tics

22 T etra Supply
a. Write SQ L c ommands for the follow ing s tatements :

i. T o dis play details of all the items in the ST O RE table in as c ending order of
Page : 110

Las tBuy.

ii. T o dis play ItemNo and Item name of thos e items from ST OR E table w hos e Rate

is more than 15 Rupees .

iii. T o dis play the details of thos e items w hos e s upplier c ode (Sc ode) is 22 or

Quantity in Store (Qty) is more than 110 from the table Store.

iv. T o dis play m in imu m Rate of items for eac h s upplier indiv idua lly as per Sc ode

from the table ST ORE.

b. Give the output of the follow ing S Q L queries :

i. SELECT COUNT(DISTINCT Scode) FROM STORE;

ii. SELECT Rate* Qty FROM STORE WHERE ItemNo = 2004;

iii. SELECT Item, Sname FROM STORE S, Suppliers P WHERE S. Scode= P. Scode

AND ItemNo = 2006;

iv. SELECT MAX(LastBuy) FROM STORE;


40. Write a program to perform ins ert an d delete operat ions o n a Q ue ue c ontain ing

Mem bers details as given in the follow ing definit ion of itemnode :

MemberN o integer

M e mb erName String

Age integer
Page : 111

OR
Determ in e the total m em ory c ons umption b y follow ing the s equenc e. Lis t1
= [40, 45, "Ekta"]

i. exc ludin g m em ory c ons umption b y ac tual data

ii. inc luding m e m or y c ons umption by ac tual data


Page : 112

12 Compute r Science Sample Pape r -01

Class 12 - Compute r Science

Solut ion

Part -A (Se ction-I ) Attempt any 15 Ques tions

1. (c) myWORK

Explanat ion : m yW O R K, String2. upper() w ill c onvert all the charac ters of a s tring to Upper
Cas e.

2. None objec t w ill be returned, (no return s tatement).


3. T h e rmdir() method delet es an empty direc tory, w h ic h is pas s ed as an argument in the
method. Before remo v ing a direc tory, all the c ontents in it s hould be deleted, i. e. direc tory
s hould be empty. OSError w ill be rais ed if the s pec ified path is not an empty direc tory.

4. (a) 'w i'

Explanat ion: w indow s [:2] = 'w i'

5. (d) b, c, f

Exp lanat ion :

In file path, ' \r' is a c arriage return c harac ter, to normalis e it w e us e another /
before it or us e 'r' prefix before the file path.

W e do not need to mention the file keyw ord to input the file path in open
func tion.

6. T he names defined ins id e a c urrent modu le c an be found by us ing dir () func tion.
7. A Connec tion (repres ented through a c onnec tion objec t) is the s ess ion betw een the
applic at ion progr am a nd the databas e. T o do anything w it h the databas e, o n e mus t have a
c onnec tion objec t. For c onnec tion Python module P y MyS Q L is installed proper ly o n your
mac h in e.

8. Mod u le names pac e is organ ized in a hierarc hic al s truc ture us ing dot notation.

9. 0 a 1 b 2 c
Page : 113

10. T he variables that are defined outs ide every func tion(loc al s c ope) in the program have a
globa l s c ope. T hey c an be acc ess ed in the w hole program anyw her e (inc lud ing ins ide
func tions ).

11. W he n the array is uns orted liner s earc h is us ed Binary s earc h is performed in a

s orted arr ay.

12. mysql > SELECT SUM (sal), AVG (sal), M AX (sal), MIN (sal) FROM empl;

13. T hes e are data s truc tures w hos e eleme nts form a s equenc e e. g. Stac k, queue and

linked lis ts .

14. (b) ID

Explanat ion : ID, A primary key is a key that is unique for eac h rec ord.

1 5. Do ma in na me : inc ome. in

UR L : http://www . inc ome. in/home. aboutus. htm

16. (c) Having

Explanation: T he HAVI NG c laus e is c los ely ass oc iated w ith the GROUP BY c laus e.

17. A Databas e c onnec tion is a fac ility that allow s c lient s oftw are to talk to databas e

s erver s oftw are, w hether o n the s am e m ac h ine or not.

18. T he w ildc ard c harac ter is us ed to s ubs titute one or mor e c harac ters in a s tring.
Page : 114
T hey are us ed w ith the LI KE operator to s earc h a value s imilar to a s pec ific pattern in a
c olumn. T here are 2 w ildc ard operators .

% - repres ents 0, 1 or ma ny c harac ters

— repres ents a s ingle n u mb er or c harac ter.

19. A repeater is an elec tronic devic e that rec eives a s ignal, amplifies it and then

retrans mits it o n the netw ork s o that the s igna l c an c over longer dis tanc es .

20. MyS Q Ld b is an interfac e for c onnec ting to a M ySQ L databas e s erver from Python. It

implements the Python Databas e API v2. 0 and is built on top of the MyS Q L API.

21. (a) 0000

Explanat ion : 0000, 1’s c omplem ent arithmet ic to get the s um.

Se ction-II (Case study bas e d Ques tions )

22. i. MIN (AVERAGE)

63

ii. SUM(STIPEND)

1000

iii. AVG(STIPEND)

450

iv. COUNT (distinct SUBJ ECT)

v. EXE C s p_rename ' old_table_name', 'new _table_name'

23. i. my_file =open(' poemBT H. txt' , 'r') w ill open the given file in read mode

and my_file. read() read the entire file in s tring form.

ii. my_file = open(' poemBT H. txt' , 'r') w ill open the given file in read mode
Page : 115

and my_file. read(100) read only the first 100 bytes from the file and s tore the read bytes
in form of a s tring.

iii. +

iv. open(“data. txt”, ”r”) v.


open(“data. txt”, ”w”)

Part – B (Se ction-I )

24. lis = eval(input ("Enter lis t:"))

last = lis[-1]

for i in range(len(lis) -1, 0, -1):

lis[i] = lis[i - 1]
lis [0] = last
print(lis )

25. Phis hing is fraudulent attempts b y c yberc rimina ls to obtain privat e informat ion. For e. g. a
m es s ag e prompt your pers ona l informat ion b y pretending that the ban k/ma il s ervic e
provid er is updating its w ebs ite. T here are various phis h ing tec hniqu es us ed b y attac kers :

E mb ed d ing a link in an ema il to redirec t to an uns ec ured w ebs ite that reques ts
s ens itive inform at io n

Ins talling a T rojan via a malic ious email attac hment

poof ing the s ender’s addres s in an email to appear as a reputable s ourc e and reques t
s ens it ive inform at io n

At tempt ing to obtain informa t ion over the phon e b y impers onat ing a kn ow n
c o mp an y vendor.

OR
i. F M: Frequenc y Modulation

ii. AM: Amplitude Modulation


iii. NFS: Netw ork File Server iv.
F TP: File Transfer Protocol

26. An Internet Protoc ol (IP) address is a numeric al ident ific ation and log ic al addres s that is
as s igned to devic es c onnec ted in a c omputer netw ork. An IP addres s is us ed to uniquely
Page : 116
ident ify dev ic es on the internet and s o one c an quic kly k n ow the loc ation of the s ys tem in
the netw ork.

In a netw ork, every mac hin e c an be identified b y a unique IP addres s as s oc iated w ith it and
thus help in provid ing netw ork s ec urity to every s ys tem c onnec ted in a n e tw ork.

27. Fruitful function - T he func tions that return a value i. e., non-void func tions are als o
k now n as fruitful func tions .

No n - fruitful function - T he func tions that do not return a value, i. e., void func tions are
als o k now n as non-fruitful func tions .

OR
Output of the c ode is :
N a me a not defined.

Sinc e, a w as dec lared after its us e in myfunc () func tion a = 2 is dec lared, after the
s tatement y = a, res ulting in the not defined error.

28. N = int(input("Enter N: "))

step = N // abs(N)
s um = 0

for i in range(N, 2*N + s tep, s tep):


s um += i
print(s um)
29. All variables in a program m ay not be acc ess ible at all loc ations in that program. T his
depen ds on the loc ation of the dec laration of the variable. T he sc ope of a variable
determ in es the region of the program w her e you c an acc es s a partic ular identif ier. If a
variab le is acc es s ed outs ide the sc ope, Python gives an error of "variab le_n ame is not
define d".

T here are tw o bas ic sc opes of variables in Python :


i. Globa l var iab les that are acc ess ib le throughout the progr am anyw h ere ins ide a ll
func tions have global s c ope.
ii. Loc al variab les that are acc ess ible on ly ins ide the func tion w here they are
dec lared, have loc al sc ope.
30. T he given query is erroneous bec aus e it involv es pattern matc hing.
T he c orrec t operator to be us ed for pattern matc hing is LI KE. Als o, there is N UL L
c omparis on and for it als o inc orrec t operator is us ed. T h e c orrec t operator for N UL L
c omparis on is IS. T hus, the c orrec t S Q L s tatement w ill be :

SEL EC T Name, class FROM s tudents WHER E Stre am-name I S NULL OR Stre am- name
LI KE "%compute rs " ;
Page : 117
31. Data types are the c lass ific ation of data items . Data types repres ent a kind of value w hic h
determ in es w ha t operations c an be performed o n that data. So m e c o mm on data types
are Integer, Float, Varc har, Char, String, etc .

Ma in objec tives of datatypes are:


i. Optimu m us age of s torage s pac e

ii. Repres ent all poss ible va lues

iii. Improve data integr ity

32. De gree . T h e number of c olumns or attributes or fields in a relation/table is c alled the

table' s degree.

Cardinality. T h e number of rows /tuples /rec ord in a relation/table is c alled the table' s
c ardinality. For example, for a table s how n below :

BookNo. Name Author Pric e

B01 Good learning Xion Z. 220

B02 Smile eas y T. Singh 350

B03 I to U S. Sandeep 250

Its degree is 4 (4 c olumns )


Cardinality is 3 (3 row s)

33. v = 3 # v mus t be defined before being us ed

if v < 5:

for j in range(v):

print(' ABC ") # () miss ing for print()

els e : # w ron g indentation; e ls e c laus e c an either be for if # or


for for loop

print ( "XYZ ” ) # () miss ing for print()


Se ction- I I
34. T his program is us ed to create a file and s tore the data in that file:
Page : 118
fp1 = open("phonebook. dat", 'w' )
fp1.w rite ("Name")

fp1.write (" ")


fp1.w ite ("Phone")
fp1. write ("\n")
w hile T rue :

name = raw _input ("Enter name:") phno


= raw _input ("Enter phone no:")

fp1. w rite ( n a m e)
fp1.write (" ")

fp1. write ("phno ")


fp1.w rite ("\n")

c h = raw _Input ("Want to enter more=y/n") if


ch == 'N’ OR ch == 'n’:

b re a k

fp1.c los e()

35. def s tringCompare(s tr1, str2):

if s tr1. length() != s tr2. length() :

return F a ls e

els e:

for i in range (s tr1. length()):

if s tr1[i] != str2[i]:

r et ur n F a ls e
els e:

return T r u e
firs t_s tring = raw_input("Enter Firs t s tring:")
s econd_s tring = raw _input("Enter Sec ond string:") if
s tringCompare(first_string, s ec ond_s tring):

print ("Given Strings are s ame. ")

els e:
Page : 119

print ("Given Strings are different. ") OR

date = input ("Enter date in MMDDYYYY format: ") def


prettyPrint(date):

months ={1: 'J anuary', 2: 'February', 3: ' March' , 4: ' April', 5: ' May', 6: 'J une', 7: 'J uly', 8:

' Augus t', 9: 'September', 10: ' October' , 11: ' November', 12: ' Dec ember' }

month = months [int(date[:2])]


day = date[2:4]

year = date[4:]

prettyDate = month + " " + day + ", " + year


print( prettyD ate)

print(prett yPrint(dat e))

36. A module in python is a . py file that defines one or more func tion/c las s es w hic h you

intend to reus e in different c odes of your program. T o reus e the func tions of a given

modu le, w e s imp ly nee d to import the module us ing the import c o mma nd.

A Python pac kage is a c ollec tion of python modules under a c omm on names pac e c reated b y
plac ing different modules on a direc tory along w ith s ome s pec ial files . T his feature c omes in
handy for organiz ing modu les of one type in one plac e.

37.

Func tion he ad er def proc es s Number(x) : in line 1

Func tion c all proc es s Number (y) in line 6

Argum ents y in line 6

P ara m eters x in line 1

x = 72
Func tion body in lines 2 and 3

return x + 3
y = 54
M a in program in lines 5 and 6

res = proc ess Number(y)


Page : 120
Se ction-II I

38. i. B-T O WN c an hous e the s erver as it has the ma x imu m no. of c omputers .

ii. T he optic al fiber c able is the bes t for this s tar topology.

iii. Sw itc h devic e - c onnecting all the c omputers w ithin eac h loc ation of B_ HUB iv.
VoIP- Voic e Over Internet Protoc ol

39. a. i. SELECT * FROM STORE ORDER BY LastBuy;

ii. SELECT ItemNo, Item FROM ST ORE WHERE Rate > 15;

iii. SELECT * FROM STORE WHERE (Scode = 22 OR Qty > 110);

iv. SELECT Sname, MIN(Rate) FROM STORE, SUPPLIERS WHERE STORE. Scode =

SUPPLIERS.Scode GROUP BY Snam

b. i. 3

ii. 880

iii.

I te m Sname

Gel Pen Class ic Pr em ium Stationers


iv. 24-Feb-10

40. I ns e rt, de le te an d dis play ope ration on que ue : -

queue : imp lemen ted a s a lis t


Page : 121
front : integer having pos ition of first elem ent in qu eue rear
: integer hav ing pos it ion of las t element in queu e """

def c ls():

print("\n" * 100)

def is Empty( Qu ) :

if Qu == [ ] :

return T r u e

els e :

return F a ls e

def Enqueue(Qu, item) :

Qu. appen d(item)

if len(Qu) == 1 :

front = rear =0

els e :

rear = len(Qu) - 1

def Dequeue(Qu) :

if is Empty(Qu) :

return "Und erf low "

els e :

item = Qu. pop(0)

if len(Qu) == 0 : # if it w as s ingle-element queue

front = rear = None


r e t urn it em
Page : 122
def Dis play(Qu) :

if is Empty(Qu) :

print ("Queue Empty!")

elif len(Qu) == 1:

print(Qu[ 0], "<== front, rear")

els e :

front = 0

rear = len(Qu) - 1
print(Qu[front], "<-front")
for a in range(l, rear ) :
print(Qu[a]) print(Qu[rear],
"<-rear")

# __main__

queue = [ ] # initially queue is empty


front = None

w hile T rue :

c ls()

print("QUEUE OPERATIONS BY USING LIST")


print("l. Ins ert")

print("2. Delet e")


print("3. Dis play ")

print("4. Exit")

c h = int(input("Enter your choic e (1-5) : ”)) if


ch == 1 :

print ("For the n ew member, enter details below :")


member No = int( input ("Enter member no :"))

m emb erN am e = input ("Enter mem be r n ame :") age


= int(input("Enter memberJ s age : “))

item = [memberNo, memberN ame, age]


Page : 123

E n qu eu e( qu eu e, it em) input("Pres s
Enter to continue. .. ")

elif c h == 2 :

item = Dequeue(queue)

if item == "Underflow " :

print ("Underflow ! Queue is empty!")

els e :

print("Deleted item is ", item)


input("Pres s Enter to c ontinue. .. ")

elif c h == 3 :

Dis play(queue)

input("Pres s Enter to continue. .. ")

elif c h == 4 :

b re a k

els e :

print ("Invalid c hoic e!")


input("Pres s Enter to c ontinue. .. ")

OR
Lis t1 = [40, 40.5, "Ekta"]
i. list overheads = 26

Referenc e pointer s ize = 4 bytes (on 32 bit implementat ion)


Length of the list =3.

Memor y c ons umption for lis t = 3

Lis t overheads + Referenc e points s ize x


length of the lis t.

= 36 + 4 3 = 48 bytes.
Page : 124
ii. M em ory c ons umption by data.

T here are 3 values

1. integer i. e. 40

memory c ons umption = 12 bytes

2. float i.e. 40. 5

memory c ons umption = 16 bytes

3. s tring i. e. "Ekta"

iii. memory c ons umption = overloads + 1 * string length = 21


bytes + 1 * 4

= 21 + 4 = 25 bytes

memory c ons umption by data = 12 + 16 + 25 = 53 bytes

memory c ons umption for lis t l inc luding ac tual data = 48 + 53 = 101 bytes
Page : 125

CBSE SAMPLE PAPER-02 (2020-21)

Class 12 Compute r Science

Max imum Marks : 70


Time Allowe d: 3 hours

Ge ne ral I ns tructions:

1. T his ques tion paper c ontains tw o parts A and B. Eac h part is c ompuls ory.

2. Both Part A and Part B have c hoic es.

3. Part-A has 2 s ec tions :

a. Sec tion – I is s hort ans w er ques tions , to be answ ered in one w ord or one line.

b. Sec tion – II has tw o c as e s tudy ques tions. Eac h c as e s tudy has 4 c as e-bas ed s ubparts.

An examinee is to attempt any 4 out of the 5 subparts .

4. Part - B is the Desc riptive Paper.

5. Part- B has three s ections

a. Sec tion-I is s hort answ er ques tions of 2 marks eac h in w hic h tw o ques tions have

int erna l opt ions .


b. Sec tion-II is long answ er ques tions of 3 marks eac h in w hic h tw o ques tions have

int erna l opt ions .


c. Sec tion-III is very long ans w er ques tions of 5 marks eac h in w hic h one ques tion has
a n interna l opt ion.

6. All programm in g ques tions are to be ans w ered us ing Python Lan guag e only
Page : 126

Part -A (Se ction-I ) Attempt any 15 Ques tions


1. Whic h of the follow ing is inc orrect?
a. s ys . platform
b . s ys . readline
c. s ys . path
d. s ys. argv
2. W hy do w e define a func tion?
3. How w ill you open a n ew binary file btext. txt in w rite and read m od e?
4. Whic h of the follow ing is an invalid s tatement?
a. a, b, c = 1000, 2000, 3000
b. a = b = c = 1,000, 000
c . a b c = 1000 2000 3000
d. abc = 1,000, 000
5. T o open a file c :\ss. txt for appending data, w e us e

a. file = open("c :\ \ss.txt", "a")

b. file = open("c :\ \ss.txt", "rw ")

c. file = open(r"c : \ss.txt", "a")

d. file = open(file = "c :\ss.txt", "w ")

e. file = open(file = "c :\ \ss.txt", "w ")

f. file = open("c :\ res. txt")


a. c, d
b. b, d
c . a, c
d. a, d

6. Wh at is the Python s earc h path?

7. What w ill the follow ing query do?

imp ort mys q l. c onnec tor

db = mys ql. c onnector.c onnec t(.. )


c urs or = db.c urs or( )
Page : 127
db. exec ute("SELECT * FROM staff WHER E pers on_id in {}".format((1,3, 4)))

db. c omm it( )


db.c los e( )

8. Wh at w ill be the res ult of follow ing s tatement w ith follow ing h ierarc hic al s truc ture of

pac kage Pkt1


i. _int_. py
ii. module1
iii. module2
iv. module3

module1 has func tions - hello (), printme ()


modu le2 has func tions - c ountme(), printit ()
module3 has func tions - this (), that ()

im p ort Pk t1
modulel. hello ()

giv e reas ons for your answ ers .


9. W hat is the differenc e betw een a lis t and a tuple?
10. Wh at is an argument?
11. Ca n you s ugges t a real-life applic at ion for input/output res tric ted queues ?
12. W ha t do you unders tand b y the terms Candid ate Ke y and Cardina lity of relation in

the relat iona l d ata bas e


13. What is overflow s ituation?
14. A(n) ________ in a table repres ents a logic al relations hip among a s et of values .
a. Entry
b. Key
c. Attribute
d. T uple

15. Expand the follow ing:


i. VoIP
ii. SMTP
16. Whic h is the s ubs et of S Q L c ommands us ed to manipulate databas e s truc tures ,
inc lud ing tab les ?
a. None of thes e
b. Both Data Definition Language (DDL) and Data Manipulation Language (DML)
Page : 128
c. Data Definition Language (DDL)
d. Data Manipulat ion Language (DML)
17. Differentiate betw een fetc hone() and fetc hall() methods .
18. What do you unders tand by Primary Key ? Giv e a suitable examp le of Primary Key
from a table c ontain ing s om e meaningfu l data.
19. What is the job of a sw itc h?
20. Write a c hec klis t before c onnec ting to a databas e?
21. Find O DD parity bit for 11100011
a. 1
b. 2
c. none of thes e
d. 0
Se ction-II (Case study bas e d Ques tions )
22. Cons ider the follow ing tables G AM E S and PLAYER and answ er (b) and (c) parts of this
ques tion :
Table: GAMES

GCode Game Name Type Num be r Prize Mone y Sche dule Date

101 Carom Bo ard Indoor 2 5000 23-J an-2004

102 Badm int on Outdoor 2 12000 12-Dec-2003

103 T able T ennis Indoor 4 8000 14-Feb-2004

105 Chess Indoor 2 9000 01-J an-2004

108 Law n T ennis Outdoor 4 25000 19-Mar-2004

Table: PLAYER

PCode Name GCode

1 Nabi Ahm ad 101

2 Ravi Sahai 108

3 J atin 101

4 Nazn een 103

a. Wh at do you unders tand by primary k e y and c andid ate keys ?


b. Write the S Q L c ommand for the follow ing s tatement:
T o dis play the name of all GAME S w ith their GCodes.

c. Write the SQ L c ommand for the follow ing s tatement:


Page : 129
T o display details of thos e G AM E S w hic h are having PrizeMoney more than 7000.

d. Write the S Q L c ommand for the follow ing s tatement:

T o dis play the c ontent of the G AM E S table in asc ending order of Schedule Date.

e. Write the S Q L c ommand for the follow ing s tatement:

T o dis play s um of PrizeMoney for eac h type of GAM ES.

23. A text file "Quotes . T xt" has the follow ing data w ritten in it :

Liv ing a life you c an be proud of Doing you

Spend ing your time w ith peop le and ac tivit ies that are important to y ou
Stand ing u p for things that are right eve n w h en it' s hard

Bec omin g the bes t vers ion of you


i. Write a us er-defined func tion to dis play the total num ber of w ords pres ent in the
file.

ii. Whic h of the follow ing func tion flus hes the files implic it ly?

a. flus h()

b. c los e()

c. open()

d. fflus h()

iii. A __________ function reads first 15 c haracters of file.

iv. You c an c reate a file us ing _________ func tion in python.

v. A _____ function requires a s equenc e of lines, lis ts, tuples etc. to write data into file.

Part – B (Se ction-I )


24. Rewrite the follow ing c ode in python after removing all s yntax error(s ).
Und er line eac h c orrec tion done in the c ode.
30 = T o

for K in range(0,T o)

IF k%4== 0:
Page : 130

print (K * 4)

Els e:

print (K + 3)
25. Write the expan ded n a mes for the follow ing abbrev iat ed terms us ed in Netw orking
and Commu n ic at ions
i. GPRS
ii. WiFi
iii. POP
iv. SMT P

OR
What is E-mail? What are its advantages ?
26. What do you mean by IP Addr es s ? How is it us eful in Computer Sec urity?
27. How c an w e import a module in Python?

OR

Find the error(s) in the follow ing c ode and c orrec t them: def
des cribe intelligent life form():

height = raw _input ("Enter the height")


raw input ("Is it c orrect?")

w eight = raw _input ("Enter the w eight")

favourite-game = raw _input ("Enter favorite game")


print "your height", height, ’and w eight', w eight

print "and your favourite g am e is ", favouritis m, '. '


28. Cons ider the follow ing nes ted lis t definit ion and then ans w er the ques tions bas ed o n

this
Page : 131
x = [10, [3.141, 20, [30, 'baz', 2.718]], 'foo'] A
s c hematic for this list is s how n below :

i. Wh at is the expres s ion that returns the ' z' in ' baz' ?

ii. What expres s ion returns the lis t [' baz', 2. 718]
29. Find and w rite the output of the follow ing python c ode:

def Change(P, Q = 30): P


=P+Q

Q=P- Q
print(P, "#", Q)
return (P)

R = 150
S = 100

R = Change(R,S)
print(R, "#", S)

S = Change(S)
30. In a table Apply, there is a c olumn name ly Ex pe rie nce that c an s tore only one of thes e
values : ' Fres her' , ' Private-s ec tor-experienc e' , ' Public -s ec tor-experienc e' , ' Govt. - s ec tor
experienc e' . Yo u w ant to s ort the data of table bas ed on c olumn e xpe rie nce as per this
order: ' Govt-s ec tor-experienc e', ' Public -s ec tor-experienc e' , 'Private-s ec tor- experienc e',
' Fres her'. Write an S Q L query to ac hieve this .

31. Cons ider a table s truc ture as follow s :


Emp loyee
E mp _ ld Em pn am e
Dept

Age.

Writ e Python c ode to c reate the above table and then c reate an index and Emp _ ld.
32. What are different types of S Q L func tions ?
33. Predic t the output of the follow ing c ode s nippets ?
i. arr = [1, 2, 3, 4, 5, 6]
for i in range(1, 6):
arr[i - 1] = arr[i]
for i in range(0, 6):
print(arr[i], end = " ")
Page : 132

ii. Numbers = [9, 18, 27, 36]

for Nu m in Numbers :

for N in range(1, Num%8) :

print(N, "#", end = " ")

print( )

Se ction- I I
34. Write a func tion CountYouM e() in Python w hic h reads the c ontents of a text file

Notes .txt and c ounts the w ords You and Me (not c as e s ens itive).
35. Write a func tion c alled removeF irs t that ac c epts a lis t as a parameter. It s hould
remove the va lue at index 0 from the lis t.
Note that it s hould not return anything (returns None). N ot e that this func tion m us t ac tually
mod ify the lis t pas s ed in, and not jus t c reate a s ec ond lis t w he n the firs t item is removed.
Yo u ma y as s ume the lis t you are given w ill have at leas t one element.

OR
Writ e the term s uitable for follow ing des c riptions :
i. A na me ins ide the parenthes es of a func tion head er that c an rec eive value.

ii. An argument pas s ed to a s pec ific paramet er us ing the paramet er n am e.

iii. A value pas s ed to a func tion parameter.

iv. A value as s igned to a paramet er n am e in the func tion header. v. A


valu e as s igned to a parameter na me in the func tion c all.

vi. A name defin ed outs ide all func tion definitions .

vii. A variable c reated ins ide a func tion body.


36. W hy do w e need pac kages in Python?
37. What is the utility of:
i. default argumen ts
ii. keyw or d arguments
Page : 133

Se ction-II I
38. Disc us s how IPv4 is different from IPv6.
39. Cons ider the follow ing table ST ORE. Write SQL c ommands for the follow ing
s tatem ents .
Table: STORE

ItemNo Item Sc ode Qty Rate Las tBuy

S harpen er
2005 23 60 8 31-Jun-09

Clas sic
2003 Ball Pen 0. 25 22 50 25 01-Feb-10

2002 Gel Pen 21 150 12 24-Feb-10


Premium

2006 Gel Pen Class ic 21 250 20 11-Mar-09

2001 Eras er Small 22 220 6 19-J an-09

2004 Eras er Big 22 110 8 02-Dec-09

2009 Ball Pen 0. 5 21 180 18 03-Nov-09


i. T o dis play details of all the items in the Store table in asc ending order of Las tBuy.

ii. T o dis play ItemNo and Item name of thos e items from Store table w hos e Rate is

more than 15 Rupees .

iii. T o dis play the details of thos e items w hos e Suppliers c ode (Sc ode) is 22 or Quantity

in Store (Qty) is more than 110 from the table Store.

iv. T o dis play the Min imum Rate of items for eac h Supplier indiv idually as per Sc ode

from the table s tore.

4 0. Write a program that depends u p on the us er's c hoic e, either pus hes or pops a n

element in a s tac k.
OR
Convert the express ion (T RUE and FALSE) or not (FALSE or T RUE) to pos tfix
expres s ion. S how the c ontents of the s tac k at every s tep.
Page : 134

12 Compute r Science Sample Pape r -02

Class 12 - Compute r Science

Solut ion
Part -A (Se ction-I ) Attempt any 15 Ques tions

1. (b) s ys. readline

Exp lanat io n : T h e c orrec t format to us e this is s ys .s tdin. re adline .

2. W e define a func tion in the program for dec ompos ing c omp le x problems into s impler piec es
by c reating func tions and for reduc ing duplic ation of c ode by c alling the func tion for
s pec ific tas k multip le times .

3. file_handle = open("btext. txt", w b+)

Note : w b+ mo de open binary files in read and w rite mode.


4. (c) a b c = 1000 2000 3000

Explanation : a b c = 1000 2000 3000 not w ork

5. (c) a, c

Exp lanat io n : (a) and (c ) s tatements have the c orrec t s yntax to open the file in appe nd m od e.

6. T he Python s earc h path is a lis t of directories that the Python s earc hes for any Python

pac kage or modu le to be imported.


7. It w ill extrac t row s from s taff table w here pers on_id is 1 or 3 or 4.
8. T his w ill g iven an error as importing a pac ket does not plac e any of modules into loc al

n am es p ac e.
9. Lis ts are mutable s equenc e types w hile tup les are immutab le s equenc e types of

Python.
10. An argument is a value s ent onto the func tion from the func tion c all s tatement.

e. g. s um(4, 3) have 4 and 3 as arguments w hic h are pass ed to s um() func tion.

11. T o s tore a w eb brows er' s his tory, the deque is us ed. Rec ently vis ited UR Ls are added
Page : 135

to the front of the deque, and the UR L at the bac k of the deque is removed after s om e
s pec ified n u mb er of ins ertions at the front.

12. Candidate ke y: It is a s et of attributes that uniquely id entify tuples in a table.

Cand id ate Ke y is a s uper key w ith no repeated attributes.

Car dinality of a re lation repres ents the nu mb er of row s in the relation.


13. Overflow refers to w h en one tries to pus h an item in s tac k that is full.
14. (d) Tuple

Exp lan at ion : T up le is one entry of the relation w ith s everal attributes w h ic h are fields .

15. i. Voic e Over Internet Protoc ol (VoIP), is a tec hnology that allow s you to make voic e

c alls over a broadba nd Internet c onnec tio n.

ii. Simple Ma il T rans fer Protocol is the protoc ol us ed for s ending e-mail over the

Intern et.
16. (c) Data Definition Language (DDL)

Explanat ion : Data Definit ion Langu age (DD L) is us ed to manage the table and index
structure. CREAT E, ALT ER, RENAME, DROP and T RUNCAT E s tatements are the names of few
data defin it ion elem ents .

17.

fe tchone () fe tchall()

T he fetc hone() method is us ed to fetc hall() is us ed to fetc h multiple values . It fetc hes
fetc h only one row from the table. all the row s in a res ults et. If s ome row s have
T he fetc hone() method returns the alre ady bee n exec uted from the res ult s et, then it
next r ow of the res ult-s et. retrieves the rema in ing r ow s from the res ult s et.

18. Primary Ke y: A c olumn or s et of c olumns that uniquely identifies a row w ithin a


table is c alled a primary key.

For example, in the follow ing table Stude nt , the c olumn Roll no. c an uniquely ident ify eac h
row in the table, henc e Roll no. is the primary key of the follow ing table.
Page : 136

Roll no. Name Marks Grade

1 - - -

2 - - -

3 - - -

4 - - -

19. Sw itc h is res pons ible for filtering i. e., trans forming data in a s pec ific w ay and for

forw arding pac kets of the mes s age being trans mitted, betw een L AN s egments. A
s w itc h does not broadc as t the mess ages , rather it unic as ts the mes s age to its
inte nd ed des t in at ion.

20. Before c onnecting to a M yS QL databas e make s ure


i. You have c reated a databas e

ii. Yo u have c reated a table

iii. T his table has fields

iv. Python module M y S Q Ld b is installed properly on your mac hine.

21. (d) 0
Parity refers to the number of bits s et to 1 in the data item
Ev en parity - an even number of bits are 1

O dd parity - an odd number of bits are 1

A parity bit is an extra bit trans mitted w ith a data item, c hos e to give the res ulting bits eve n
or odd parity

Odd parity - data: 11100011, parity bit 0


Se ction-II (Case study bas e d Ques tions )

22. a. Primary Ke y is a unique and non-null key, w hic h is us ed to identify a tuple


uniqu e ly. If a table has m ore than one s uc h attributes w h ic h identify a tuple
un ique ly than all s uc h attributes are kn ow n as c andid ate keys .

b. SELECT GameName, GCode FROM GAMES;

c. SELECT * FROM Games WHERE PrizeMoney > 7000;

d. SELECT * FROM Games ORDER BY ScheduleDate;


Page : 137

e. SELECT SUM(Prizemoney) FROM Games GROUP BY Type;

23. (i) Us er define func tion to dis play total number of w ords in a file:

def c ountw ords():

s =open ("Quotes .txt", 'r')

f = s, read()

z = f. split()
c ount=0
for i in z:
c ount=c ount +1
print("T otal number of w ords ", c ount)
(ii) b. c los e()
(iii) read(15)

(iv) open()

(v) writelines ()
Part – B (Se ction-I )
24. T o = 30 # variable name s hould be on L HS

for K in range(0, T o) : # : w as mis s ing

if k%4 == 0: # IF s hould be in low erc as e; i. e; if

print (K * 4)

els e: # els e s hould b e in low er c as e

print (K + 3)
25. i. GPRS: General Pac ket Radio Servic e

ii. WiFi: Wireles s fidelity

iii. POP: Post Offic e Protocol

iv. SMTP: Simple Mail T rans fer Protoc ol OR

E-mail (Elec tronic mail) is s ending and rec eiving mes s ages by a c omputer. Elec tronic mail
(email or e-mail) is a method of exc hanging mes s ages ("mail") betw een people us ing
elec tronic devic es . T he major advantages of E-mail are:
Page : 138

i. Eas y rec ord maint enanc e

ii. Was te reduc tion

iii. Low Cos t

iv. Fas t delivery

26. An Internet Protoc ol (IP) address is a numeric al ident ific ation and log ic al addres s that is
as s igned to devic es c onnec ted in a c omputer netw ork. An IP addres s is us ed to uniquely
ident ify dev ic es on the internet and s o one c an quic kly k n ow the loc ation of the s ys tem in
the netw ork.

In a netw ork, every mac hin e c an be identified b y a unique IP addres s as s oc iated w ith it and
thus help in provid ing netw ork s ec urity to every s ys tem c onnec ted in a n e tw ork.

2 7. i. us ing im po rt s tatement

Syntax: import <modulenam e1>[, <modulen ame2>, . . . <modulename3>]


Ex ample :

im port math, c mat h

im port r an dom, math, n u mp y

ii. us ing f rom s tatement

Syntax: from <modulename> import <funtion1> [, <function2>, ... <func tion>]


Ex ample :

from m ath import s qrt, p ow

fr om r an d om imp ort ra nd om, randint, ra ndr an ge


OR
T he c orrec t s yntax for the c ode is : def
describe_intelligent_life_form():

height = raw _input ("Enter the height")


ques = raw _input ("Is it c orrec t(y/n)?")
w eight = raw _input ("Enter the w eight")

favourite_game = raw _input ("Enter favorite game")


print ("your height", height, ' and w eight', w eight)

print ("and your favourite game is ", favourite_game, '. ')


Page : 139

Errors : Func tion nam e s hould not have s pac es . W e c an us e unders c ore in plac e of
s pac es.

N o variable is defined to obtain valu e be ing input, w e c an us e a variable to take input. Lines
4 and 6 are badly ind ented; be ing part of s ame func tion, thos e s hould be at the s ame
indentat ion leve l as that of lines 2, 3, 5 and 7.

An d als o, variab le favorit es -game is an invalid ident ifier as it c ontains a hyphen, but it
s hould h a v e b ee n an unders c ore.

28. i. x[1] [2] [1] [2]

ii. x[1] [2] [1:]


29. 250 # 150

250 # 100

130 # 100

T he R = Change(R, S) prints the value of R and S from the func tion and updates variable
R. T hen, next print(R, "#", S) s tatement prints the updated value of R and value of S.
T hen, S = Change(S) prints the value of S and Q(=30) in the func tion.

30. Statement:-

SELECT * FROM Apply ORDER BY FIELD (Experience, ' Govt-sector-experience', 'Public- s ec tor-
experienc e' , ' Private-s ec tor -experienc e' , 'Fresher') ;

31. import MySQLdb

db = MySQLdb.c onnec t("loc alhos t", "HRMan", "HRman@pwd", "c ompvtLtd")


c urs or= db. c urs or()

c urs or. execute ("Drop T able IF Exis ts Employee")

sql="""Create Table Employee(Emp_id INT NOT NULL , Emp_name c har(50) NOT NULL , Dept'
c har(20)

NOT NULL , Age INT NOT NULL )"""


c urs or. exec ute(s ql)

c ursor. exec ute('' "create index eid on us er, (Emp_Id)""")


c urs or.c ommit()

c urs or.c los e ()


db.c los e()
Page : 140

32. There are tw o types of SQL func tions;


i. Single R ow (or Sc alar) functions , w ork w ith a s ingle row at a time. A s ingle row

func tion returns a res ult for every r ow of a queried table.

ii. Multip le R ow (or Group or Aggregate) func tions, w ork w ith data of multiple row s

at a time a n d return aggregat ed va lue.


33. Outputs of the above given c ode s egments are:
i. 2 3 4 5 6 6

ii. 1 #

1#2#

1#2#3#

Se ction- I I
34. Count Yo uM e function w ill c ount the number of oc c urrenc es of w ord You and M e in the

file given.

def CountYouMe():

w ordlis t = [line.s trip() for line in open(‘Notes .txt’)] #


Searc hing for a w ord in a file

c ount =0

for w ord in w ordlis t:


w ords = word.s plit(" ")
for w ord in w ords :

# Remov e all lead ing and trailing w hite s pac es


w ord =w ord. s trip(). low er()

if w ord == ' you' or word==' me'():

c ount = c ount + 1

if c ount == 0:

print ("Not found in file")


els e:
Page : 141
print ("c ount=", c ount)
Examp le : If the file c ontains
Yo u are my bes t friend

You and m e make a good team.


Output w ould be: c ount=3
35. def removeFirs t (input_lis t):

"""T his func tion w ill remove firs t item of the lis t"""

input_lis t. pop(0)

#pop remo ves and retur ns item of lis t

r e t ur n
OR
i. Parameter

ii. Na m ed argument

iii. Argume nt

iv. Default value

v. Named/k eyw ord argu ments

vi. Global Variable

vii. Loc al Variable


36. As the applic ation program grow s larger in s ize w ith a lot of modules , w e plac e s imilar
modu les in one pac kage and different modules in different pac kages . T his makes a
projec t eas y to m an ag e and c onc eptually c lear.

3 7. i. T h e default paramet ers are parameters w ith a default va lue s et to them. T his default
value is automatic ally c ons idered as the pas s ed value W H E N no value is provid ed for
that parame ter in the func tion c all s tatement.

T h us default arguments are us eful w h e n w e w ant to s kip an argum ent in a


func tion c all s tatement a n d us e the default va lue for it ins tead.

ii. T he keyw ord arguments give c omplete c ontrol and flexibility over the values s ent as
argum ents for the c orres ponding paramet ers . Irres pec tive of the plac e men t a nd order of
arguments , keyw ord argum ents are c orrec tly matc hed. A keyw ord ar gume nt is w here
y ou provid e a na me to the variab le as yo u pas s it into the func tion.

Se ction-II I
38. Internet Protoc ol (IP) is a s et of tec hnic al rules that define how c omputers
Page : 142

c ommunic at e over a netw ork. T here are currently tw o vers ions : IP vers ion 4 (IPv4)
and IP vers ion 6 (IPv6).
IPv4 w as the firs t vers ion of Internet Protoc ol to be w idely us ed and still ac c ounts for mos t of
today' s Internet traffic . T here are jus t over 4 billion IPv4 address es . While that is a lot of IP
addres s es , it is not enough to las t forever. IPv4 and IPv6 are internet protoc ol vers ion 4 and
internet protoc ol vers ion 6, IP vers ion 6 is the n ew vers ion of Internet Protoc ol, w hic h is w ay
better than IP vers ion 4 in terms of c omplex ity and effic ienc y.

IPv6 is a new er numbering s ys tem to replac e IPv4. It w as deployed in 1999 and


provid es far m ore IP address es , w hic h s hould mee t the need w ell into the future.

T he major differenc e betw een IPv4 and IPv6 is the number of IP address es. Although there
are s lightly m or e than 4 billion IPv4 addres s es , there are mor e than 16 billion- billion IPv6
addres s es .

Internet Protoc ol vers ion 4 Internet Protoc ol vers ion 6

(IPv4) (IPv6)
Addres s s ize 32-bit numb er 128-bit number

Dotted dec imal notation : Hexad ec im a l notat ion :


Addr es s format

192. 168.0. 202 3FFE:0400:2807:8AC9::/64


N u m b er of
2^32 2^128
addres s es
39. i. SELECT *
FROM ST ORE ORDER
By LastBuy ;

ii. SELECT ItemNo, Item


FROM ST ORE
WHERE Rate >15 ;

iii. SELECT *
FROM STORE
WHERE Scode = 22 OR Qty > 110 ;

iv. SELECT Scode, Min(Rate)


FROM ST ORE
GROUP By Scode;
Page : 143

40. pus h and po p ope ration into the s tack: -


MAX_SIZE = 1000

stack = [0 for i in range(MAX_SIZE)] -


top= 0

def pus h():

global s tack, top

x = int( input ("Enter element to pus h into s tac k: " )) if


top >= MAX_SIZE:

print("Cannot pus h. Stac k is full. Overflow !")

els e:

s tack[top] = x
top += 1

def pop():
global s tac k, top if
top == 0:

print("Cannot pop. Stac k is empty. Underflow !")


els e:
top -= 1
def printStac k():
print(s tac k[:top])
# __main__
w hile T rue:

print("Ple as e c hoos e oper ation")


print("1. Pus h")

print("2. Pop")
print("3. Print")
print("4. Exit")

c hoic e = int(input("Pleas e enter 1/2/3 : " )) if


choic e == 4:

b re a k
Page : 144
elif choic e == 3:
printStac k()

elif choic e == 2:

pop( )
elif choic e == 1:
pus h()
els e:
print("Ple as e give a c orrec t input")
OR
[(T RUE and FALSE) or not (FALSE or TRUE)]
Add ing ] to the end of the express ion and ins erting [ to the beginning of the s tac k.
Sc anning from Left to Right
Page : 1

S. No Symbol Stack Pos tfix Ex pre s s ion Y

0 [

1 ( [(

2 TRUE TRUE

3 and [( and TRUE

4 FALSE TRUE FALSE

5 ) [ TRUE FALSE and

6 or [ or TRUE FALSE and

7 not [ or not TRUE FALSE and

8 ( [ or not ( TRUE FALSE and

9 FALSE TRUE FALSE and FALSE

10 or [ or not ( or TRUE FALSE and FALSE

11 TRUE TRUE FALSE and FALSE TRUE

12 ) [ or not TRUE FALSE and FALSE TRUE or

13 ] End of Express ion T RUE FALSE and FALSE T RUE or not or

*******ALL THE BEST*******

You might also like