Student Support Material Class Xii - Cs
Student Support Material Class Xii - Cs
AHEDABAD CLUSTER
CONTRIBUTORS
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.”
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()
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
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= "#")
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
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) 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:
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
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
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)
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.
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
1.
Page : 31
3
Page : 32
6
Page : 33
Page : 34
Page : 35
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()
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()
for i in data:
#word=word.upper()
if i==word:
c+=1
print("Word found", c,"times")
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)
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-
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::
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.
1,Peter,3500
2,Scott,4000
3,Harry,5000
4,Michael,2500
5,Sam,4200
import # Line 1
def addCsvFile(Name,Mobile): # to write / add data into the CSV file
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
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:
Example:
If the file content is as follows: Updated information
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
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.
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.
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
OR
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])
“Book.dat”
OR
Page : 68
import pickle
def createFile():
fobj=open("Book.dat","ab")
Book_name=input("Name :")
Author = input(“Author: “)
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.
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])
# Driver Code
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print (arr[i])
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
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 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
A B C
D E
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
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
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
½ 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
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:
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)
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.
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
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 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.
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
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
# 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")
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
It works like "undo", which reverts all the changes that you
ROLLBACK have made.
CBSE
CLASS12
COMPUTER 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 )
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
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. 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 ?
12. Write a query to dis play the Sum, Average, Highes t and Low es t s alary of the
employees .
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
19. Wh at is a repeater?
a. 0000
b. 1111
c . 1110
d. 0111
Page : 104
22. Give output for follow ing SQ L queries as per given table(s ):
Table: GRADUAT E
S.NO. NAME STIPEND SUBJECT AVERAGE DIV
5.
SABINA 500 MAT HEMATICS 70 1
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 :
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.
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
a=2
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
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
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
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
Samp le run :
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 :
2. x = 72
3. return x + 3
4.
5. y = 54
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
VILLAGE 1 to B_TOWN 2 KM
B_TOWN 120
VILLAGE 1 15
VILLAGE 2 10
VILLAGE 3 15
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
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
iv. Whic h s ervic e/protoc ol w ill be mos t helpful to c onduc t live interac tions of Experts
39. Cons ider the follow ing tables ST ORE and SUPPLIERS and answ er (a) and (b) parts of
Scode Sname
21 Pr em ium Stationers
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
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
iii. SELECT Item, Sname FROM STORE S, Suppliers P WHERE S. Scode= P. Scode
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"]
Solut ion
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.
5. (d) b, c, f
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
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
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
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 .
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.
Explanat ion : 0000, 1’s c omplem ent arithmet ic to get the s um.
63
ii. SUM(STIPEND)
1000
iii. AVG(STIPEND)
450
23. i. my_file =open(' poemBT H. txt' , 'r') w ill open the given file in read mode
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. +
last = lis[-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
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
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.
step = N // abs(N)
s um = 0
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 .
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 :
if v < 5:
for j in range(v):
fp1. w rite ( n a m e)
fp1.write (" ")
b re a k
return F a ls e
els e:
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):
els e:
Page : 119
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' }
year = date[4:]
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.
x = 72
Func tion body in lines 2 and 3
return x + 3
y = 54
M a in program in lines 5 and 6
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
ii. SELECT ItemNo, Item FROM ST ORE WHERE Rate > 15;
iv. SELECT Sname, MIN(Rate) FROM STORE, SUPPLIERS WHERE STORE. Scode =
b. i. 3
ii. 880
iii.
I te m Sname
def c ls():
print("\n" * 100)
def is Empty( Qu ) :
if Qu == [ ] :
return T r u e
els e :
return F a ls e
if len(Qu) == 1 :
front = rear =0
els e :
rear = len(Qu) - 1
def Dequeue(Qu) :
if is Empty(Qu) :
els e :
if is Empty(Qu) :
elif len(Qu) == 1:
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__
w hile T rue :
c ls()
print("4. Exit")
E n qu eu e( qu eu e, it em) input("Pres s
Enter to continue. .. ")
elif c h == 2 :
item = Dequeue(queue)
els e :
elif c h == 3 :
Dis play(queue)
elif c h == 4 :
b re a k
els e :
OR
Lis t1 = [40, 40.5, "Ekta"]
i. list overheads = 26
= 36 + 4 3 = 48 bytes.
Page : 124
ii. M em ory c ons umption by data.
1. integer i. e. 40
3. s tring i. e. "Ekta"
= 21 + 4 = 25 bytes
memory c ons umption for lis t l inc luding ac tual data = 48 + 53 = 101 bytes
Page : 125
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.
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.
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
6. All programm in g ques tions are to be ans w ered us ing Python Lan guag e only
Page : 126
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
im p ort Pk t1
modulel. hello ()
GCode Game Name Type Num be r Prize Mone y Sche dule Date
Table: PLAYER
3 J atin 101
T o dis play the c ontent of the G AM E S table in asc ending order of Schedule Date.
23. A text file "Quotes . T xt" has the follow ing data w ritten in it :
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
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()
v. A _____ function requires a s equenc e of lines, lis ts, tuples etc. to write data into file.
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():
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:
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 .
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
for Nu m in Numbers :
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.
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
S harpen er
2005 23 60 8 31-Jun-09
Clas sic
2003 Ball Pen 0. 25 22 50 25 01-Feb-10
ii. T o dis play ItemNo and Item name of thos e items from Store table w hos e Rate is
iii. T o dis play the details of thos e items w hos e Suppliers c ode (Sc ode) is 22 or Quantity
iv. T o dis play the Min imum Rate of items for eac h Supplier indiv idually as per Sc ode
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
Solut ion
Part -A (Se ction-I ) Attempt any 15 Ques tions
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 .
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
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.
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
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.
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
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.
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
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
23. (i) Us er define func tion to dis play total number of w ords in a file:
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
print (K * 4)
print (K + 3)
25. i. GPRS: General Pac ket Radio Servic e
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
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
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.
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') ;
sql="""Create Table Employee(Emp_id INT NOT NULL , Emp_name c har(50) NOT NULL , Dept'
c har(20)
ii. Multip le R ow (or Group or Aggregate) func tions, w ork w ith data of multiple row s
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():
c ount =0
c ount = c ount + 1
if c ount == 0:
"""T his func tion w ill remove firs t item of the lis t"""
input_lis t. pop(0)
r e t ur n
OR
i. Parameter
ii. Na m ed argument
iii. Argume nt
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.
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.
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 .
(IPv4) (IPv6)
Addres s s ize 32-bit numb er 128-bit number
iii. SELECT *
FROM STORE
WHERE Scode = 22 OR Qty > 110 ;
els e:
s tack[top] = x
top += 1
def pop():
global s tac k, top if
top == 0:
print("2. Pop")
print("3. Print")
print("4. Exit")
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
0 [
1 ( [(
2 TRUE TRUE