0% found this document useful (0 votes)
40 views144 pages

Xii CSC Worksheets All Chapters

The document is a revision worksheet for Grade 12 Computer Science, containing various questions related to Python programming concepts. It includes tasks such as identifying valid identifiers, writing Python code, evaluating expressions, and understanding data structures like lists, tuples, and dictionaries. The worksheet is divided into sections with questions worth 1, 2, and 3 marks, covering a range of topics from syntax errors to built-in functions.

Uploaded by

Raghav Raghav
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
0% found this document useful (0 votes)
40 views144 pages

Xii CSC Worksheets All Chapters

The document is a revision worksheet for Grade 12 Computer Science, containing various questions related to Python programming concepts. It includes tasks such as identifying valid identifiers, writing Python code, evaluating expressions, and understanding data structures like lists, tuples, and dictionaries. The worksheet is divided into sections with questions worth 1, 2, and 3 marks, covering a range of topics from syntax errors to built-in functions.

Uploaded by

Raghav Raghav
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/ 144

Grade: 12 Computer Science

Revision Tour - Worksheet - 1


1 Marks
1. Find the invalid identifier from the following
a) MyName b) True c) 2ndName d) My_Name
2. Given the lists L=[1,3,6,82,5,7,11,92] , write the output of print(L[2:5])
3. Identify the valid arithmetic operator in Python from the following.
a) ? b) < c) ** d) and
4. Suppose a tuple T is declared as T = (10, 12, 43, 39), which of the following is
incorrect?
a) print(T[1]) b) T[2] = -29 c) print(max(T)) d) print(len(T))
5. Write a statement in Python to declare a dictionary whose keys are 1, 2, 3 and values
are Monday, Tuesday and Wednesday respectively?
6. A tuple is declared as T = (2,5,6,9,8) What will be the value of sum(T)?
7. Name the built-in mathematical function / method that is used to return an absolute
value of a number
8. Identify the valid declaration of L:
L = [‘Mon’, ‘23’, ‘hello’, ’60.5’]
a. dictionary b. string c.tuple d. list
9. If the following code is executed, what will be the output of the following code?
name="ComputerSciencewithPython"
print(name[3:10])
10. Which of the following is valid arithmetic operator in Python: (i) // (ii) ? (iii) < (iv) and
11. Write the type of tokens from the following: (i) if (ii) roll_no
12. Name the Python Library modules which need to be imported to invoke the following
functions: (i) sin( ) (ii) randint ( )
13. What do you understand by the term Iteration?
14. 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’)
(iii) Day=[1:’monday’,2:’tuesday’,3:’wednesday’]
(iv) Day={1’monday’,2’tuesday’,3’wednesday’]

Revision Tour - Worksheet – 1 - 1 Marks Page 1


15. Identify the valid declaration of L:
L = [1, 23, ‘hi’, 6].
(i) list (ii) dictionary (iii) array (iv) tuple
16. Find and write the output of the following python code:
x = "abcdef"
i = "a"
while i in x:
print(i, end = " ")
17. Find the invalid identifier from the following
a. none b. address c. Name d. pass
18. Consider a declaration L = (1, 'Python', '3.14').
Which of the following represents the data type of L?
a. list b. tuple c. dictionary d. string
19. Given a Tuple tup1= (10, 20, 30, 40, 50, 60, 70, 80, 90). What will be the output of
print (tup1 [3:7:2])?
a. (40,50,60,70,80) b. (40,50,60,70) c. [40,60] d. (40,60)
20. The return type of the input() function is
a. string b. integer c. list d. tuple
21. Which of the following operator cannot be used with string data type?
a. + b. in c. * d. /
22. Consider a tuple tup1 = (10, 15, 25, and 30). Identify the statement that will result
in an error.
a. print(tup1[2]) b. tup1[2] = 20 c. print(min(tup1)) d. print(len(tup1))
23. Which one of the following is the default extension of a Python file?
a. .exe b. .p++ c. .py d. .p
24. Which of the following symbol is used in Python for single line comment?
a. / b. /* c. // d. #
25. Which of these about a dictionary is false?
a) The values of a dictionary can be accessed using keys
b) The keys of a dictionary can be accessed using values
c) Dictionaries are ordered
d) Dictionaries are mutable

Revision Tour - Worksheet – 1 - 1 Marks Page 2


Grade: 12 Computer Science
Revision Tour - Worksheet - 1
2 Marks

1. Evaluate the following expressions:


a) 6 * 3 + 4**2 // 5 – 8 b) 10 > 5 and 7 > 12 or not 18 > 3
2. Differentiate between actual parameter(s) and a formal parameter(s) with a suitable
example for each.
3. Explain the use of global key word used in a function with the help of a suitable
example.
4. Rewrite the following code in Python after removing all syntax error(s). Underline each
correction done in the code.
Value=30
for VAL in range(0,Value)
If VAL%4==0:
print (VAL*4)
Elseifval%5==0:
print (VAL+3)
else
print(VAL+10)
5. 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 maximum values that
can be assigned to each of the variables Lower and Upper. import random
AR=[20,30,40,50,60,70];
Lower =random.randint(1,3)
Upper =random.randint(2,4)
for K in range(Lower, Upper +1):
print (AR[K],end=”#“)
(i) 10#40#70# (ii) 30#40#50# (iii) 50#60#70# (iv) 40#50#70#
6. Find and write the output of the following Python code:
def Display(str):
m=""
for i in range(0,len(str)):
if(str[i].isupper()):
m=m+str[i].lower()
Revision Tour - Worksheet – 1 – 2 Marks Page 1
elifstr[i].islower():
m=m+str[i].upper()
else:
if i%2==0:
m=m+str[i-1]
else:
m=m+"#"
print(m)
Display('[email protected]')
7. Rewrite the following code in python after removing all syntax error(s). Underline each
correction done in the code.
30=To
for K in range(0,To)
IF k%4==0:
print (K*4)
Else:
print (K+3)
8. Find and write the output of the following python code:
def fun(s):
k=len(s)
m=" "
for i in range(0,k):
if(s[i].isupper()):
m=m+s[i].lower()
elif s[i].isalpha():
m=m+s[i].upper()
else:
m=m+'bb'
print(m)
fun('school2@com')
9. Find the output of the following code:
Name="PythoN3.1"
R=""
for x in range(len(Name)):

Revision Tour - Worksheet – 1 – 2 Marks Page 2


if Name[x].isupper():
R=R+Name[x].lower()
elif Name[x].islower():
R=R+Name[x].upper()
elif Name[x].isdigit():
R=R+Name[x-1]
else:
R=R+"#"
print(R)
10. Rao has written a code to input a number and check whether it is prime or not. His
code is having errors. Rewrite the correct code and underline the corrections made.
def prime():
n=int(input("Enter number to check :: ")
for i in range (2, n//2):
ifn%i=0:
print("Number is not prime \n")
break
else:
print("Number is prime \n’)
11. (a) Given is a Python string declaration:
myexam="@@CBSE Examination 2022@@"
Write the output of:
print(myexam[::-2])
(b) Write the output of the code given below:
my_dict = {"name": "Aman", "age": 26}
my_dict['age'] = 27
my_dict['address'] = "Delhi"
print(my_dict.items())
12. Predict the output of the Python code given below:
tuple1 = (11, 22, 33, 44, 55 ,66)
list1 =list(tuple1)
new_list = []
for i in list1:
if i%2==0:

Revision Tour - Worksheet – 1 – 2 Marks Page 3


new_list.append(i)
new_tuple = tuple(new_list)
print(new_tuple)
13. The code given below accepts a number as an argument and returns the reverse
number. Observe the following code carefully and rewrite it after removing all syntax and
logical errors. Underline all the corrections made.

14. Predict the output of the following code:

15. Write the Python statement for each of the following tasks using BUILT-IN
functions/methods only:
(i) To insert an element 200 at the third position, in the list L1.
(ii) To check whether a string named, message ends with a full stop / period or not.
16. A list named studentAge stores age of students of a class. Write the Python
command to import the required module and (using built-in function) to display the
most common age value from the given list.
17. Rewrite the following code in Python after removing all syntax error(s) : 2 Underline
each correction done in the code.
Runs = (10, 5, 0, 2, 4, 3)
for I in Runs:
if I=0:
Revision Tour - Worksheet – 1 – 2 Marks Page 4
print(Maiden Over)
else
print(Not Maiden)
18. What possible output(s) is/are expected to be displayed on the screen at the time of
execution of the program from the following code ? Also specify the maximum and
minimum value that can be assigned to the variable R when K is assigned value as 2.
import random
Signal = ['Stop', 'Wait', 'Go' ]
for K in range(2, 0, -1):
R = randrange(K)
print (Signal[R], end = ' # ')
(a) Stop # Wait # Go # (b) Wait # Stop # (c) Go # Wait # (d) Go # Stop #
19. Write the output for the execution of the following Python code :
def change(A):
S=0
for i in range(len(A)//2):
S+=(A[i]*2)
return S
B = [10,11,12,30,32,34,35,38,40,2]
C = Change(B)
print('Output is',C)
17. What is the difference between logical error and run-time error? Give a suitable
example of each.
18. Rewrite the following code in Python after removing all syntax error(s). Underline
each correction done in the code.
Val = 32
for K in range(20:32):
if K>25
print K*Val
Else:
PRINT K+ValNumber
19. Find and write the output of the following Python code :
Txt="Some2Thing"
STxt=""

Revision Tour - Worksheet – 1 – 2 Marks Page 5


Fold=0
for C in range(0,len(Txt)):
if Txt[C]>="0" and Txt[C]<="9":
Fold=1
STxt = STxt + "#"
elif Fold==0 and Txt[C]>="A" and Txt[C]<="S":
STxt = STxt + "@"
elif Fold==1 and Txt[C]>="T" and Txt[C]<="Z":
STxt = STxt + "*"
else:
STxt = STxt + Txt[C]
print (STxt)
20. Out of the (i) to (iv) options, which is/are not possible outputs(s) of the following
program code? Also specify the maximum value that can be assigned to the variable R.
import random
ALPHA=["A","C","E","F","G","B"]
for I in range(1,4):
R=random.randint(I,5)
print(ALPHA[R],":")
(i) F : B : F : (ii) C : G : F : (iii) A : G : F : (iv) G : B : G :
21. R. Rajguru has written a code to input a range and print the Fibonacci series.
His code is having errors. Rewrite the correct code and underline the correction made.

def fibo(n)
a=1,b=1
print(a,b)
for i in range(2,n1+1):

c=a+b
print(c)
a=c
b=c

Revision Tour - Worksheet – 1 – 2 Marks Page 6


22. (a) Given is a Python string declaration:

CBSE="##ANNUAL Examination2023##"
Write the output of: print(CBSE[::-3])

(b) Write the output of the code given below:


my_dict = {"name": "Aman", "age": 26}
my_dict['age'] = 27
my_dict['address'] = "Delhi"
print(my_dict)
my_dict.popitem()
print(my_dict)
23. Predict the output of the Python code given below:
T1 = (11, 22, 33, 44, 55 ,66)
L1 =list(T1)
NL = []
for i in T1:
if i%2==0:
NL.append(i)
NT = tuple(NL)
print(NT)
24. Rishi has written a code and his code is having errors. Rewrite the correct code and
underline the corrections made.
x=input("Enter a no:-")
if x%2=0:
for i range(2*x):
print(i)
loop else:
print("#")
25. (a) Given is a Python string declaration:

S="Cyber World @@ 2022"


Write the output of:

print(S.replace('2','2+1')[::-2])

Revision Tour - Worksheet – 1 – 2 Marks Page 7


(b) Write the output of the code given below:
D={'India':'New Delhi', 'China':'Beijing', 'USA':'Washington DC', 'UK':'London'}
for i in D:
if 'U' in i:
D[i]+='Ok'

for i in D.values():
print(i,end=' ')

Revision Tour - Worksheet – 1 – 2 Marks Page 8


Grade: 12 Computer Science
Revision Tour - Worksheet - 1
3 Marks

1. 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 maximum values that
can be assigned to each of the variables FROM and TO.
import random
AR=[20,30,40,50,60,70];
FROM=random.randint(1,3)
TO=random.randint(2,4)
for K in range(FROM,TO+1):
print (AR[K],end=”# “)
(i) 10#40#70# (ii) 30#40#50# (iii) 50#60#70# (iv) 40#50#70#
2. What will be the output of the following code?
import random
List=["Delhi","Mumbai","Chennai","Kolkata"]
for y in range(4):
x = random.randint(1,3)
print(List[x],end="#")
a. Delhi#Mumbai#Chennai#Kolkata#
b. Mumbai#Chennai#Kolkata#Mumbai#
c. Mumbai# Mumbai #Mumbai # Delhi#
d. Mumbai# Mumbai #Chennai # Mumbai
3. Predict the output of the Python code given below:

Revision Tour - Worksheet – 1 – 3 Marks Page 1


4. What possible output(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 values that can be assigned to the variable End.
import random
Colours = ["VIOLET","INDIGO","BLUE","GREEN", "YELLOW","ORANGE","RED"]
End = randrange(2)+3
Begin = randrange(End)+1
for i in range(Begin,End):
print(Colours[i],end="&")
(i) INDIGO&BLUE&GREEN& (ii) VIOLET&INDIGO&BLUE&
(iii) BLUE&GREEN&YELLOW& (iv) GREEN&YELLOW&ORANGE&
5. Predict the output of the code given below:
s="school2@com"
k=len(s)
m=""
for i in range(0,k):
if (s[i].isupper()):
m=m+s[i].lower()
elif s[i].isalpha():
if i%2==0:
m=m+s[i].upper()
else:
m=m+s[i-1]
else:
m=m+'#'
s=m
print(s)
6. Predict the output of the code given below:

def change():

Text1="CBSE 2021"
Text2="#"
I=0
while I<len(Text1) :

Revision Tour - Worksheet – 1 – 3 Marks Page 2


if Text1[I]>="0" and Text1[I]<="9":

Val = int(Text1[I])
Val = Val + 1
Text2=Text2 + str(Val)

elif Text1[I]>="A" and Text1[I] <="Z":

Text2=Text2 + (Text1[I+1])
else :

Text2=Text2 + "*"
I=I+1
print(Text2)
change()
7. What output will be generated when the following Python code is executed?

8. Find the output of the following Python program:


defmakenew(mystr):
newstr = " "
count = 0
for i in mystr:
if count%2 !=0:
newstr = newstr+str(count)
else:
Revision Tour - Worksheet – 1 – 3 Marks Page 3
ifislower(i):
newstr = newstr+upper(i)
else:
newstr = newstr+i
count +=1
newstr = newstr+mystr[:1]
print ("The new string is :",newstr)
makenew(“sTUdeNT")
9. What are the possible outcome(s) executed from the following code ? Also specify
the maximum and minimum values that can be assigned to variable PICKER.
import random
PICK=random.randint(0,3)
CITY=[“DELHI”,”MUMBAI”,”CHENNAI”,”KOLKATA”];
for I in CITY:
for J in range(1,PICK):
print(I,end=””)
print()

Revision Tour - Worksheet – 1 – 3 Marks Page 4


10.

11. Write a function modilst(L) that accepts a list of numbers as argument and increases
the value of the elements by 10 if the elements are divisible by 5. Also write a proper call
statement for the function.
For example: If list L contains [3,5,10,12,15]
Then the modilist() should make the list L as [3,15,20,12,25]
12. Predict the output of the code given below:
def convert(Old):
l=len(Old)
New=" "
for i in range(0,1):
if Old[i].isupper():
New=New+Old[i].lower()
elif Old[i].islower():
New=New+Old[i].upper()
elif Old[i].isdigit():
New=New+"*"
else: New=New+"%"
return New
Older="InDIa@2022"
Newer=Convert(Older)
print("New String is: ", Newer)
Revision Tour - Worksheet – 1 – 3 Marks Page 5
13. Write a function INDEX_LIST(L), where L is the list of elements passed as argument
to the function. The function returns another list named ‘indexList’ that stores the
indices of all Elements of L which has a even unit place digit.
For example: If L contains [12,4,15,11,9,56]
The indexList will have - [0,1,5]
14. Find and write the output of the following Python code:
def makenew(mystr):
newstr = " "
count = 0
for i in mystr:
if count%2 !=0:
newstr = newstr+str(count)
else:
ifi.islower():
newstr = newstr+i.upper()
else:
newstr = newstr+i
count +=1
newstr = newstr+mystr[:1]
print("The new string is :", newstr)
makenew("sTUdeNT")
15. Write a Python function to sum all the numbers in a list.
Sample List : [8, 2, 3, 0, 7]
Expected Output : 20
16. Write a function listchange(Arr)in Python, which accepts a Arr of numbers , the
function will replace the even number byvalue 10 and multiply odd number by 5 .
Sample Input Data of the list is:
a=[10,20,23,45]
output : [10, 10, 115, 225]
17. 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

Revision Tour - Worksheet – 1 – 3 Marks Page 6


3, 4, 5, 16, 9
then the function should rearranged list as
6, 2,10,8, 18
18. Write a function copylist(lst1,lst2) in Python, which accepts two list Lst1 and Lst2 of
numbers and copies the common numbers into third list.
Sample Input Data of the list
lst1 = [ 10,20,30,40,12,11]
lst2 = [ 10,30,40,13,15,76]
Output
[10,30,40]

19. Find the output of the following code:

Exam="CS Test_1 @ 10Am"


Res=""
t=len(Exam)
for i in range(t):

if Exam[i].isspace():

Res=Res+'-'
elif Exam[i].isdigit():

Res=Res+'$'
elif Exam[i].isupper():

Res=Res+Exam[i-1]
elif Exam[i].islower():

Res=Res+Exam[i].upper()

else:
Res=Res+"*"
print(Res)
20. What will be the output of the following python code.

def change(msg):

Revision Tour - Worksheet – 1 – 3 Marks Page 7


n = len(msg)
new_msg = ‘’
for i in range(0,n):

if not msg[i].isalpha():

ifmsg[i] == ‘ ’:

new_msg = new_msg + ‘#’


else:

new_msg = new_msg + ‘&’

else:

ifmsg[i].isupper():

new_msg = new_msg + msg[i]*2


else:

new_msg = new_msg + msg[i]

returnnew_msg

new_msg = change(“15 Dew Street”)


print(new_msg)

21. Predict the output of the following code:


L1=[10,20,30,40,12,11]
n=2
l=len(L1)
for i in range (0,n):
y=L1[0]
for j in range(0,l-1):
L1[j]=L1[j+1]
L1[l-1]=y
print(L1)

Revision Tour - Worksheet – 1 – 3 Marks Page 8


Grade: 12 Computer Science
Function - Worksheet - 1
1 Marks

1. Find and write the output of the following python code:


a=10
def call():
global a
a=15
b=20
print(a)
call()
2. Which of the following components is part of a function header in Python?
a. Function Name b. Return Statement c. Parameter List d. Both a and c
3. Which of the following function header is correct?
a. def cal_si(p=100, r, t=2) b. def cal_si(p=100, r=8, t)
c. def cal_si(p, r=8, t) d. def cal_si(p, r=8, t=2)
4. Which of the following is the correct way to call a function?
a. my_func() b. def my_func() c. return my_func d. call my_func()

5. What will be the output of the following Python code?


def add (num1, num2):
sum = num1 + num2
sum = add(20,30)
print(sum)
a. 50 b. 0 c. Null d. None
6. What will be the output of the following code?
def my_func(var1=100, var2=200):
var1+=10
var2 = var2 – 10
return var1+var2
print(my_func(50),my_func())
a. 100 200 b. 150 300 c. 250 75 d. 250 300

Function - Worksheet – 1 - 1 Marks Page 1


7. Consider the code given below:

Which of the following statements should be given in the blank for #Missing Statement,
if the output produced is 110?
a. global a b. global b=100 c. global b d. global a=100
8. Write the output of the following Python code :
def Update(X=10):
X += 15
print('X = ', X)
X=20
Update()
print('X = ', X)
9. Which of the following statement(s) would give an error after executing the following
code?
def prod (int a): #Statement 1
d=a*a #Statement 2
print(d) #Statement 3
return prod #Statement 4
(a) Statement 1 and Statement 2 (c) Statement 1 and Statement 4
(b) Statement 1 and Statement 3 (d) Statement 2 and Statement 4
10. Assertion (A) :- A return statement returns a value as well as the control from a
function.
Reasoning (R) :- It is compulsory for all functions to have a return statement.
11. Assertion(A):-If the arguments in function call statement match the Number and
order of arguments as defined in the function definition, such arguments are called
positional arguments.
Reasoning(R):-During a function call, the argument list positional argument(s) must
occur after the default arguments.

Function - Worksheet – 1 - 1 Marks Page 2


13. Assertion (A): The local and global variables declared with the same name in the
function are treated same by the Python interpreter.
Reason (R): The variable declared within the function block is treated to be local variable
where as, the variable declared outside the function block will be referred to as global
variable.
14. Assertion (A): A variable declared as global inside a function is visible with changes
made to it outside the function.
Reasoning (R): All variables declared outside are not visible inside a function till they are
redeclared with global keyword.
15. Assertion (A):- If the arguments in a function call statement match the number and
order of arguments as defined in the function definition, such arguments are called
positional arguments.
Reasoning (R):- During a function call, the argument list first contains default
argument(s) followed by positional argument(s).
16. Assertion (A):- In Python, statement return [expression] exits a function.
Reasoning (R):- Return statement passes back an expression to the caller.A return
statement with no arguments is the same as return None.
17. Assertion (A):- If the arguments in a function call statement match the number and
order of arguments as defined in the function definition, such arguments are called
positional arguments. Reasoning
(R):- During a function call, the argument list first contains default argument(s) followed
by positional argument(s).
18. Assertion(A):Functionisdefinedasasetofstatementswrittenunderaspecificname in the
python code
Reason(R): The complete block (set of statements) is used at different instances in the
program as and when required, referring the function name. It is a common code to
execute for different values(arguments),provided to a function.
19. Assertion: The default value of an argument will be used inside a function if we do
not pass a value to that argument at the time of the function call.
Reason: the default arguments are optional during the function call. It overrides
the default value if we provide a value to the default arguments during function calls.
20. Assertion (A):- The default arguments can be skipped in the function call.
Reasoning (R):- The function argument will take the default values even if the values are
supplied in the function cal

Function - Worksheet – 1 - 1 Marks Page 3


21. Assertion(A):Key word arguments are related to the function calls
Reason(R): When you use keyword arguments in a function call, the caller identifies the
arguments by the parameter name
22. Assertion (A): The function definition calculate(a, b, c=1,d) will give error.
Reason (R): All the non-default arguments must precede the default arguments.
23. Assertion (A):- The number of actual parameters in a function call may not be equal
to the number of formal parameters of the function.
Reasoning (R):- During a function call, it is optional to pass the values to default
parameters
24. What will be output of following code:
X = 50
def funct(X):
X=2
funct (X)
print(“X is now: “, X)
a) X is now: 50 b) X is now: 2 c) Error d) None of the above
25. Which function header statement is correct:-
(a) def interest (prin, time=2, rate):
(b) def interest (prin=2000, time=2, rate):
(c) def interest (prin=2000; time=2; rate)
(d) def interest (prin, time=2, rate=0.10):

Function - Worksheet – 1 - 1 Marks Page 4


Grade: 12 Computer Science
Function - Worksheet - 1
2 Marks

1. What do you understand by local and global scope of variables? How can you access a
global variable inside the function, if function has a variable with same name.
2. What will be the output of the following code?
value = 50
def display(N):
global value
value = 25
if N%7==0:
value = value + N
else:
value = value - N
print(value, end="#")
display(20)
print(value)
3. Predict the output of the Python code given below:
def Diff(N1,N2):
if N1>N2:
return N1-N2
else:
return N2-N1
NUM= [10,23,14,54,32]
for CNT in range (4,0,-1):
A=NUM[CNT]
B=NUM[CNT-1]
print(Diff(A,B),'#', end=' ')
4. Write a function countNow(PLACES) in Python, that takes the dictionary, PLACES as
an argument and displays the names (in uppercase)of the places whose names are
longer than 5 characters. For example, Consider the following dictionary
PLACES={1:"Delhi",2:"London",3:"Paris",4:"New York",5:"Doha"}
The output should be: LONDON NEW YORK

Function - Worksheet – 1 - 2 Marks Page 1


5. Write a function countNow(PLACES) in Python, that takes the dictionary, PLACES as
an argument and displays the names (in uppercase)of the places whose names are
longer than 5 characters.
For example, Consider the following dictionary
PLACES={1:"Delhi",2:"London",3:"Paris",4:"New York",5:"Doha"}
The output should be: LONDON NEW YORK
6. Predict the output of the following code:

7. Find and write the output of the following Python code :


defChangeVal(M,N):
fori in range(N):
if M[i]%5 == 0:
M[i] //= 5
if M[i]%3 == 0:
M[i] //= 3
L=[25,8,75,12]
ChangeVal(L,4)
fori in L :
print(i, end='#')
8. Explain the use of positional parameters in a Python function with the help of a
suitable example.
9. Explain the use of a default parameter in a Python function with the help of a suitable
example.
10. Write a Python method/function SWapPair(COLORS) to swap the alternate values of
the content of a list COLORS and display the final values of COLORS.
Note : Assuming that the list has even number of values in it.
For Example :

Function - Worksheet – 1 - 2 Marks Page 2


If the list COLORS contains ["RED","BLACK","WHITE","PINK", "CYAN","BLUE"]
After swap pair operation the content should be displayed as
BLACK RED PINK WHITE BLUE CYAN
11. Write a Python method/function DispFactors(N) to find and display all the factors of
an integer N (parameter).
For Example : If the value of N is 28 The output should be displayed as 1 2 4 7 14 28
12. Predict the output of the Python code given below:
def CALC (P1,P2):
if P1>P2:
return P1-P2
else:
returnP2-P1
N=[20,25,18,64,42]
for CP in range (3,0,-2):
A=N[CP]
B=N[CP-1]
print(CALC(A,B),'@',end='')
13. Predict the output of the Python code given below:
def div5(n):
if n%5==0:
return n*5
else:
return n+5
def output(m=5):
fori in range(0,m):
print(div5(i),'@',end='')
print()
output(7)
output()
14. Write the output of the code given below:
A= 7
defsum(M, N=4):

Function - Worksheet – 1 - 2 Marks Page 3


global A
A=N+M**2
print(A,end='#')
X,Y=10,5
Y=sum(X,Y)
sum(N=9,M=2)
15. Write a generator function generatesq() that displays the square roots of
numbers from 100 to n where n is passed as an argument .
16. Write a program in Python to input a number and display its each digit reversed.
Example :
If the number is 6534
The program should display 4356
17. Write definition of a Method SEARCHNAME(MEMBERS, NAME) to search and
display the serial number of first presence of a NAME from a list of MEMBERS.
For example :
If the list of MEMBERS contain
["ZAHEEN","TOM","CATHERINE","AMIT","HEENA"]
And
The NAME to search is "CATHERINE"
The following should get displayed 3
18. Write definition of a method OddSum(NUMBERS) to add those values in the list
of NUMBERS, which are odd.
19. Write definition of a Method AFIND(CITIES) to display all the city names from a
list of CITIES, which are starting with alphabet A.
For example :
If the list CITIES contains
["AHMEDABAD","CHENNAI","NEW DELHI","AMRITSAR","AGRA"]
The following should get displayed
AHMEDABAD
AMRITSAR
AGRA
20. Write definition of a method MSEARCH(STATES) to display all the state names from
a list of STATES, which are starting with alphabet M.
For example :

Function - Worksheet – 1 - 2 Marks Page 4


If the list STATES contains
["MP","UP","WB","TN","MH","MZ","DL","BH","RJ","HR"]
The following should get displayed :
MP
MH
MZ
21. Write definition of a method EvenSum(NUMBERS) to add those values in the list of
NUMBERS, which are even.
22. What will be the output of the following code?
x=3
defmyfunc():
global x
x+=2
print(x, end=' ')
print(x, end=' ')
myfunc()
print(x, end=' ')
23. Vivek has written a code to input a number and check whether it is even or odd
number. His codeis having errors. Rewrite the correct code and underline the corrections
made.
defcheckNumber(N):
status = N%2
return
#main-code
num=int( input(“ Enter a number to check :))
k=checkNumber(num)
if k = 0:
print(“This is EVEN number”)
else:

Function - Worksheet – 1 - 2 Marks Page 5


24. Write the output of the code given below:

defprintMe(q,r=2):

p=r+q**3

print(p)
#main-code
a=10
b=5
printMe(a,b)
printMe(r=4,q=2)

25. Write the output of the following code:


def change(m, n=10):
global x
x+=m
n+=x
m=n+x
print(m,n,x)
x=20
change(10)
change(20)

Function - Worksheet – 1 - 2 Marks Page 6


Grade: 12 Computer Science
Function - Worksheet - 1
3 Marks

1. Write a function LShift(Arr,n) in Python, which accepts a list Arr of numbers and n is
a numeric value by which all elements of the list are shifted to left.
Sample Input Data of the list Arr= [ 10,20,30,40,12,11], n=2
Output
Arr = [30,40,12,11,10,20]
2. 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)
print(R,"#",S)
3. Write a function INDEX_LIST(L), where L is the list of elements passed as argument to
the function. The function returns another list named ‘indexList’ that stores the indices
of all Non-Zero Elements of L.
For example: If L contains [12,4,0,11,0,56]
The indexList will have - [0,1,3,5]
4. Find and write the output of the following Python code :
def Call(P=40,Q=20):
P=P+Q
Q=P–Q
print(P,'@',Q)
return
R=200
S=100
R=Call(R,S)
Function - Worksheet – 1 - 3 Marks Page 1
print (R,'@',S)
S=Call(S)
print(R,'@',S)
5. Write the definition of a function Sum3(L) in Python, which accepts a list L of integers
and displays the sum of all such integers from the list L which end with the digit 3.
For example, if the list L is passed [ 123, 10, 13, 15, 23]
then the function should display the sum of 123, 13, 23, i.e. 159 as follows :
Sum of integers ending with digit 3 = 159
6. Find and write the output of the following Python code :
def Compute(A,B,C="*"):
for I in range(A,B+1):
if I%2==0:
print(I,C)
else:
print(I,"@")
print (" " )
Compute(10,14)
Compute(25,29,"#")
Compute(5,10)
7.Write definition of a method/function TenSum(SCORES)to find and display sum of
those scores which are less than 500 and ending with 0.
For example, If the SCORES contain [150,206,370,110,920,530,501,120]
The function should display
Ten Sum: 640
8. Write definition of a method/function NotLess(PRICE, LowPrice) to count and display
number of values of PRICE, which are not less than LowPrice.
For Example :
If the PRICE contains [100,120,103,180,162,113] and LowPrice contains 115
The function should display: 2 Prices are not less than 115
9. Write a function NEW_LIST(L),where L is the list of integers passed as that stores
all the 4 digits integers present in L.
For example:
If L contains[123,3454,0,87511,8612,5678,66]
The New List will have[3454,8612,5678]

Function - Worksheet – 1 - 3 Marks Page 2


10. Write a function ODD_LIST(M),where L is the list of elements passed as argument
to the function. The function returns another list named “indexList
that stores the indices of all odd Elements of M.
For example:
If M contains[12,4,0,11,41,56,3]
The ODD_LIST will have[3,4,6]
11. Kritika was asked to accept a list of even numbers but she did not put the relevant
condition while accepting the list of numbers. You are required to write a code to convert
all the odd numbers into even by multiplying them by 2.
12. Write afunctioninPythonConvert()toreplaceselementshavingevenvalueswithits
halfandelementshaving oddvalueswithtwice itsvalueinalist. eg:ifthelistcontains3,4,5,16,9
then rearrangedlistas6,2,10,8,18
13. Write a function AdjustList(L), where L is a list of integers. The function should
reverse the contents of the list without slicing the list and without using any second list.
Example: If the list initially contains 2, 15, 3, 14, 7, 9, 19, 6, 1, 10,
then after reversal the list should contain 10, 1, 6, 19, 9, 7, 14, 3, 15, 2
14. Write definition of a method/function DoubletheOdd( ) to add and display twice of
odd values from the list of Nums.
For example : If the Nums contains [25,24,35,20,32,41] The function should display
Twice of Odd Sum: 202
15. Write a function INDEX_LIST(L), where L is the list of elements passed as argument
to the function. The function returns another list named ‘indexList’ that stores the
indices of all Elements of L which has a even unit place digit.
For example: If L contains [12,4,15,11,9,56]
The indexList will have - [0,1,5]
16. Write a function INDEX_LIST(S), where S is a string. The function returns a list
named ‘indexList’ that stores the indices of all vowels of S.
For example: If S is "Computer", then indexList should be [1,4,6]
17. Write a Python function to sum all the numbers in a list. Sample List : [8, 2, 3, 0, 7]
Expected Output : 20
18. Write a function in python named SwapHalfList(Array), which accepts a list Array of
numbers and swaps the elements of 1st Half of the list with the 2nd Half of the list ONLY
if the sum of 1st Half is greater than 2nd Half of the list.
Sample Input Data of the list Array= [ 100, 200, 300, 40, 50, 60],

Function - Worksheet – 1 - 3 Marks Page 3


Output Arr = [40, 50, 60, 100, 200, 300]
19. Write a function listchange(Arr)in Python, which accepts a list Arr of numbers , the
function will replace the even number by value 10 and multiply odd number by 5 .
Sample Input Data of the list is:
a=[10,20,23,45]
listchange(a,4)
output : [10, 10, 115, 225]
20. 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
21. Take the two lists, and write a program that returns a list only the elements that are
common between both the lists (without duplicates) in ascending order. Make sure your
program works on two lists of different sizes.
e.g. L1= [1,1,2,3,5,8,13,21,34,55,89]
L2= [20,1,2,3,4,5,6,7,8,9,10,11,12,13]
The output should be: [1,2,3,5,8,13]
22. What will be the output of the following code:-
def change (p, q=50):
p = p+q
q = p-q
print(p, '#', q)
return (p)
r = 300
s = 150
r = change (r,s)
print(r,"#",s)
s = change(s)
print(r,"#",s)
23. What is the output of the following code snippet?
defUpdatev (M, N):
fori in range (N):
if M[i]%5 == 0:
M[i] //= 5

Function - Worksheet – 1 - 3 Marks Page 4


if M[i] %3 == 0:
M[i] //= 3
L = [12, 25, 8, 75]
Updatev (L,4)
fori in L:
print(i, end = "#")
24. Write a function INDEX_LIST(L), where L is the list of elements passed as argument
to the function. The function returns another list named ‘indexList’ that stores the
indices of all Non-Zero Elements of L.
For example: If L contains [12,4,0,11,0,56]
The indexList will have - [0,1,3,5]
25. Write the definition of a function Sum3(L) in Python, which accepts a list L of
integers and displays the sum of all such integers from the list L which end with the
digit 3.
For example, if the list L is passed [ 123, 10, 13, 15, 23] then the function should
display the sum of 123, 13, 23, i.e. 159 as follows :
Sum of integers ending with digit 3 = 159

Function - Worksheet – 1 - 3 Marks Page 5


Grade: 12 Computer Science
Data File Handling
Worksheet - 1
1 Marks

1. The correct syntax of seek() is:


(A) seek(offset [, reference_point]) (B) seek(offset, file_object)
(C) seek.file_object(offset) (D) file_object.seek(offset [, reference_point])
2. Which functions is used to close a file in python?
(A) close (B) cloose() (C) Close() (D) close()
3. Which of the file opening mode will open the file for reading and writing in binary
mode?
a) rb b) rb+ c) wb d) a+
4. Which of the following python statement will bring the read pointer to 10th character
from the end of a file containing 100 characters, opened for reading in binary mode.
a) File.seek(10,0) b) File.seek(-10,2) c) File.seek(-10,1) d) File.seek(10,2)
5.Assertion (A): A binary file in python is used to store collection objects like lists and
dictionaries that can be later retrieved in their original form using pickle module.
Reasoning (R): A binary files are just like normal text files and can be read using a text
editor like notepad.
6. Which of the following mode will refer to binary data? (a)r (b) w (c) + (d) b
7. The correct syntax of seek() is:
(a) file_object.seek(offset [, reference_point])
(b) seek(offset [, reference_point])
(c) seek(offset, file_object)
(d) seek.file_object(offset)
8. Assertion (A): CSV (Comma Separated Values) is a file format for data storage which
looks like a text file.
Reason (R): The information is organized with one record on each line and each field is
separated by comma
9. Which file mode can be used to open a binary file in both append and read mode?
a) w+ b) wb+ c) ab+ d) a+
10. Which option correctly explains tell () method?
a) tells the current position within the file.
b) tells the name of file.
Data File Handling Worksheet - 1 - 1 Marks Page 1
c) moves the current file position to a different location.
d) it changes the file position only if allowed to do so else returns an error.
11. Assertion (A): CSV module allows to write a single record into each row in CSV file
using writerow() function.
Reason (R): The writerow() function creates header row in csv file by default.
12. Which of the following mode in file opening statement results or generates an error if
the file does not exist?
(a) r+ (b) a+ (c) w+ (d) None of the above
13.Assertion (A): A binary file stores the data in the same way as as stored in the
memory.
Reason (R): Binary file in python does not have line delimiter.
14. Which of the following is used to read n characters from a file object“ f1” .
a)f1.read(n) b)f1(2) c)f1(read,2) d)allof the above
15. Which of the following statements correctly explain the function of seek()method?
a. tells the current position with in the file.
b. determines if you can move the file position or not.
c. indicates that the next read or write occurs from that position in a file.
d. moves the current file position to a given specified position.
16. Which of the following is not a valid mode to open a file?
(a) ab (b) r+ (c) w+ (d) rw
17. The tell() function returns:
(a) Number of bytes remaining to be read from the file
(b) Number of bytes already read from the file
(c) Number of the byte written to the file
(d) Total number of bytes in the file
18. Assertion (A): CSV stands for Comma Separated Values
Reason(R): CSV files are a common file format for transferring and storing data
19. Which of the following mode in file opening statement generates an error if the file
does not exist?
a) a+ b) r+ c) w+ d) None of these
20. tell() is a method of: a) pickle module b) csv module c) file object d) seek()

Data File Handling Worksheet - 1 - 1 Marks Page 2


21.Assertion: Pickling is the process by which a Python object is converted to a byte
stream. Reason: load() method is used to write the objects in a binary file. dump()
method is used to read data from a binary file
22. When the file content is to be retained , we can use the ____________ mode . .
(a) r (b) w (c) a (d) w+
23. Which of the following modes is used to open a binary file for writing
(a) b (b) rb+ (c) wb (d) rb
24. Assertion (A):- If a text file already containing some text is opened in write mode the
previous contents are overwritten.
Reasoning (R):- When a file is opened in write mode the file pointer is present at the
beginning position of the file
25. Which of the following mode in file opening statement does not overwrites the any
previous content of the file?
a. w+ b. r+ c. a+ d. None of the above

Data File Handling Worksheet - 1 - 1 Marks Page 3


Grade: 12 Computer Science
Data File Handling
Worksheet - 1
3 Marks

1. Write a function countINDIA() which read a text file ‘myfile.txt’ and print the
frequency
of the words ‘India’ in it (ignoring case of the word).
Example: If the file content is as follows:
INDIA is my country.
I live in India. India has many states.
The countIndia() function should display the output as:
Frequency of India is 3

2. Write a function countVowel() in Python, which should read each character of a text
file“myfile.txt” and then count and display the count of occurrence of vowels (including
small cases and upper case).
Example:
If the file content is as follows:
INDIA is my country. I live in India. India has many states.
The countVowel() function should display the output as:
Total number of vowels are : 20

3. A pre-existing text file data.txt has some words written in it. Write a python function
displaywords() that will print all the words that are having length greater than 3.
Example: For the file content:
A man always wants to strive higher in his life
He wants to be perfect.
The output after executing displayword() will be:
Always wants strive higher life wants perfect
4. A pre-existing text file info.txt has some text written in it. Write a python function
countvowel() that reads the contents of the file and counts the occurrence of
vowels(A,E,I,O,U) in the file.

5. Write a function COUNT_AND( ) in Python to read the text file “STORY.TXT” and count
the number of times “AND” occurs in the file. (include AND/and/And in the counting)

Data File Handling Worksheet – 1 - 3 Marks Page 1


6. Write a function DISPLAYWORDS( ) in python to display the count of words starting
with “t” or “T” in a text file ‘STORY.TXT’.

7. What is the advantage of using a csv file for permanent storage? Write a Program in
Python that defines and calls the following user defined functions:

(i) ADD() – To accept and add data of an employee to a CSV file ‘record.csv’. Each record
consists of a list with field elements as empid, name and mobile to store employee id,
employee name and employee salary respectively.

(ii) COUNTR() – To count the number of records present in the CSV file named
‘record.csv’.

8. Give any one point of difference between a binary file and a csv file. Write a Program
in Python that defines and calls the following user defined functions:

(i) add() – To accept and add data of an employee to a CSV file ‘furdata.csv’. Each record
consists of a list with field elements as fid, fname and fprice to store furniture id,
furniture name and furniture price respectively.

(ii) search()- To display the records of the furniture whose price is more than 10000.

9. Write a function in Phyton to read lines from a text file visiors.txt, and display only
those lines, which are starting with an alphabet 'P'.
If the contents of file is :
Visitors from various cities are coming here.
Particularly, they want to visit the museum.
Looking to learn more history about countries with their cultures.
The output should be:
Particularly, they want to visit the museum
10. Write a method in Python to read lines from a text file book.txt, to find and display
the occurrence of the word 'are'.
For example, if the content of the file is:
Books are referred to as a man’s best friend. They are very beneficial for mankind and
have helped it evolve. Books leave a deep impact on us and are responsible for uplifting
our mood.
The output should be
3

Data File Handling Worksheet – 1 - 3 Marks Page 2


11. Write a method/function DISPLAYWORDS() in python to read lines from a text file
STORY.TXT, and display those words, which are less than 4 characters.
12. Write a function RevText() to read a text file "Story.txt" and Print only word starting
with 'I' in reverse order.
Example:
If value in text file is:
INDIA IS MY COUNTRY
Output will be: AIDNI SI MY COUNTRY.
13. Write a method COUNTLINES() in Python to read lines from text file ‘TESTFILE.TXT’
and display the lines which are starting with any article (a, an, the) insensitive of the
case.
Example: If the file content is as follows:
Give what you want to get.
We all pray for everyone’s safety.
A marked difference will come in our country.
The Prime Minister is doing amazing things.
The COUNTLINES() function should display the output as:
The number of lines starting with any article are : 2
14. Write a function GPCount() in Python, which should read each character of a text file
“STORY.TXT” and then count and display the count of occurrenceof alphabets G and P
individually (including small cases g and p too).
Example: If the file content is as follows:
God helps those who help themselves.
Great way to be happy is to remain positive.
Punctuality is a great virtue.
The GPCount() function should display the output as:
The number of G or g: 3
The number of P or p : 6
15. Write a method count_words_e()in Python to read the content of a textfile and count
the number of words ending with 'e' in the file.
Example: If the file content is as follows:
An apple a day keeps the doctor away.
We all pray for everyone’s safety.
A marked difference will come in our country.

Data File Handling Worksheet – 1 - 3 Marks Page 3


The count_words_e() function should display the output as:
No. of such words: 4
16. Write a function reverseFile()in Python, which should read the content of a text file
“TESTFILE.TXT” and display all its line in the reverse order.
Example: If the file content is as follows:
It rained yesterday.
It might rain today.
I wish it rains tomorrow too.
I love Rain.
The RainCount()function should display the output as:
.yadretseydeniartI
.yadotniarthgimtI
.ootworromotsniartihsiw I
.niaRevol I
17. Write a method/function COUNT_BLANK_SPACES() in Python to read lines from a
text file STORY.TXT, and display the count of blank spaces in the text file.
18. Write a method/function DISPLAYWORDS() in python to read lines from a text file
POEM.TXT, and display those words, which are less than 4 characters
19. Write a function in python to count the number of lines in a text file ‘Country.txt’
which are starting with an alphabet ‘W’ or ‘H’.
For example, If the file contents are as follows:
Whose woods these are I think I know.
His house is in the village though;
He will not see me stopping here
To watch his woods fill up with snow.
The output of the function should be:
W or w : 1
H or h : 2
20. Write a user defined function to display the total number of words present in a text
file 'Quotes.txt'
For example if the file contents are as follows:

Data File Handling Worksheet – 1 - 3 Marks Page 4


Living a life you can be proud of doing your best Spending your time with people and
activities that are important to you Standing up for things that are right even when it’s
hard Becoming the best version of you.
The countwords() function should display the output as:
Total number of words : 40
21. Write a function COUNTLINES( ) which reads a text file STORY.TXT and then count
and display the number of the lines which starts and ends with same letter irrespective
of its case .
For example if the content of the text file STORY.TXT is :
The person has a sent a lovely tweet
Boy standing at station is very disturbed
Even when there is no light we can see
How lovely is the situation
The expected output is :
The Number of lines starting with same letter is 2
22. Write a function VOWEL_WORDS which reads a text file TESTFILE.TXT and then
count and display the number of words starting with vowels ‘a’ or ‘u’ (including capital
cases A and U too)
For example is the text in the file TESTFILE.txt is :
The train from Andaman has earned the name ‘Floating Train’. What is so unique about
this train to receive such a name?
The expected output is :
The Number of words starting with letter ‘a’ is : 3
The Number of words starting with letter ‘u’ is : 1
23. Define a function SHOWWORD () in python to read lines from a text file STORY.TXT,
and display those words, whose length is less than 5.
24. Write a user defined function in python that displays the number of lines starting
with 'H' in the file para.txt
25. Write a function in python to count the number lines in a text file ‘Country.txt’ which
is starting with an alphabet ‘W’ or ‘H’. If the file contents are as follows:
Whose woods these are I think I know.
His house is in the village though;
He will not see me stopping here
To watch his woods fill up with snow.

Data File Handling Worksheet – 1 - 3 Marks Page 5


The output of the function should be:
W or w : 1
H or h : 2

Data File Handling Worksheet – 1 - 3 Marks Page 6


Grade: 12 Computer Science
Data File Handling
Worksheet - 1
4 Marks

1.

Data File Handling Worksheet - 1 - 4 Marks Page 1


2. Sudheer has written a program to read and write using a csv file. He has written the
following code but failed to write completely, leaving some blanks. Help him to complete
the program by writing the missing lines by following the questions a) to d)

_________________ #Statement 1
headings = ['Country','Capital','Population']
data = [['India', 'Delhi',130],['USA','Washington DC',50],[Japan,Tokyo,2]]
f = open('country.csv','w', newline="")
csvwriter = csv.writer(f)
csvwriter.writerow(headings) ________________ #Statement 2
f.close()
f = open('country.csv','r')
csvreader = csv.reader(f)
head = _________________ #Statement 3
print(head)
for x in __________: #Statement 4
ifint(x[2])>50:
print(x)

a) Statement 1 – Write the python statement that will allow Sudheer work with csv files.
b) Statement 2 – Write a python statement that will write the list containing the data
available as a nested list in the csv file
c) Statement 3 – Write a python statement to read the header row in to the head object.
d) Statement 4 – Write the object that contains the data that has been read from the file.
3.Anuj Kumar of class 12 is writing a program to create a CSV file “user.csv” which will
contain user name and password for some entries. He has written thefollowing code. As
a programmer, help him to successfully execute the giventask.
import _____________ # Line 1
def addCsvFile(UserName,PassWord): # to write / add data into the CSV file
f=open(' user.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(' user.csv','r') as newFile:

Data File Handling Worksheet - 1 - 4 Marks Page 2


newFileReader = csv._________(newFile) # Line 3
for row in newFileReader:
print (row[0],row[1])
newFile.______________ # Line 4

addCsvFile(“Arjun”,”123@456”)
addCsvFile(“Arunima”,”aru@nima”)
addCsvFile(“Frieda”,”myname@FRD”)
(a) Name the module he should import in Line 1.
(b) In which mode, Anuj 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.
4. Mr. Deepak is a Python programmer. He has written a code and created a binary
file “MyFile.dat” with empid, ename and salary. The file contains 15 records.
He now has to update a record based on the employee id entered by the user and
update the salary. The updated record is then to be written in the file “temp.dat”. The
records which are not to be updated also have to be written to the file “temp.dat”. If
the employee id is not found, an appropriate message should to be displayed.
As a Python expert, help him to complete the following code based on the
requirement given above:
import _______ #Statement 1
def update_rec():
rec={}
fin=open("MyFile.dat","rb")
fout=open("_____________") #Statement 2
found=False
eid=int(input("Enter employee id to update salary : "))
while True:
try:
rec=______________ #Statement 3
if rec["empid"]==eid:
found=True
rec["salary"]=int(input("Enter new salary : "))
pickle.____________ #Statement 4

Data File Handling Worksheet - 1 - 4 Marks Page 3


else:
pickle.dump(rec,fout)
except:
break
if found==True:
print("The salary of employee id ",eid," has been updated.")
else:
print("No employee with such id is not found")
fin.close()
fout.close()
(i) Which module should be imported in the program? (Statement 1)
(ii) Write the correct statement required to open a temporary file named temp.dat.
(Statement 2)
(iii) Which statement should Deepak fill in Statement 3 to read the data from the binary
file, record.dat and in Statement 4 to write the updated data in the file, temp.dat?
5.Reshabh is a programmer, who has recently been given a task to write a python code
to perform the following binary file operations with the help of two user defined
functions/modules:
a. AddStudents() to create a binary file called STUDENT.DAT containing student
information – roll number, name and marks (out of 100) of each student.
b. GetStudents() to display the name and percentage of those students who have a
percentage greater than 75. In case there is no student having percentage > 75 the
function displays an appropriate message. The function should also display the average
percent.
He has succeeded in writing partial code and has missed out certain statements, so he
has left certain queries in comment lines. You as an expert of Python have to provide the
missing statements and other related queries based on the following code of Reshabh.
import pickle
def AddStudents():
_____________________ # statement 1 to open the binary file to write data
while True:
Rno = int(input("Rno :"))
Name = input("Name : ")
Percent = float(input("Percent :"))

Data File Handling Worksheet - 1 - 4 Marks Page 4


L = [Rno, Name, Percent]
__________________ #statement 2 to write the list L into the file
Choice = input("enter more (y/n): ")
if Choice in "nN":
break
F.close()

def GetStudents():
Total=0
Countrec=0
Countabove75=0
with open("STUDENT.DAT","rb") as F:
while True:
try:
___________________ #statement 3 to read from the file
Countrec+=1
Total+=R[2]
if R[2] > 75:
print(R[1], " has percent =",R[2])
Countabove75+=1
except:
break
if Countabove75==0:
print("No student has percentage more than 75")
print("average percent of class = ",_____________) #statement 4
AddStudents()
GetStudents()
(i) Which of the following commands is used to open the file “STUDENT.DAT” for writing
only in binary format? (marked as #1 in the Python code)
(ii) Which of the following commands is used to write the list L into the binary file,
STUDENT.DAT? (marked as #2 in the Python code)
(iii) Which of the following commands is used to read each record from the binary file
STUDENT.DAT? (marked as #3 in the Python code)

Data File Handling Worksheet - 1 - 4 Marks Page 5


(iv) What expression will be placed in statement 4 to print the average percent of the
class.
6. Arun is a class XII student of computer science. The CCA in-charge of his school
wants to display the words form a text files which are less than 4 characters. With the
help of his computer teacher Arun has developed a method/function FindWords() for
him in python which read lines from a text file Thoughts. TXT, and display those words,
which are lesser than 4 characters. His teachers kept few blanks in between the code
and asked him to fill the blanks so that the code will run to find desired result. Do the
needful with the following python code.
def FindWords():
c=0
file=open(‘NewsLetter.TXT’, ‘_____’) #Statement-1
line = file._____ #Statement-2
word = _____ #Statement-3
for c in word:
if _____: #Statement-4
print(c)
_________ #Statement-5
FindWords()
(i) Write mode of opening the file in statement-1?
(ii) Fill in the blank in statement-2 to read the data from the file.
(iii) Fill in the blank in statement-3 to read data word by word
(iv) Fill in the blank in statement-4, which display the word having lesser than 4
characters OR (Only for iii and iv above)
(v) Fill in the blank in Statement-5 to close the file.
(vi) Which method of text file will read only one line of the file?
7. Tushar is a Python programmer. He has written a code and created a binary file
record.dat with employeeid, ename and salary. The file contains 10 records.
He now has to delete a record based on the employee id entered by the user. For this
purpose, he creates a temporary file, named temp.dat, to store all the records other than
the record to be deleted. If the employee id is not found, an appropriate message should
to be displayed.

Data File Handling Worksheet - 1 - 4 Marks Page 6


As a Python expert, help him to complete the following code (by completing statements 1,
2, 3, and 4) based on the requirement given above:
(i) Complete Statement#1 to import the required module.
(ii) Write the correct statement required to open a temporary file named temp.dat.
(#Statement 2)
(iii) Which statement should Aman fill in Statement 3 to read the data from the binary
file, record.dat
(iv) What should be written in Statement 4 to write the required records in the file
temp.dat
import ___________ #Statement 1
def update_data():
rec={}
fin=open("record.dat","rb")
fout=open("____________","___") #Statement 2
found=False
eid=int(input("Enter employee id: "))
while True:
try:
rec= ________________ #Statement 3
if rec["Employee id"]==eid:
found=True else: _________________ #Statement 4
except:
break
if found==True:
print("Record deleted.")
else:
print("Employee with such id is not found")
fin.close()
fout.close()
8. Ashok Kumar of class 12 is writing a program to create a CSV file “empdata.csv” with
empid, name and mobile no and search empid and display the record. He has written
the following code. As a programmer, help him to successfully execute the given task.
import _____ #Line1

Data File Handling Worksheet - 1 - 4 Marks Page 7


fields=['empid','name','mobile_no']
rows=[['101','Rohit','8982345659'],['102','Shaurya','8974564589'],
['103','Deep','8753695421'],['104','Prerna','9889984567'], ['105','Lakshya','7698459876']]
filename="empdata.csv"
with open(filename,'w',newline='') as f:
csv_w=csv.writer(f,delimiter=',')
csv_w.___________ #Line2
csv_w.___________ #Line3
with open(filename,'r') as f:
csv_r=______________(f,delimiter=',') #Line4
ans='y'
whileans=='y':
found=False
emplid=(input("Enter employee id to search="))
for row in csv_r:
iflen(row)!=0:
if _____==emplid: #Line5
print("Name : ",row[1])
print("Mobile No : ",row[2])
found=True
break
if not found:
print("Employee id not found")
ans=input("Do you want to search more? (y)")
(a) Name the module he should import in Line 1.
(b) Write a code to write the fields (column heading) once from fields list in Line2.
(c) Write a code to write the rows all at once from rows list in Line3.
(d) Fill in the blank in Line4 to read the data from a csv file.
(e) Fill in the blank to match the employee id entered by the user with the empid of
record from a file in Line5
9. 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

Data File Handling Worksheet - 1 - 4 Marks Page 8


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:
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
(b) In which mode, Priti should open the file to print data.
(c) Fill in the blank in Line 2 to open the file.
(d) Fill in the blank in Line3 to read the data from a csv file.
(e) Write the output he will obtain while executing the above program.
10. Anuj Kumar of class 12 is writing a program to create a CSV file “user.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(' user.csv','________') # Line 2
newFileWriter = csv.writer(f)
newFileWriter.writerow([UserName,PassWord])
f.close() #csv file reading code

Data File Handling Worksheet - 1 - 4 Marks Page 9


def readCsvFile(): # to read data from CSV file
with open(' user.csv','r') as newFile:
newFileReader = csv._________(newFile) # Line 3
for row in newFileReader:
print (row[0],row[1])
newFile.______________ # Line 4
addCsvFile(“Arjun”,”123@456”)
addCsvFile(“Arunima”,”aru@nima”)
addCsvFile(“Frieda”,”myname@FRD”)
readCsvFile() #Line 5
(a) Name the module he should import in Line 1.
(b) In which mode, Anuj 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.
11. Krishna of class 12 is writing a program to read the details of Sports performance
and store in the csv file “Sports.csv” delimited with a tab character. As a programmer,
help him to achieve the task.
import ___________ # Line 1
f = open(“Sports.csv”,”a”)
wobj = csv.______________ (f, delimiter = ‘\t’) # Line 2
wobj.writerow( [‘Sport’, ‘Competitions’, ‘Prizes Won’] )
ans = ‘y’
i=1
while ans == ‘y’:
print(“Record :”, i)
sport = input(“Sport Name :”)
comp = int(input(“No. of competitions participated :”))
prize = int(input(“Prizes won:”))
record = ____________________ # Line 3
wobj.______________ (rec) # Line 4
i += 1
ans = input(“Do u want to continue ? (y/n) :”)
f.___________ # Line 5

Data File Handling Worksheet - 1 - 4 Marks Page 10


a) Name the module he should import in Line 1
b) To create an object to enable to write in the csv file in Line 2
c) To create a sequence of user data in Line 3
d) To write a record onto the writer object in Line 4
e) Fill in the blank in Line 5 to close the file.
12. Abhisar is making a software on “Countries & their Capitals” in which various
records are to be stored/retrieved in CAPITAL.CSV data file. It consists some
records(Country & Capital). He has written the following code in python. As a
programmer, you have to help him to successfully execute the program.
import ___________ # Statement-1
def AddNewRec(Country,Capital): # Fn. to add a new record in CSV file
f=open(“CAPITAL.CSV”,_________) # Statement-2
fwriter=csv.writer(f)
fwriter.writerow([Country,Capital])
f.__________ # Statement-3
def ShowRec(): # Fn. to display all records from CSV file
with open(“CAPITAL.CSV”,”r”) as NF:
NewReader=csv.___________(NF) # Statement-4
for rec in NewReader:
print(rec[0],rec[1])
AddNewRec(“INDIA”,”NEW DELHI”)
AddNewRec(“CHINA”,”BEIJING”)
ShowRec() # Statement-5
(a) Name the module to be imported in Statement-1.
(b)Write the file mode to be passed to add new record in Statement-2.
(c) Fill in the blank in Statement-3 to close the file.
(d)Fill in the blank in Statement-4 to read the data from a csv file.
(e) Write the output which will come after executing Statement-5.
13. 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

Data File Handling Worksheet - 1 - 4 Marks Page 11


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:
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.
14.Parth Patel of class 12 is writing a program to create a CSV file “emp.csv” which will
contain employee code and name of some employees. He has written the following code.
As a programmer, help him to successfully execute the given task.
import #Line 1
def addemp(empcode,name):#to write/add data into the CSV file
fo=open('emp.csv','a')
writer=csv. (fo) #Line 2
writer.writerow([empcode,name])
fo.close() #csv file reading code
def reademp():
with open('emp.csv',' ') as fin: #Line 3
filereader=csv.reader(fin)
for row in filereader:
for data in row:
print(data,end='\t')

Data File Handling Worksheet - 1 - 4 Marks Page 12


print(end='\n')
fin.________ #Line 4
addemp('E105','Parth')
addemp("E101",'Arunima')
addemp("E102",'Prahalad') reademp() #Line 5
Answer the following questions: (1 mark each)
(a) Name the module he should import in Line 1.
(b) Fill in the blank in Line 2 to write the data in a CSV file.
(c) In which mode, Parth should open the file to read the data from the file(Line 3).
(d) Fill in the blank in Line 4 to close the file.
(e) Write the output he will obtain while executing Line 5.
15. Amit Kumar of class 12 is writing a program to store roman numbers and find their
equivalents using a dictionary. He has written the following code. As a programmer, help
him to successfully execute the given task.
import __________ #Line 1
numericals = {1: ‘I’, 4 : ‘IV’, 5: ‘V’ , 9: ‘IX’, 10:’X’, 40:’XL’,50:’L’, 90:’XC’,
100:’C’,400:’CD’,500:’D’,900:’CM’,1000:’M’}
file1 = open(“roman.log”,”_______”) #Line 2
pickle.dump(numerals,file1)
file1.close()
file2 = open(“roman.log”,’________”) #Line 3
num = pickle.load(file2)
file2.__________ #Line 4
n=0
while n!=-1:
print(“Enter 1,4,5,9,10,40,50,90,100,400,500,900,1000:”)
print(“or enter -1 to exit”)
n = int(input(“Enter numbers”))
if n!= -1:
print(“Equivalent roman number of this numeral is:”,num[n])
else:
print(“Thank You”)
(a) Name the module he should import in Line 1.
(b) In which mode, Amit should open the file to add data into the file in Line #2

Data File Handling Worksheet - 1 - 4 Marks Page 13


(c) Fill in the blank in Line 3 to read the data from a binary file.
(d) Fill in the blank in Line 4 to close the file.
(e) Write the output he will obtain while input is 100
16. Ranjan Kumar of class 12 is writing a program to create a CSV file “user.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(' user.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(' user.csv','r') as newFile:
newFileReader = csv._________(newFile) # Line 3
for row in newFileReader: p
rint (row[0],row[1])
newFile.______________ # Line 4
addCsvFile(“Arjun”,”123@456”)
addCsvFile(“Arunima”,”aru@nima”)
addCsvFile(“Frieda”,”myname@FRD”)
readCsvFile() #Line 5
(a) Name the module he should import in Line 1.
(b) In which mode, Ranjan 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.
17.MOHIT of class 12 is writing a program to search a name in a CSV file “MYFILE.csv”.
He has written the following code. As a programmer, help him to successfully execute
the given task.
import _________ # Statement 1
f = open("MYFILE.csv", _______) # Statement 2
data = ____________ ( f ) # Statement 3
nm = input("Enter name to be searched: ")

Data File Handling Worksheet - 1 - 4 Marks Page 14


for rec in data:
if rec[0] == nm:
print (rec) f.________( ) # Statement 4
(a) Name the module he should import in Statement 1.
(b) In which mode, MOHIT should open the file to search the data in the file in statement
2?
(c) Fill in the blank in Statement 3 to read the data from the file.
(d) Fill in the blank in Statement 4 to close the file.
(e) Write the full form of CSV.
18. Tushar is a Python programmer. He has written a code and created a binary file
record.dat with employeeid, ename and salary. The file contains 10 records.
He now has to delete a record based on the employee id entered by the user. For this
purpose, he creates a temporary file, named temp.dat, to store all the records other than
the record to be deleted. If the employee id is not found, an appropriate message should
to be displayed.
As a Python expert, help him to complete the following code (by completing statements 1,
2, 3, and 4) based on the requirement given above:
(i) Complete Statement #1 to import the required module.
(ii) Write the correct statement required to open a temporary file named temp.dat.
(#Statement 2)
(iii) Which statement should Aman fill in Statement 3 to read the data from the binary
file, record.dat
(iv) What should be written in Statement4 to write there records in the file temp.dat?
import ______________ #Statement1
def update_data():
rec={} fin=open("record.dat","rb")
fout=open(" ","") #Statement2
found=False
eid=int(input("Enter employee id:")) while True:
try:
rec= __________ #Statement3
if rec["Employee id"]==eid:
found=True
else:

Data File Handling Worksheet - 1 - 4 Marks Page 15


____________ #Statement 4
except:
break
if found==True:
print("Recorddeleted.")
else:
print("Employee with such id is notfound")
fin.close()
fout.close()

19. Gupta is writing a program to create a csv file “employee.csv” which will
contain user name and password for department entries. He has written the
following code . As a programmer, help him to successfully execute the given
task.
import ---------------- #statement 1
def add_emp(username,password):
f=open(‘employee.csv’, ’----------‘) # statement 2
content=csv.writer(f)
content.writerow([username,password])
f.close()
def read_emp( ):
with open (‘employee.csv’,’r’) as file:
content_reader=csv.-------------------(file) # statement 3
for row in content_reader:
print(row[0],row[1])
file.close( )
add_emp(‘mohan’,’emp123#’)
add_emp(‘ravi’,’emp456#’)
read_emp() #statement 4
i) Name the module he should import in statement 1
ii) In which mode , Gupta should open the file to add record in to the file ? (statement 2)
iii) Fill in the blank in statement 3 to read the record from a csv file
iv) What output will he obtain while executing statement 4 ?

Data File Handling Worksheet - 1 - 4 Marks Page 16


20. Anamika is a Python programmer. She has written a code and created a binary file
data.dat with sid, sname and marks. The file contains 10 records.
She now has to update a record based on the sid entered by the user and update the
marks. The updated record is then to be written in the file extra.dat. The records which
are not to be updated also have to be written to the file extra.dat. If the sid is not found,
an appropriate message should to be displayed.
As a Python expert, help him to complete the following code based on requirement given
above:
import ……………. #Statement 1
def update_data():
rec={}
fin=open("data.dat","rb")
fout=open("______________________") #Statement 2
found=False
eid=int(input("Enter student id to update their marks :: "))
while True:
try:
rec= #Statement 3
if rec["student id"]==sid:
found=True
rec["marks"]=int(input("Enter new marks:: "))
pickle.____________ #Statement 4
except:
break
if found==True:
print("The marks of student id ",sid," has been updated.")
else:
print("No student with such id is not found")
fin.close()
fout.close()
(i) Which module should be imported in the program? (Statement 1)
(ii) Write the correct statement required to open a temporary file named extra.dat.
(Statement 2)
(iii) Which statement should Anamika fill in Statement 3 to read the data from the

Data File Handling Worksheet - 1 - 4 Marks Page 17


binary file, data.dat and in Statement 4 to write the updated data in the file, extra.dat?
21. Write a Program in Python that defines and calls the following user defined
functions:
Add_New():
To accept record of Player and add to ‘playerdata.csv’ file. The record of player
consists P_id, P_name and P_runs in form of python list.
Display_Record():
To read the records of Player from ‘playerdata.csv’ file and display the record of
player whose runs are more than 5000.
22. A csv file “ result.csv” contains record of student in following order
[rollno, name, sub1,sub2,sub3,total]
Initially student total field is empty string as example data is given below
['1', 'Anil', '40', '34', '90', '']
['2', 'Sohan', '78', '34', '90', '']
['3', 'Kamal', '40', '45', '9', '']
A another file “final.csv” is created which reads records of “result.csv” and copy all
records after calculating total of marks into final.csv. The contents of final.csv
should be
['1', 'Anil', '40', '34', '90', '164']
['2', 'Sohan', '78', '34', '90', '202']
['3', 'Kamal', '40', '45', '9', '94']
(a) Define a function createcsv() that will create the result.csv file with the sample data
given above.
(b) Define a function copycsv() that reads the result.csv and copy the same data after
calculating total field into final.csv file.
23. Biplab is a Python programmer. He has written a code and created a binary file
STUDENT.DAT which has structure (admission_number, Name, Percentage).
He has written an incomplete 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%.As a Python expert, help him to complete the following code based on the
requirement given above:
import __________ #statement1
def countrec():

Data File Handling Worksheet - 1 - 4 Marks Page 18


_____________________ #Statement2
records=_______________ #Statement3
count=0
for record in records:
if(_______________):#Statement4
count=count+1
print("ID",record[0])
print("NAME",record[1])
print("PERCENTAGE",record[2])
print("No of students with perentage above 75",count)
(i) Which module should be imported in the program? (Statement1)
(ii) Write the correct statement required to open a file named STUDENT.DAT. in binary
mode (Statement2)
(iii) Which statement should Biplab fill in Statement 3 to read the data from the binary
file, STUDENT.DATand in Statement 4 to check thepercentage?
24. What is CSV file?
Write a program using two functions :
(a) addCustomer( ): To write Customer code, Customer name and Amt in file “cust.csv”.
The details of the customers are as follows :
[‘CustCode’, ‘CustName’, ‘Amount’]
[‘001’, ‘Nihir’, ‘8000’] [‘104’, ‘Akshay’, ‘5000’]
(b) readCustomer( ): To read the details of the customers and display them.
25. When do we use CSV file?
Write a program using following functions :
(a) getlnventory() : Write code to accept as many inventory records and store them to the
csv file Inventory.csv storing records of inventory as per following structure
PCode Invname Price Reorder
(b) Display() : To display the detail that store in Inventory.csv
25. Does python create a file itself if the file doesn’t exist in the memory? Illustrate your
answer with an example:
Write a program using following functions :
(a) inputStud() :To input details of as many students and add them to a csv file
“college.csv” without removing the previous records.
SrNo Studname City Percentage

Data File Handling Worksheet - 1 - 4 Marks Page 19


(b) readCollege() : To open the file “college.csv” and display records whose city is
“Kolkata”

Data File Handling Worksheet - 1 - 4 Marks Page 20


Grade: 12 Computer Science
Data File Handling
Worksheet - 1
5 Marks

1.

2.

2. Write the full form of ‘CSV’. What is the default delimiter of csv files? The scores and ranks of
three students of a school level programming competition is given as: [‘Name’, ‘Marks’, ‘Rank’]
[‘Sheela’, 450, 1]
[‘Rohan’, 300, 2]
[‘Akash’, 260, 3]
Write a program to do the following:
(i) Create a csv file (results.csv) and write the above data into it.
(ii) To display all the records present in the CSV file named ‘results.csv’
OR
What does csv.writer object do?
3. Rohan is making a software on “Countries & their Capitals” in which various records are to
be stored/retrieved in CAPITAL.CSV data file. It consists some records(Country & Capital).
Help him to define and call the following user defined functions:
(i) AddNewRec(Country,Capital) – To accept and add the records to a CSV file
“CAPITAL.CSV”. Each record consists of a list with field elements as Country and
Capital to store country name and capital name respectively.
(ii) ShowRec() – To display all the records present in the CSV file named ‘CAPITAL.CSV’

Data File Handling Worksheet – 1 - 5 Marks Page 1


4.A binary file data.dat needs to be created with following data written it in the form of
Dictionaries.

Write the following functions in python accommodate the data and manipulate it.
a) A function insert() that creates the data.dat file in your system and writes the three
dictionaries.
b) A function() read() that reads the data from the binary file and displays the dictionaries whose
age is 16.
5.(a) What does CSV stand for?
(b) Write a Program in Python that defines and calls the following user defined functions:
(i) InsertRow() – To accept and insert data of an student to a CSV file ‘class.csv’. Each record
consists of a list with field elements as rollno, name and marks to store roll number, student’s
name and marks respectively.
(ii) COUNTD() – To count and return the number of students who scored marks greater than 75
in the CSV file named ‘class.csv’
6. Dhirendra is a programmer, who has recently been given a task to write a python code to
perform the following CSV file operations with the help of two user defined functions/modules:
a. CSVOpen() : to create a CSV file called BOOKS.CSV in append mode containing information of
books – Title, Author and Price.
b. CSVRead() : to display the records from the CSV file called BOOKS.CSV where the field title
starts with 'R'. He has succeeded in writing partial code and has missed out certain statements,
so he has left certain queries in comment lines.
importcsv
def CSVOpen():
with open('books.csv','_____',newline='') as csvf: #Statement-1
cw=_____________#Statement-2
__________________#Statement-3
cw.writerow(['Rapunzel','Jack',300])
cw.writerow(['Barbie','Doll',900])
cw.writerow(['Johnny','Jane',280])
def CSVRead():
try:
with open('books.csv','r') as csvf:
cr=_________________#Statement-4
for r in cr: if : #Statement-5

Data File Handling Worksheet – 1 - 5 Marks Page 2


print(r)
except:
print('File Not Found')
CSVOpen()
CSVRead()
You as an expert of Python have to provide the missing statements and other related queries
based on the following code of Raman.
(i) Choose the appropriate mode in which the file is to be opened in append mode (Statement 1)
(ii) Which statement will be used to create a csv writer object in Statement 2.
(iii) Choose the correct option for Statement 3 to write the names of the column headings in the
CSV file, BOOKS.CSV.
(iv) Which statement will be used to read a csv file in Statement 4.
(v) Fill in the appropriate statement to check the field Title starting with ‘R’ for Statement 5 in the
above program
7.(a) What one advantage and one disadvantage of using a binary file for permanent storage?
(b) Write a Program in Python that defines and calls the following user defined functions: (i)
ADD() – To accept and add data of an item to a CSV file ‘events.csv’. Each record consists of
Event_id, Description, Venue, Guests, and Cost.
(ii) COUNTR() – To read the data from the file events.csv, calculate and display the average
number of guests and average cost.
8. (a) Give any one point of difference between a binary file and a text file.
(b) Write a Program in Python that defines and calls the following user definedfunctions: (i) ADD()
– To accept and add data of an item to a binary file ‘events.dat’. Each record of the file is a list
[Event_id, Description, Venue, Guests, Cost]. Event_Id, Description, and venue are of str type,
Guests and Cost are of int type.
(ii) COUNTR() – To read the data from the file events.dat, calculate and display the average
number of guests and average cost
9. Manoj Kumar of class 12 is writing a program to create a CSV file “user.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 ______________ #Line1
def addCsvFile(UserName, Password):
fh=open('user.csv','_____________') #Line2
Newfilewriter=csv.writer(fh)
Newfilewriter.writerow([UserName,Password])
fh.close( )
# csv file reading code

Data File Handling Worksheet – 1 - 5 Marks Page 3


def readCsvFile(): #to read data from CSV file
with open('user.csv','r') as newFile:
newFileReader=csv.______(newFile) #Line3
for row in newFileReader:
print(row)
newFile.________________ #Line4
addCsvFile('Arjun','123@456')
addCsvFile('Arunima','aru@nima')
addCsvFile('Frieda','myname@FRD')
readCsvFile()
OUTPUT___________________ #Line 5
(a) What module should be imported in #Line1 for successful execution of the program? (b) In
which mode file should be opened to work with user.csv file in#Line2
(c) Fill in the blank in #Line3 to read data from csv file
(d) Fill in the blank in #Line4 to close the file (e) Write the output he will obtain while executing
Line5
10.Radha Shah is a programmer, who has recently been given a task to write a python code to
perform the following CSV file operations with the help of two user defined functions/modules:
(a) . CSVOpen() : to create a CSV file called “ books.csv” in append mode containing information
of books – Title, Author and Price.
(b). CSVRead() : to display the records from the CSV file called “ books.csv” .where the field title
starts with 'R'.
She has succeeded in writing partial code and has missed out certain statements, so she has left
certain queries in comment lines.
Import csv
def CSVOpen( ):
with open('books.csv','______',newline='') as csvf: #Statement-1
cw=______ #Statement-2
______ #Statement-3
cw.writerow(['Rapunzel','Jack',300])
cw.writerow(['Barbie','Doll',900])
cw.writerow(['Johnny','Jane',280])
def CSVRead( ):
try:
with open('books.csv','r') as csvf:
cr=______ #Statement-4
for r in cr:

Data File Handling Worksheet – 1 - 5 Marks Page 4


if ______: #Statement-5
print(r)
except:
print('File Not Found')
CSVOpen( )
CSVRead( )
You as an expert of Python have to provide the missing statements and other related queries
based on the following code of Radha.
(a) Write the appropriate mode in which the file is to be opened in append mode (Statement 1)
(b) Which statement will be used to create a csv writer object in Statement 2.
(c) Write the correct option for Statement 3 to write the names of the column headings in the
CSV file, books.csv
(d) Write statement to be used to read a csv file in Statement 4.
(e) Fill in the appropriate statement to check the field Title starting with „R for Statement 5 in
the above program.
11. 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”
12. 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%
13. Vijay 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): # write data into the CSV file
f=open(' mydata.csv','________') # Line 2
newFileWriter = csv.writer(f)
newFileWriter.writerow([UserName,PassWord])
f.close()
def readCsvFile(): # read data from CSV file
with open('mydata.csv','r') as newFile:
newFileReader = csv._________(newFile) # Line 3
for row in newFileReader:

Data File Handling Worksheet – 1 - 5 Marks Page 5


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

addCsvFile(“Aman”,”123@456”)
addCsvFile(“Vijay”,”aru@nima”)
addCsvFile(“Raju”,”myname@FRD”)
readCsvFile()
(i) Give Name of the module he should import in Line 1.
(ii) In which mode, Vijay should open the file to add data into the file in Line2.
(iii) Complete the Line 3 to read the data from csv file and Line 4 to close the file
14. What is the significance of a delimiter symbol in a csv file? Write a Program in Python that
defines and calls the following user defined functions:
(i) ADD_CONT() – To accept and add data of a contact to a CSV file ‘address.csv’. Each record
consists of a list with field elements as contId, cname and cmobile to store contact id, contact
name and contact number respectively.
(ii) COUNT_CONT() – To count the number of records present in the CSV file named ‘address.csv’
15. How csv file is different from a binary file? Write a Program in Python that defines and calls
the following user defined functions:
(i) save() – To accept and add data of watches to a CSV file ‘watchdata.csv’. Each record consists
of a list with field elements as watchid, wname and wprice to store watch id, watch name and
watch price respectively.
(ii) search()- To display the records of the watch whose price is more than 6000.
16. Vaishanavi is a budding Python programmer. She has written a code and created a binary
file phonebook.dat with contactNo, name and blocked [ Y/ N ]. The file contains 10 records as a
dictionary like {‘contactNo’ : 32344455 , ‘name’: ‘kamalkant’ ,’blocked’ : “Y” }
She now wants to shift all the records which have blocked = ‘Y’ status from phonebook.dat to a
binary file blocked.dat also all records which have blocked = ‘N’ status from phonebook.dat to
unblocked.dat. She also wants to keep count and print the total number of blocked and
unblocked records. As a Python expert, help her to complete the following code based on the
requirement given above:
import _____________ #Statement 1
def shift_contact( ):
fin = open(“phonebook.dat”,’rb’)
fblock = open( ___________________ ) #Statement 2
funblock = open( ___________________ ) #Statement 3
while True :
try: rec = __________________ # Statement 4

Data File Handling Worksheet – 1 - 5 Marks Page 6


if rec[“blocked”] == ‘Y’:
pickle.__________________ #Statement 5
if rec[“blocked”] == ‘N’:
Pickle. ________________ # Statement 6
except:
break
(i) Which module should be imported in the program? (Statement 1)
(ii) Write the correct statement required to open a blocked.dat and unblocked.dat binary files
(Statement 2 and 3)
(iii) which statement should Vaishnavi use in statement 4 to read the data from the binary file,
phonebook.dat
(iv) which statement should Vaishnavi use in statement 5 and 6 to write data to the blocked.dat
and unblocked.dat
17.Sumit is a programmer who is working on a project that requires student data of a school to
be stored in a CSV file. Student data consists of roll no, name, class and section. He has written
a program to obtain the student data from user and write it to a CSV file. After getting errors in
the program he left five statements blank in the program as shown below. Help him to find the
answer of the following questions to find the correct code for missing statements. #Incomplete
Code
import_____ #Statement 1
fh = open(_____, _____, newline=‘ ’) #Statement 2
stuwriter = csv._____ #Statement 3
data = []
header = [‘ROLL_NO’, ‘NAME’, ‘CLASS’, ‘SECTION’]
data.append(header)
for i in range(5):
roll_no = int(input(“Enter Roll Number : ”))
name = input(“Enter Name : ”)
Class = input(“Class : ”)
section = input(“Enter Section : ”)
rec = [_____] #Statement 4
data.append(rec)
stuwriter. _____ (data) #Statement 5
fh.close()
(i) Identify the suitable code for blank space in line marked as Statement 1.
(ii) Identify the missing code for blank space in line marked as Statement 2.

Data File Handling Worksheet – 1 - 5 Marks Page 7


(iii) Choose the function name (with argument) that should be used in the blank space of line
marked as Statement 3.
(iv) Identify the suitable code for blank space in line marked as Statement 4.
(v) Choose the function name that should be used in the blank space of line marked as
Statement 5 to create the desired CSV file?
18. What are the advantages of binary file over text file? Write a Python program in Python to
search the details of the employees (name, designation and salary) whose salary is greater than
5000. The records are stored in the file emp.dat. consider each record in the file emp.dat as a list
containing name, designation and salary.
19. (a) What is the advantage of using a csv file for permanent storage?
(b) Write a Program in Python that defines and calls the following user defined functions: (i)
ADD() – To accept and add data of an item to a CSV file ‘furniture.csv’. Each record consists of
Fur_id, Description, Price, and Discount.
(ii) COUNTR() – To count the number of records present in ‘furniture.csv’ whose price is less than
5000.
20. (a) Give any one point of difference between a binary file and a csv file.
(b) Write a Program in Python that defines and calls the following user defined functions: (i)
ADD() – To accept and add data of an item to a binary file ‘furniture.dat’. Each record of the file
is a list [Fur_id, Description, Price, and Discount]. Fur_Id and Description are of str type, Price is
of int type, and Discount is of float type.
(ii) COUNTR() – To count the number of records present in ‘furniture.dat’ whose price is less than
5000.
21. Given a binary file “emp.dat” has structure (Emp_id, Emp_name, Emp_Salary). Write a
function in Python countsal() in Python that would read contents of the file “emp.dat” and
display the details of those employee whose salary is greater than 20000.
22. A binary file “Stu.dat” has structure (rollno, name, marks).
(i) Write a function in Python add_record() to input data for a record and add to Stu.dat. (ii) Write
a function in python Search_record() to search a record from binary file “Stu.dat” on the basis of
roll number
23. 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

Data File Handling Worksheet – 1 - 5 Marks Page 8


HARI
SHANKER
Function should display
Total Names beginning from “S” are 2
24. Consider the following CSV file (emp.csv):
Sl,name,salary
1,Peter,3500
2,Scott,4000
3,Harry,5000
4,Michael,2500
5,Sam,4200
Write Python function DISPEMP( ) to read the content of file emp.csv and display only those
records where salary is 4000 or above
25. Consider an employee data, Empcode, empname and salary. Write python function to create
binary file emp.dat and store their records. 2. write function to read and display all the records

Data File Handling Worksheet – 1 - 5 Marks Page 9


Exception Handling
Worksheet – 1
1. In a try-except block, can there be multiple 'except' clauses?
a) No, there can be only one 'except' clause.
b) Yes, but only if the exceptions are of the same type.
c) Yes, it allows handling different exceptions separately.
d) No, 'except' clauses are not allowed in a try-except block.

2. When might you use the 'finally' block in exception handling?

a) To handle exceptions that are expected to occur frequently.


b) To provide a resolution for every possible error.
c) To close resources that were opened in the 'try' block, regardless of whether an
exception occurred or not.
d) To avoid having to use 'except' blocks.

3. What will be the output of the following code snippet?

a) Division by zero! b) Arithmetic error occurred!


c) No error! d) This code will raise a syntax error.
4. Which of the following is NOT a standard built-in exception in Python?
a) ValueError b) IndexError c) NullPointerException d) KeyError
5. What is an exception in programming?
a) An error that occurs during runtime b) A warning message from the compiler
c) A comment in the cod d) A statement that terminates the program
6. What is the purpose of the "try" block in a try-except construct?
a) To handle the exception by executing specific code
b) To specify the type of exception to be thrown
c) To define a custom exception class
d) To ensure a specific block of code always executes

7. Which of the following exceptions in Python is not a built-in exception?


a) ValueError b) KeyError c) CustomError d) IndexError

A. Both A and R are true and R is correct explanation of A


B. Both A and R are true but R is not correct explanation of A
C. A is True but R is False
D. R is True but A is False

Exception Handling – Worksheet 1 – 1 Marks Page 1


8. Assertion (A): In Python, the "try" block is used to enclose code that might raise an
exception.
Reasoning (R): The "try" block is where the program attempts to execute code that might
result in an exception. If an exception occurs, it is handled in the corresponding "except"
block.
9. Assertion (A): The "finally" block in Python is always executed, regardless of whether
an exception is raised or not.
Reasoning (R): The "finally" block contains code that is guaranteed to execute, whether
an exception occurs within the "try" block or not.
10. Assertion (A): Python allows multiple "except" blocks to be used within a single "try"
block to handle different exceptions.
Reasoning (R): By using multiple "except" blocks with different exception types, Python
provides the flexibility to handle various types of exceptions separately.
11. Code snippet:

Predict the output when:


a) The user enters "0" . b) The user enters "5".
c) The user enters "abc".
12. State whether the following statement is True or False:
An exception may be raised even if the program is syntactically correct.
13. What will be the output of the following code if the input is “e”:
try:
value = int("abc")
result = 10 / 0
except ValueError:
print("Error: Invalid value conversion")
except ZeroDivisionError:
print("Error: Division by zero")
14. What will be the output of the following code if the input is: i. 2 ii. 2.2
try:
num = int(input("Enter a number: "))
except ValueError:
print("Error: Invalid input")
else:
print("Entered number: ",num)

15.Rewrite the following code after handling all possible exceptions.


num = int(input("Enter a number: "))

Exception Handling – Worksheet 1 – 1 Marks Page 2


result = 10 / num
print("Result:", result)

16. Consider the code given below:


L = [‘s’, 45, 23]
Result = 0
for x in L:
print (“The element is “, x)
Result += x
print(“The addition of all elements of L is: “, Result)
Which of the following error will be raised by the given Python code?
a) NameError b) ValueError c) TypeError d) IOError
17. Code snippet:

Predict the output when:


a) The user enters "10" for both numbers.
b) The user enters "5" for the first number and "0" for the second number.
c) The user enters "abc" for both numbers.

18. Which of the following statements is true?


a). The standard exceptions are automatically imported in Python programs.
b). All raised standard exceptions must be handled in Python.
c). When there is deviation from the rules of a programming language, a semantic error
is thrown.
d). If any exception is thrown in try block, else block is executed.
19. Identify the statement(s) from the following options which will raise TypeError
exception(s):
a) print('5') b) print( 5 * 3) c) print('5' +3) d) print('5' + '3')
20. What is an exception in Python?
a) An error b) A warning c) A function d) A class

21. Which keyword is used to raise an exception explicitly in Python?


a) catch b) throw c) raise d) try

22. What is the purpose of the 'finally' block in a try-except statement?


a) To handle exceptions b) To specify alternative code

Exception Handling – Worksheet 1 – 1 Marks Page 3


c) To execute cleanup code d) To suppress errors

23. Which of the following is not an exception handling clause in Python?


a) try b) except c) else d) throw

24. What will be the output of the following code?


try:
print(10 / 0)
except ZeroDivisionError:
print("Error: Division by zero")
a) Error: Division by zero b) Error: Index out of range

c) 10 d) None of the above

25. In a try-except block, if an exception occurs but it is not handled by any except
clause, what happens?
a) The program terminates b) The exception is ignored
c) The program continues to execute normally d) None of the above

Exception Handling – Worksheet 1 – 1 Marks Page 4


Grade: 12 Computer Science
Data Structure
Worksheet 1
3 Marks

1. A list contains following record of a student:


[StudentName, Class, Section, MobileNumber]
Write the following user defined functions to perform given operations on the stack
named ‘xiia’:
(i) pushElement() - To Push an object containing name and mobile number of students
whobelong to class xii and section ‘a’ to the stack
(ii) popElement() - To Pop the objects from the stack and display them. Also, display
“Stack
Empty” when there are no elements in the stack.
For example:
If the lists of students details are:
[“Rajveer”, “99999999999”,”XI”, “B”]
[“Swatantra”, “8888888888”,”XII”, “A”]
[“Sajal”,”77777777777”,”VIII”,”A”]
[“Yash”, “1010101010”,”XII”,”A”]
The stack “xiia” should contain
[“Swatantra”, “8888888888”]
[“Yash”, “1010101010”]
The output should be:
[“Yash”, “1010101010”]
[“Swatantra”, “8888888888”]
Stack Empty
2. Write a function in Python, Push(SItem) where, SItem is a dictionary containing the
details ofstationary items– {Sname:price}.
The function should push the names of those items in the stack who have price greater
than 25.
Also display the count of elements pushed into the stack.
For example:
If the dictionary contains the following data:

Data Structure Worksheet 1 - 3 Marks Page 1


Ditem = {“Rubber”:5, "Pencil":5, "Pen":30, "Notebook": 60, "Eraser":5, “Watch”: 250}
The stack should contain
Pen
Notebook
Watch
The output should be:
The count of elements in the stack is 3
3. A dictionary contains the names of some cities and their population in crore. Write a
python function push(stack, data), that accepts an empty list, which is the stack and
data, which is the dictionary and pushes the names of those countries onto the stack
whose population is greater than 25 crores.
For example : The data is having the contents
{'India':140, 'USA':50, 'Russia':25, 'Japan':10} then the execution of the function push()
should push India and USA on the stack.
4. A list of numbers is used to populate the contents of a stack using a function
push(stack, data) where stack is an empty list and data is the list of numbers. The
function should push all the numbers that are even to the stack. Also write the function
pop() that removes the top element of the stack on its each call.
5. Write a program to perform push operations on a Stack containing Student details as
given in the following definition of student node:
RNo integer
Name String
Age integer
defisEmpty(stk):
ifstk == [ ]:
return True
else:
return False
defstk_push(stk, item):
# Write the code to push student details using stack.
6. Write a program to perform pop operations on a Stack containing Student details as
given in the following definition of student node:
RNo integer
Name String

Data Structure Worksheet 1 - 3 Marks Page 2


Age integer
defisEmpty(stk):
ifstk == [ ]:
return True
else:
return False
defstk_pop(stk): # Write the code to pop a student using stack
7. Write a function in Python PUSH(Num), where Num 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 atleast one element, otherwise display appropriate error message.
For example: If the list Num is: [66, 75, 40, 32, 10, 54]
The stack should contain: [75, 40, 10]
8. Write functions in Python, MakePush(Package) and MakePop(Package) to add a new
Package and delete a Package from a List of Package Description, considering them to
act as push and pop operations of the Stack data structure.
9. A list contains following record of a customer:
[Customer_name, Phone_number, City]
Write the following user defined functions to perform given operations on the stack
named ‘status’:
(i) Push_element() -
To Push an object containing name and Phone number of customers who live in Goa to
the stack
(ii) Pop_element() - To Pop the objects from the stack and display them. Also,
display “Stack Empty” when there are no elements in the stack.
For example:
If the lists of customer details are:
[“Ashok”, “9999999999”,”Goa”]
[“Avinash”, “8888888888”,”Mumbai”]
[“Mahesh”,”77777777777”,”Cochin”]
[“Rakesh”, “66666666666”,”Goa”]
The stack should contain:
[“Rakesh”,”66666666666”]
[“Ashok”,” 99999999999”]
The output should be:

Data Structure Worksheet 1 - 3 Marks Page 3


[“Rakesh”,”66666666666”]
[“Ashok”,”99999999999”]
Stack Empty
10. Write Add_New(Book) and Remove(Book) methods in Python to Add a new
Book and Remove a Book from a List of Books, considering them to act as
PUSH and POP operations of the data structure stack.
11. Aalia has a list containing 10 integers. You need to help him create a program
with separate user defined functions to perform the following operations
based on this list.
➢ Traverse the content of the list and push the even numbers into a stack.
➢ Pop and display the content of the stack.
For example:
If the sample content of the list is as follows:
N=[12,13,34,56,21,79,98,22,35,38]
Sample output of the code should be:
38 22 98 56 34 12
12. A nested list contains the data of visitors in a museum. Each of the inner
listscontains
the following data of a visitor:
[V_no (int), Date (string), Name (string), Gender (String M/F), Age (int)]
Write the following user defined functions to perform given operations on the stack
named "status":
Push_element(Visitors) - To Push an object containing Gender of visitor who
are in the age range of 15 to 20.
Pop_element() - To Pop the objects from the stack and count the display the number of
Male and Female entries in the stack. Also, display “Done” when
there are no elements in the stack
For example: If the list Visitors contains:
[['305', "10/11/2022", “Geeta”,"F”, 35],
['306', "10/11/2022", “Arham”,"M”, 15],
['307', "11/11/2022", “David”,"M”, 18],
['308', "11/11/2022", “Madhuri”,"F”, 17],
['309', "11/11/2022", “Sikandar”,"M”, 13]]

Data Structure Worksheet 1 - 3 Marks Page 4


The stack should contain
F
M
M
The output should be:
Done
Female: 1
Male: 2
13. Pramod has created a dictionary containing EMPCODE and SALARY as key value
pairs of 5 Employees of Parthivi Constructions.
Write a program, with separate user defined functions to perform the following
operations:
● Push the keys (Employee code) of the dictionary into a stack, where the corresponding
value (Salary) is less than 25000.
● Pop and display the content of the stack.
For example: If the sample content of the dictionary is as follows:
EMP={"EOP1":16000, "EOP2":28000, "EOP3":19000, "EOP4":15000, EOP5":30000}
The output from the program should be: EOP4 EOP3 EOP1
14.Write a function POP(Arr) , where Arr is a stack implemented by a list of numbers The
function returns the value deleted from the stack.
15. Write a function in Python PushBook(Book) to add a new book entry as book_no and
book_title in the list of Books , considering it to act as push operations of the Stack data
structure.
16. Write a function in Python PopBook(Book), where Book is a stack implemented by a
list of books. The function returns the value deleted from the stack
17. A dictionary contains records of a tourist place like :
Tour_dict = { ‘Name’: ‘Goa’ , ‘PeakSeason’ : ‘December’ , ‘Budget’ : 15000 ,
‘Famous’:’Beaches’}
Write the following user defined functions to perform given operations on the stack
named
‘tour’:
(i) Push_tour( Tour_dict) – To Push a list containing values for Name and PeakSeason
wherevalue of budget is less than 10000 into the tour stack
(ii) Pop_tour() – To Pop the list objects from the stack and display them. Also, display

Data Structure Worksheet 1 - 3 Marks Page 5


“Nomore tours” when there are no elements in the stack.
For example if the following dictionaries are passed to Push_tour( ) function in the
followingsequence:
{ ‘Name’: ‘Goa’ , ‘PeakSeason’ : ‘December’ , ‘Budget’ : 15000 , ‘Famous’:’Beaches’}
{ ‘Name’: ‘Nainital’ , ‘PeakSeason’ : ‘May’ , ‘Budget’ : 9000 , ‘Famous’:’Nature’}
{ ‘Name’: ‘Sikkim’ , ‘PeakSeason’ : ‘May’ , ‘Budget’ : 9500 , ‘Famous’:’Mountains’}
{ ‘Name’: ‘Kerala’ , ‘PeakSeason’ : ‘November’ , ‘Budget’ : 15000 , ‘Famous’:’Back Waters’}
{ ‘Name’: ‘Orissa’ , ‘PeakSeason’ : ‘January’ , ‘Budget’ : 8000 , ‘Famous’:’Temples’}
Then the stack ‘tour’ will contain :
[ ‘Orrisa’ , ‘January’]
[‘Sikkim’, ‘May’]
[‘Nainital’ ,’ May’]
The output produced when calling pop_tour( ) function should be :
[ ‘Orrisa’ , ‘January’]
[‘Sikkim’, ‘May’]
[‘Nainital’ ,’ May’]
No more tours
18. Write a function in Python, Push(stack, SItem) where , SItem is a List containing
the detailsof stationary items in a format like – [Name , price , Unit , Company , MRP ].
The function should push the company names of those items in the stack whose price is
10% percent less than its MRP. Also write a function print_stack( ) to display the Item
Names and the count of Items pushed into the stack.
For example:
If following data is passed to the function:
[ ‘Pen’ , 120.00 , ‘Pcs.’ , ‘Reynolds’ , 132.00 ]
[‘Paper’, 345.00 , ‘Rim’ , ‘Camel’, 500.00]
[Eraser , 100.00 , ‘Box’ , ‘IBP’ , 110.00
The stack should contain
Eraser
Pen
The output should be:
The count of elements in the stack is 2

Data Structure Worksheet 1 - 3 Marks Page 6


19. Write PushOn(Book) and Pop(Book) methods/functions in Python to add a new Book
and delete a Book from a list of Book titles, considering them to act as push and pop
operations of the Stack data structure.
20. Mr.Ajay has created a list of elements. Help him to write a program in python with
functions, PushEl(element) and PopEl(element) to add a new element and delete an
element from a List of element Description, considering them to act as push and pop
operations of the Stack data structure. Push the element into the stack only when the
element is divisible by 4.
For eg:if L=[2,5,6,8,24,32]
then stack content will be 32 24 8
21. Write a function AddCustomer(Customer) in Python to add a new Customer
information NAME into the List of CStack and display the information.
22. Write a function DeleteCustomer() to delete a Customer information from a list of
CStack. The function delete the name of customer from the stack.
23.Write a program to perform push operations on a Stack containing Student details as
given in the following definition of student node:
RNo integer
Name String
Age integer
defisEmpty(stk):
ifstk == [ ]:
return True
else:
return False
defstk_push(stk, item):
# Write the code to push student details using stack
24. Write a program to perform push operations on a Stack containing Student details
as given in the following definition of student node:
RNo integer
Name String
Age integer
defisEmpty(stk):
ifstk == [ ]:

Data Structure Worksheet 1 - 3 Marks Page 7


return True
else:
return False
defstk_pop(stk):
# Write the code to pop a student using stack.
25. Write A Function Python, Make Push(Package) and Make Pop (Package) to add a new
Package and delete a Package form a List Package Description, considering them to act
as push and pop operations of the Stack data structure.

Data Structure Worksheet 1 - 3 Marks Page 8


Grade: 12 Computer Science
DBMS
Worksheet - 1
1 Marks
1. Fill in the blank:
The SELECT statement when combined with ________ clause, returns records without
repetition.
(A) DISTINCT (B) DESCRIBE (C) UNIQUE (D) NULL
2. Which function is used to display the total number of records from a table in a
database?
(A) total() (B) total(*) (C) return(*) (D) count(*)
3. In order to open a connection with MySQL database from within Python using
mysql.connector package, __________ function is used.
(A) open (B) connect (C) database() (D) connectdb()
4. Fill in the blank: ________ command is used to change table structure in SQL.
(A) update (B) change (C) alter (D) modify
5. Which of the following commands will remove the entire database from MYSQL?
(A) DELETE DATABASE (B) DROP DATABASE
(C) REMOVE DATABASE (D) ALTER DATABASE
6. Fill in the blank:
_____ is a non-key attribute, whose values are derived from the primary key of some
other table.
(A) Primary Key (B) Candidate Key (C) Foreign Key (D) Alternate Key
7. Which of the following statements is True?
a) There can be only one Foreign Key in a table.
b) There can be only one Unique key is a table
c) There can be only one Primary Key in a Table
d) A table must have a Primary Key.
8. Which of the following is not part of a DDL query?
a) DROP b) MODIFY c) DISTINCT d) ADD
9. _______________ Keyword is used to obtain unique values in a SELECT query
a) UNIQUE b) DISTINCT c) SET d) HAVING
10. Which statement in MySql will display all the tables in a database?
a) SELECT * FROM TABLES; b) USE TABLES;

DBMS Worksheet – 1 - 1 Marks Page 1


c) DESCRIBE TABLES; d) SHOW TABLES;
11. Which of the following is a valid sql statement?
a) ALTER TABLE student SET rollnoINT(5);
b) UPDATE TABLE student MODIFY age = age + 10;
c) DROP FROM TABLE student;
d) DELETE FROM student;
12.Which of the following is not valid cursor function while performing database
operations using python. Here Mycur is the cursor object?
a) Mycur.fetch() b) Mycur.fetchone()
c) Mycur.fetchmany(n) d) Mycur.fetchall()
13. Fill in the blank: ______ command is used to remove a column from a table in SQL.
(a) update (b)remove (c) alter (d)drop
14. Which of the following commands will delete the rows of table?
(a) DELETE command (b) DROP Command
(c) REMOVE Command (d) ALTER Command
15. Fill in the blank: All tuples in the relation are assigned NULL as the value for the
new Attribute, with the ________ Command
(a) MODIFY (b) TAILOR (c)ELIMINATE (d) ALTER
16. Which of the following ignores the NULL values inSQL?
a) Count(*) b) count() c)total(*) d)None of these
17. Which of the following is not a legal method for fetching records from a database
from within a Python program?
(a) fetchone() b)fetchtwo() (c) fetchall() (d) fetchmany()
18. Which of the following statements is True?
a) There can be only one Foreign Key in a table.
b) There can be only one Unique key is a table
c) There can be only one Primary Key in a Table
d) A table must have a Primary Key.
19. Fill in the blank:
The SQL built-in function _______ calculates the average of values in numeric columns.
(a) MEAN() (b)AVG() (c) AVERAGE() (d) COUNT()

DBMS Worksheet – 1 - 1 Marks Page 2


20. Which of the following commands will be used to select a particular database named
“Student” from MYSQL Database?
(a) SELECT Student; (b) DESCRIBE Student;
(c) USE Student; (d) CONNECT Student;
21. Fill in the blank:
An attribute in a relation is a foreign key if it is the ________ key inany other relation.
(a) Candidate Key (b) Foreign Key (c) Primary Key (d) Unique Key
22. Fill in the blank:
When two conditions must both be true for the rows to be selected, theconditions are
separated by the SQL keyword ________
(a)ALL (b)IN (c)AND (d)OR
23. Which statement in SQL allows to change the definition of a table is
(a) Alter (b) Update. (c) Create (d) select
24. The statement which is used to get the number of rows fetched byexecute() method
of cursor:
(a) cursor.rowcount (b) cursor.rowscount()
(c) cursor.allrows() (d) cursor.countrows()
25. Fill in the blank: The SQL built-in function _______ calculates the average of values
in numeric columns.
(a) MEAN() (b)AVG() (c) AVERAGE() (d) COUNT()

DBMS Worksheet – 1 - 1 Marks Page 3


Grade: 12 Computer Science
DBMS
Worksheet - 1
2 Marks
1. Explain the use of ‘Foreign Key’ in a Relational Database Management System. Give
example to support your answer
2. Differentiate between order by and group by clause in SQL with appropriate example.
3. Categorize the following commands as DDL or DML: INSERT, UPDATE, ALTER, DROP
4.Mention two differences between a PRIMARY KEY and a UNIQUE KEY.
5. A MySQL table, sales have 10 rows. The following queries were executed on the sales
table.
SELECT COUNT(*) FROM sales; SELECT COUNT(discount) FROM sales;
Count(*) Count(discount)
10 6
Write a statement to explain as to why there is a difference in both the counts.
6. What is the difference between a Candidate Key and an Alternate Key
7. Differentiate between DDL and DML with one Example each.
8. Write the output of the queries (a) to (d) based on the table

(a) SELECT min(Population) FROM country;

(b) SELECT max(SurfaceArea) FROM country Where Lifeexpectancy<50;

(C)SELECT avg(LifeExpectancy) FROM country Where CName Like "%G%";

(d) SELECT Count(Distinct Continent) FROM country;

DBMS - Worksheet – 1- 2 Marks Page 1


9.
(a) Identify the candidate key(s) from the
table Country.
(b) Consider the table CAPITAL given below:
Which field will be considered as the foreign
key if the tables COUNTRY and CAPITAL are
related in a database?

10. Write two points of difference between ALTER and UPDATE command in SQL.
11. Categorize the following commands as DDL or DML: DROP, DELETE, SELECT,
ALTER
12. Explain the use of primary key in a relational database system? Give example to
support your answer?
13. Define Tuple and Attribute with appropriate example.
14. Explain the use of “Primary key in a Relational Database Management System.
Give example to support your answer
15. Differentiate between DDL and DML?
16. Write the main difference between INSERT and UPDATE Commands in SQL
17. Differentiate between ‘WHERE’ clause and ‘HAVING’ clause in MySQL with
appropriate example.
18. Differentiate between DELETE and DROP keywords used in MySQL,giving suitable
example for each
19. Define Primary Key of a relation in SQL. Give an Example using a dummy table.
20. Consider the following Python code is written to access the record of CODE passed to
function: Complete the missing statements:
def Search(eno):
#Assume basic setup import, connection and cursor is created
query="select * from emp where empno=________".format(eno)
mycursor.execute(query)
results = mycursor._________
print(results)
21. What is a cursor and how to create it in Python SQL connectivity?
22. What is Degree and Cardinality in relational table?
23. Answer the following :

DBMS - Worksheet – 1- 2 Marks Page 2


i) Name the package for connecting Python with MySQL database.
ii) What is the purpose of cursor object?
24 What do understand by an Alternate key? Give a suitable example to support your
answer.
25. What do you mean by domain of an attribute in DBMS? Explain with an example.

DBMS - Worksheet – 1- 2 Marks Page 3


Grade: 12 Computer Science
DBMS
Worksheet - 1
3 Marks
1. Write the output of the queries (i) to (vi) based on the table given below:

(i) Select BRAND_NAME, FLAVOUR from CHIPS where PRICE <> 10;
(ii) Select * from CHIPS where FLAVOUR=”TOMATO” and PRICE > 20;
(iii) Select BRAND_NAME from CHIPS where price > 15 and QUANTITY < 15;
(iv) Select count( distinct (BRAND_NAME)) from CHIPS;
(v) Select price , price *1.5 from CHIPS where FLAVOUR = “PUDINA”;
(vi) Select distinct (BRAND_NAME) from CHIPS order by BRAND_NAME desc;
2.(A) Consider the following tables BOOKS and ISSUED in a database named “LIBRARY”.
WriteSQL commands for the statements (i) to (iv).

(i) Display book name and author name and price of computer type books.
(ii) To increase the price of all history books by Rs 50.
(iii) Show the details of all books in ascending order of their prices.
(iv) To display book id, book name and quantity issued for all books which have been
issued.
(B)Write the command to view all tables in a database.

DBMS Worksheet - 1 - 3 Marks Page 1


3. The code given below inserts the following record in the table Student:

Note the following to establish connectivity between Python and MySQL:


* Username is root
* Password is toor@123
* The table exists in a “stud” database.
* The details (RollNo, Name, Clas and Marks) are to be accepted from the user.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object

4. Write the outputs of the SQL queries (i) to (iii) based on the relations Teacher and
Posting given below:

1. SELECT count(DISTINCT Address) FROM Consumer;

DBMS Worksheet - 1 - 3 Marks Page 2


2.SELECT Company, MAX(Price), MIN(Price), COUNT(*) from Stationary GROUP BY
Company;
SELECT Consumer.ConsumerName, Stationary.StationaryName, Stationary.Price FROM
Stationary, Consumer WHERE Consumer.S_ID = Stationary.S_ID;
5. Write a output for SQL queries (i) to (iii), which are based on the table: SCHOOL and
ADMIN given below:

1. SELECT SUM (PERIODS), SUBJECT FROM SCHOOL GROUP BY SUBJECT;


2. SELECT TEACHERNAME, GENDER FROM SCHOOL, ADMIN WHERE DESIGNATION
= ‘COORDINATOR’ AND SCHOOL.CODE=ADMIN.CODE;
3. SELECT COUNT (DISTINCT SUBJECT) FROM SCHOOL;
6. The code given below reads the following record from the table named studentand
displays only those records who have marks greater than 75:
RollNo – integer
Name – string
Class – integer
Marks – integer
Note the following to establish connectivity between Python and MYSQL:
• Username is root
• Password is tiger
• The table exists in a MYSQL database named school.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the query that extracts records of those students whose marks
are greater than 75.
Statement 3- to read the complete result of the query (records whose 2+3 marks are
greater than 75) into the object named data, from the table student in the database.
import mysql.connector as mysql
def sql_data():

DBMS Worksheet - 1 - 3 Marks Page 3


con1=mysql.connect(host="localhost",user="root", password="tiger",
database="school")
mycursor=_______________ #Statement 1
print("Students with marks greater than 75 are : ")
_________________________ #Statement 2
data=__________________ #Statement 3
for i in data:
print(i)
print()
7. (a) Consider the following tables – Applicants and Centre

What will be the output of the following statement?


SELECT * FROM Applicants NATURAL JOIN Centre;
(b) Write the output of the queries (i) to (iv) based on the table, Car given below:

(i) SELECT DISTINCT MAKE FROM CAR;


(ii) SELECT MAKE, COUNT(*) FROM CAR GROUP BY MAKE;
(iii) SELECT CNAME FROM CAR WHERE CAPACITY>5 ORDER BY CNAME;
(iv) SELECT CNAME, MAKE FROM CAR WHERE CHARGES>2500
8. (a) Consider the following tables EMPLOYEE and SALARY

DBMS Worksheet - 1 - 3 Marks Page 4


Give the output of the following SQL queries:
(i) SELECT COUNT(SGRADE), SGRADE FROM EMPLOYEE GROUP BY SGRADE;
(ii) SELECT MIN(DOB), MAX(DOJ) FROM EMPLOYEE;
(iii) SELECT NAME, SALARY FROM EMPLOYEE E, SAL S WHERE
E.SGRADE=S.SGRADE AND E.ECODE<103;
(iv) SELECT SGRADE, SALARY+HRA FROM SAL WHERE SGRADE= ‘S02’;
(b) Write the command to view structure of table FOOD in a database.
9. The code given below inserts the following record in the table Student:
Rollno – integer
Name – string
Age – integer
Note the following to establish connectivity between Python and MYSQL:
• Username is root
• Password is sys
• The table exists in a MYSQL database named school.
• The details (Rollno, Name and Age) are to be accepted from the user.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the command that inserts the record in the table Student.
Statement 3- to add the record permanently in the database
import mysql.connector
mydb= mysql.connector.connect(host="localhost",user="root",passwd="sys", database =
“myschool”)
mycursor = ______________ #statement 1
while True:
ch=int(input("enter -1 to exit , any other number to insert record"))
if ch==-1:
break
rollno = int(input("enter Roll no:"))
name = input("enter Name:")
age = int(input("enter Age:"))
qry = "insert into student values ({},'{}',{})".format(rollno,name,age)
_________________________ #statement 2
_________________________ #statement 3

DBMS Worksheet - 1 - 3 Marks Page 5


print(“Data added successfully”)
10. The code given below adds a new column in the table Student, updates the data into
it and displays the content of the table. Student table details are as follows:
Rollno – integer
Name – string
Age – integer
Note the following to establish connectivity between Python and MYSQL:
• Username is root
• Password is sys
• The table exists in a MYSQL database named school.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute a query that adds a column named “MARKS” of type integer in
the table Student.
Statement 3- to update the record permanently in the database
import mysql.connector
mydb= mysql.connector.connect(host="localhost",user="root",passwd="sys",
database="myschool")
mycursor = _____________________ #statement1
________________________________ #statement2
mycursor.execute("update student set MARKS=9 where Rollno = 1")
______________________________ #statement3
mycursor.execute("select * from student")
for x in mycursor:
print(x)
11. a. Consider the following tables – Sales and Item:

What will be the output of the following statement?


SELECT SNAME,SCITY,IPRICE FROM sales, Item where SCITY=”Delhi” and Sales.SCode
=Item.SCode;

DBMS Worksheet - 1 - 3 Marks Page 6


b. Write the output of the queries (i) to (iv) based on the table, TABLE: EMPLOYEE

12. a. Consider the following tables ACTIVITY and COACH.Write SQL commands for the
statements (i) to (iv) and give the The outputs for the SQL queries (v) to (viii)
Table: Activity

(i) To display the name of all activities with their Acodes in descending order.
(ii) To display sum of PrizeMoney for each of the number of participants groupings (as
shown in column ParticipantsNum 10,12,16)
(iii) To display the coach’s name and ACodes in ascending order of ACode from the table
COACH.
(iv) To display the content of the Activity table whose ScheduleDate is earlier than
01/01/2004 in ascending order of ParticipantsNum.

DBMS Worksheet - 1 - 3 Marks Page 7


(b) Write the command to view all tables in a database.
13. (a)Consider the following tables – Bank_Account and Branch:
Bank_Account: Branch:

What will be the output of the following statement?


SELECT * FROM Bank_Account NATURAL JOIN Branch;
(b) Give the output of the following sql statements as per table given above.
Table : SPORTS

i. SELECT COUNT(*) FROM SPORTS.


ii. SELECT DISTINCT Class FROM SPORTS.
iii. SELECT MAX(Class) FROM SPORTS;
iv. SELECT COUNT(*) FROM SPORTS GROUP BY Game1;
14. (a) consider the following tables School and Admin and answer the following
questions:

TABLE: SCHOOL TABLE : ADMIN

Give the output of the following SQL queries:


i. Select Designation, count(*) from Admin Group by Designation having
count(*)<2;
ii. Select max(experience) from school;
iii. Select teacher from school where experience >12 order by teacher;

DBMS Worksheet - 1 - 3 Marks Page 8


iv. Select count(*), gender from admin group by gender;
(b) Write SQL command to delete a table from database.
15. (a) Consider the following table:
Table: Employee

What is the degree and cardinality of table Employee, if it contains only the given data?
Which field fields is/are the most suitable to be the Primary key if the data shown above
is only the partial data?
(b) Write the output of the queries (i) to (iv) based on the table Employee:
(i) select name, project from employee order by project;
(ii) select name, salary from employee where doj like'2015%';
(iii)select name, salary from employee where salary between 100000 and 200000;
(iv) select min(doj), max(dob) from employee;
16. (a) Write the outputs of the SQL queries (i) to (iv) based on the relations Projects and
Employee given below:

(i) select project, count(*) from employee group by project;


(ii) selectpid, pname, eid, name from projects p,employee e where p.pid=e.project;
(iii) select min(startdate), max(startdate) from projects;
(iv) selectavg(salary) from employee where doj between '2018-08-19' and '2018-08-31';
(b) Write the command to make Projects column of employee table a foreign key which
refers to PID column of Projects table.
17. (a)Write SQL query to add a column total price with datatype numeric and size 10, 2
in a table product.

DBMS Worksheet - 1 - 3 Marks Page 9


(b) Consider the following tables SCHOOL and ADMIN. Give the output the following SQL
queries:
Table: School Table: Admin

i.SELECT Designation COUNT (*) FROM Admin GROUP BY Designation HAVING COUNT
(*) <2:
ii.SELECT max (EXPERIENCE) FROM SCHOOL;
iii. .SELECT TEACHER FROM SCHOOL WHERE EXPERIENCE >12 ORDER BY
TEACHER;
iv.SELECT COUNT (*), GENDER FROM ADMIN GROUP BY GENDER;
18. (a)Sonal needs to display name of teachers, who have “0” as the third character in
their name. She wrote the following query.
SELECT NAME FROM TEACHER WHERE NAME = “$$0?”;
But the query is’nt producing the result. Identify the problem.
(b)Write output for (i) & (iv) based on table COMPANY and CUSTOMER

i. SELECT COUNT(*) , CITY FROM COMPANY GROUP BY CITY;


ii. SELECT MIN(PRICE), MAX(PRICE) FROM CUSTOMER WHERE QTY>10;
iii. SELECT AVG(QTY) FROM CUSTOMER WHERE NAME LIKE “%r%;
iv. SELECT PRODUCTNAME, CITY, PRICE FROM COMPANY, CUSTOMER WHERE
COMPANY.CID=CUSTOMER.CID AND PRODUCTNAME=”MOBILE”;
19. (a) Differentiate between Natural join and Equi join.
Table: Employee Table: Job

DBMS Worksheet - 1 - 3 Marks Page 10


Give the output of following SQL statement:
(i) Select Name, JobTitle, Sales from Employee, Job where
Employee.JobId=Job.JobId and JobId in (101,102);
(ii) (ii) Select JobId, count(*) from Employee group by JobId;
20. (a) Consider the following table GAMES. Give outputs for SQL queries (i) to (iv).
Table: GAMES

(i) SELECT COUNT(DISTINCT Number) FROM GAMES;


(ii) SELECT MAX(ScheduleDate),MIN(ScheduleDate) FROM GAMES;
(iii) SELECT SUM(PrizeMoney) FROM GAMES;
(iv) SELECT * FROM GAMES WHERE PrizeMoney> 12000;
21. (a) Consider the following tables – EMPLOYEES AND DEPARTMENT

What will be the output of the following statement?


SELECT ENAME, DNAME FROM EMPLOYEES, DEPARTMENT WHERE
EMPLOYEE.DNO=DEPARTMENT.DNO;
(b) Write the output of the queries (i) to (iv) based on the tables given below:

i) SELECT ITEM_NAME, MAX(PRICE), COUNT(*) FROM ITEM GROUP BY ITEM_NAME;

DBMS Worksheet - 1 - 3 Marks Page 11


ii) SELECT CNAME, MANUFACTURER FROM ITEM, CUSTOMER WHERE
ITEM.ID=CUSTOMER.ID;
iii) SELECT ITEM_NAME, PRICE*100 FROM ITEM WHERE MANUFACTURER="ABC";
(iv) SELECT DISTINCT CITY FROM CUSTOMER;

22. (a) Write the outputs of the SQL queries (i) to (iv) based on the relations SCHOOL
and ADMIN given below:
Table: School Table: Admin

(i) SELECT SUM (PERIODS), SUBJECT FROM SCHOOL GROUP BY SUBJECT;


(ii) SELECT TEACHERNAME, GENDER FROM SCHOOL, ADMIN WHERE DESIGNATION
= ‘COORDINATOR’ AND SCHOOL.CODE=ADMIN.CODE;
(iii) SELECT COUNT (DISTINCT SUBJECT) FROM SCHOOL;
(iv) SELECT MAX(PERIODS) FROM SCHOOL;
(b) Write the command to view the structure of a table SCHOOL
23. Write the outputs of the SQL queries (a) to (c) based on the relation Furniture

(a) SELECT Itemname FROM Furniture WHERE Type="Double Bed";


(b) SELECT MONTHNAME(Dateofstock) FROM Furniture WHERE Type="Sofa";
(c) SELECT Price*Discount FROM Furniture WHERE Dateofstock>31/12/02;

DBMS Worksheet - 1 - 3 Marks Page 12


24. Consider the following table GAMES

Write the output for the following queries :


(i) SELECT COUNT(DISTINCT Number) FROM GAMES;
(ii) SELECT MAX(ScheduleDate),MIN(ScheduleDate) FROM GAMES;
(iii) SELECT SUM(PrizeMoney) FROM GAMES;
25. Consider the table

The Following program code is used to increase the salary of Trainer SUNAINA by 2000.
Note the following to establish connectivity between Python and MYSQL:
 Username is root
 Password is system
 The table exists in a MYSQL database named Admin.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the command that inserts the record in the table Student.
Statement 3- to add the record permanently in the database
import mysql.connector as mydb
mycon = mydb.connect (host = “localhost”, user = “root”, passwd = “system”, database =
“Admin”)
cursor = _______________ #Statement 1
sql = “UPDATE TRAINER SET SALARY = SALARY + 2000 WHERE TNAME = ‘SUNAINA’”
cursor. _______________ #Statement 2
_______________ #Statement 3
mycon.close( )

DBMS Worksheet - 1 - 3 Marks Page 13


Grade: 12 Computer Science
DBMS
Worksheet - 1
4 Marks
1. Tarun created the following table in MySQL to maintain stock for the items he has.

Based on the above table answer the following questions.


a) Identify the primary key in the table with valid justification.
b) What is the degree and cardinality of the given table.
c) Write a query to increase the stock for all products whose company is Parley.
OR (only for part)
c) Write a query to delete all the rows from the table which are not having any rating
2. The code given below search the following record in the table Student:

DBMS Worksheet – 1 - 4 Marks Page 1


3. a) Consider the following tables Emp and Dept:

What will be the output of the following statement?


SELECT * FROM Emp NATURAL JOIN Dept WHERE dname='Physics';

DBMS Worksheet – 1 - 4 Marks Page 2


b) Write output of the queries (i) to (iv) based on the table Sportsclub

(i) SELECT DISTINCT sports FROM Sportsclub;


(ii) SELECT sports, MAX(salary) FROM Sportsclub GROUP BY sports HAVING
sports<>'SNOOKER';
(iii) SELECT pname, sports, salary FROM Sportsclub WHERE country='INDIA' ORDER
BY salary DESC;
(iv) SELECT SUM(salary) FROM Sportsclub WHERE rating='B';
4. Based on the given set of tables write answers to the following questions.

a) Write a query to display the passenger, source, model and price for all bookings whose
destination is KOL.
b) Identify the column acting as foreign key and the table name where it is present in the
given example.
5. Sumitra wants to write a program to connect to MySQL database using python and
increase the age of all the students who are studying in class 11 by 2 years.
Since she had little understanding of the coding, she left a few blank spaces in her code.
Now help her to complete the code by suggesting correct coding for statements 1, 2 and
3.
import ________________ as myc # Statement 1
con = myc.connect(host="locahost", user="root", passwd="", database="mydb")
mycursor = __________________ #Statement 2
sql = "UPDATE student SET age=age+2 WHERE class='XI'"

DBMS Worksheet – 1 - 4 Marks Page 3


mycursor.execute(sql)
sql = "SELECT * FROM student"
mycursor=con.execute(sql)
result = _____________________ #Statement 3
for row in result:
print(row)

Statement 1 : The required module to be imported


Statement 2: To initialize the cursor object.
Statement 3: Read all the data using cursor object
6.

DBMS Worksheet – 1 - 4 Marks Page 4


7. Write SQL commands for the following queries (i) to (v) based on the relationTrainer
and Course given below:

(i) Display the Trainer Name, City & Salary in descending order of their Hiredate.
(ii) To display the TNAME and CITY of Trainer who joined the Institute in the month of
December 2001.
(iii) To display TNAME, HIREDATE, CNAME, STARTDATE from tables TRAINER and
COURSE of all those courses whose FEES is less than or equal to 10000.
(iv) To display number of Trainers from each city.
OR
(iv) To display the Trainer ID and Name of the trainer who are not belongs to ‘Mumbai’
and ‘DELHI’
8. A company stores the records of motorbikes sold in January, February, March and
April months in MOTOR table as shown below:

Based on the data given above answer the following questions:


(i) Identify the most appropriate column, which can be considered as Primary key.
(ii) If 3 more columns are added and 2 rows are deleted from the table MOTOR, what will
be the new degree and cardinality?
(iii)Write the query to:

DBMS Worksheet – 1 - 4 Marks Page 5


(a) Insert the following record into the table Bcode- 207, Bname- TVS, January-
500, February- 450, March- 480, April - 350.
(b) Display the names of motor bikes which are sold more than 200 in January
month.
OR (Option for part iii only)
(iii) Write the query to:
(a) Add a new column MAY in MOTOR table with datatype as integer.
(b) Display total number of Motorbikes sold in March Month.
9. Sheela is a Python programmer. She has written a code and created a binary file
“book.dat” that has structure [BookNo, Book_Name, Author, Price]. The following user
defined function CreateFile() is created to take input data for a record and add to
book.dat and another user defined function CountRec(Author) which accepts the Author
name as parameter and count and return number of books by the given Author.
As a Python expert, help her to complete the following code based on the requirement
given above:
import ___________ #statement1
def createFile():
fobj = open("book.dat","________") #statement2
BookNo = int(input("Book number:"))
Book_Name = input("Book Name:")
Author = input("Author:")
Price = int(input("Price:"))
rec = [BookNo, Book_Name, Author, Price]
pickle.__________________ #statement3
fobj.close()

def Count_Rec(Author):
fobj = open("book.dat","rb")
num = 0
try:
while True:
rec = pickle._______________ #statement4
if Author == rec[2]:
num=num+1

DBMS Worksheet – 1 - 4 Marks Page 6


except:
fobj.close()
return num
(i) Which module should be imported in the program? (Statement 1)
(ii) Write the correct statement required to open a file named book.dat. (Statement 2)
(iii) Which statement should be filled in Statement 3 to write the data into the binary file,
book.dat and in Statement 4 to read the data from the file, book.dat?
10. Rashmi creates a table FURNITURE with a set of records to maintain the records of
furniture purchased by her. She has entered the 6 records in the table. Help her to find
the answers of following questions:-

1. Identify the Primay Key from the given table with justification of your answer.
2. If three more records are added and 2 more columns are added, find the degree
and cardinality of the table.
3. (i) Write SQL command to insert one more data/record to the table
(ii) Increase the price of furniture by 1000, where discount is given more than 10.
OR (Option for part 3 only)
3. Write the statements to:
(a) Delete the record of furniture whose price is less than 20000.
(b) Add a column WOOD varchar with 20 characters.
11. Mayank creates a table RESULT with a set of records to maintain the marks secured
by students in sub1, sub2, sub3 and their GRADE. After creation of the table, he has
entered data of 7 students in the table.
Table : RESULT

DBMS Worksheet – 1 - 4 Marks Page 7


Based on the data given above answer the following questions:
(i) Identify the most appropriate column, which can be considered as Primary key.
(ii) If two columns are added and 2 rows are deleted from the table result, what will be
the new degree and cardinality of the above table?
(iii) Write the statements to:
a. Insert the following record into the table Roll No- 108, Name- Aaditi, sub1- 470,
sub2-444, sub3-475, Grade– I.
b. Increase the sub2 marks of the students by 3% whose name begins with ‘N’.
OR (Option for part iii only)
(iii) Write the statements to:
a. Delete the record of students securing Grade-IV.
b. Add a column REMARKS in the table with datatype as varcharwith 50
characters.
12. Raghav has been assigned the task to create a database, named Projects. Healso has
to create following two tables in the database:

Based on the given scenario, answer the following questions:


(i) Which table should he create first – Projects or Employee? Justify your answer.
(ii) What will be the degree of the Cartesian product of these two tables?
(iii) Write the SQL statement to create the table Employee.
(iv) Write the SQL statement to add a column Gender of type char(1) to the table
Employee, assuming that table Employee has already been created.

DBMS Worksheet – 1 - 4 Marks Page 8


13. A departmental store MyStore is considering to maintain their inventory using SQL
to store the data. As a database Administrator, Abhay has decided that:
Name of the database – mystore
Name of the table –STORE
The attributes of STORE are as follows
ItemNo –numeric
ItemName – character of size 20
Scode – numeric
Quantity – numeric
Table : STORE

(a) Identify the attribute best suitable to be declared as primary key


(b) Write the query to add the row with following details (2010,”Notebook”,23,155)
(c) (i) Abhay wants to remove the table STORE from the database MyStore, Help Abhay in
writing the command for removing the table STORE from the database MyStore.
(ii) Now Abhay wants to display the structure of the table STORE i.e. name of the
attributes and their respective data types that he has used in the table. Write the query
to display the same.
OR
(i) Abhay wants to ADD a new column price with data type as decimal. Write the query
to add the column.
(ii) Now Abhay wants to remove a column price from the table STORE. Write the query.
14. Modern Public School is maintaining fees records of students. The database
administrator Aman decided that-
• Name of the database -School
• Name of the table – Fees
• The attributes of Fees are as follows:
Rollno - numeric Name – character of size 20

DBMS Worksheet – 1 - 4 Marks Page 9


Class - character of size 20
Fee – Numeric
Qtr – Numeric
Answer any four from the following questions:
(i) Identify the attribute best suitable to be declared as a primary key
(ii) What is the degree of the table.
(iii) Write the statements to:
a. Insert the following record into the table
Rollno-1201, Name-Akshay, Class-12th, Fee-350, Qtr-2
b. Increase the second quarter fee of class 12th students by 50
OR (Option for part iii only)
a. Delete the record of student with Rollno-1212
b. Aman wants to add a new column to the Fees table,
Which command will he use from the following:
a) CREATE b) ALTER c) SHOW d) DESCRIBE
15. Sagar a cloth merchant creates a table CLIENT with a set of records to maintain the
client’s order volume in Qtr1, Qtr2, Qtr3 and their total. After creation of the table, he
has entered data of 7 clients in the table

Based on the data given above answer the following questions:


(i) Identify the most appropriate column, which can be considered as Primary key.
(ii) What is the product of degree and cardinality of the above table ?
(iii) Write the statements to:
Update a record present in the table with data for Qtr2 – 200 , Qtr3 = 600 , total –
sum of all Qtrs where the Client_ID is C660
OR (option for part iii only )
(iii) (a) Delete all records where total is between 500 to 900
(b) Add a column RATINGS with datatype integer whose value must lie between 1 to 5

DBMS Worksheet – 1 - 4 Marks Page 10


Grade: 12 Computer Science
DBMS
Worksheet - 1
5 Marks
1. Write SQL commands for the following queries (i) to (v) based on the relation Trainer
and Course given below:

(i) Display the Trainer Name, City & Salary in descending order of their Hiredate.
(ii) To display the TNAME and CITY of Trainer who joined the Institute in the month of
December 2001.
(iii) To display TNAME, HIREDATE, CNAME, STARTDATE from tables TRAINER and
COURSE of all those courses whose FEES is less than or equal to 10000.
(iv) To display number of Trainers from each city.
(v) To display the Trainer ID and Name of the trainer who are not belongs to ‘Mumbai’
and ‘DELHI’
2. Write SQL queries for (i) to (v), which are based on the table: SCHOOL and ADMIN
TABLE: SCHOOL TABLE: ADMIN

i) To decrease period by 10% of the teachers of English subject.


ii) To display TEACHERNAME, CODE and DESIGNATION from tables SCHOOL and
ADMIN whose gender is male.
iii) To Display number of teachers in each subject.
iv) To display details of all teachers who have joined the school after 01/01/1999 in
descending order of experience.

DBMS Worksheet – 1 - 5 Marks Page 1


v) Delete all the entries of those teachers whose experience is less than 10 years in
SCHOOL table

3.
Identify the primary key in the table. Write query for the following
ii. Find average salary in the table.
iii. Display number of records for each individual designation.
iv. Display number of records along with sum of salaries for each individual designation
where number of records are more than 1.
v. What is the degree and cardinality of the relation Employee?

4. Write SQL commands for the following queries (i) to (v) on the basis of relation Mobile
Master and Mobile Stock.

DBMS Worksheet – 1 - 5 Marks Page 2


(i) Display the Mobile Company, Name and Price in descending order of their
manufacturing date.
(ii) List the details of mobile whose name starts with “S” or ends with “a”.
(iii) Display the Mobile supplier & quantity of all mobiles except “MB003”.
(iv) List showing the name of mobile company having price between 3000 & 5000.
(v) Display M_Id and sum of Moble quantity in each M_Id.
5. Write SQL commands for i) to v) based on the relations given below

i) To display details of all the items in the Store table in descending order of LastBuy.
ii) To display Itemno and item name of those items from store table whose rate is more
than 15 rupees.
iii) To display the details of those items whose supplier code is 22 or Quantity in store is
more than 110 from the table Store.
iv) To display minimum rate of items for each Supplier individually as per Scode from
the table Store.

DBMS Worksheet – 1 - 5 Marks Page 3


v) To display ItemNo, Item Name and Sname from the tables with their corresponding
matching Scode

6. Write SQL commands for the following queries (i) to (v) based on the relations
TRAINER & COURSE given below:

(i) Display all details of Trainers who are living in city CHENNAI.
(ii) Display the Trainer Name, City & Salary in descending order of their Hiredate.
(iii) Count & Display the number of Trainers in each city.
(iv) Display the Course details which have Fees more than 12000 and name ends with
‘A’. (v) Display the Trainer Name & Course Name from both tables where Course Fees is
less than 10000.

7. Write SQL commands for the queries (i) to (iii) and output for (iv) & (v) based on a
table COMPANY and CUSTOMER .

DBMS Worksheet – 1 - 5 Marks Page 4


(i) To display those company name which are having price less than 30000.
(ii) To display the name of the companies in reverse alphabetical order.
(iii) To increase the price by 1000 for those customer whose name starts with ‘S’
(iv) SELECT PRODUCTNAME,CITY, PRICE FROM COMPANY,CUSTOMER WHERE
COMPANY.CID=CUSTOMER.CID AND PRODUCTNAME=”MOBILE”;
(v) SELECT AVG(QTY) FROM CUSTOMER WHERE NAME LIKE “%r%;

8. Write SQL Commands for the following queries based on the relations PRODUCT and
CLIENT given below.

(i) To display the ClientName and City of all Mumbai- and Delhi-based clients in Client
table.
(ii) Increase the price of all the products in Product table by 10%.
(iii) To display the ProductName, Manufacturer, ExpiryDate of all the products that
expired on or before ‘2010-12-31’.

DBMS Worksheet – 1 - 5 Marks Page 5


(iv) To display C_ID, ClientName, City of all the clients (including the ones that have not
purchased a product) and their corresponding ProductName sold.
(v) To display productName, Manufacturer and ClientName of Mumbai City.

9. Consider the following tables Sender and Recipient. Write SQL commands for the
statements (a) to (c) and give the outputs for SQL queries (d) to (e).

a. To display the RecIC, Sendername, SenderAddress, RecName, RecAddress for every


Recipient
b. To display Recipient details in ascending order of RecName
c. To display number of Recipients from each city
d. To display the details of senders whose sender city is ‘mumbai’
e. To change the name of recipient whose recid is ’Ko05’ to’ S Rathore’.

DBMS Worksheet – 1 - 5 Marks Page 6


10. Write SQL commands for (i) to (v) on the basis of relations given below:
TABLE: BOOK

TABLE; ISSUED

(i) To show the books of FIRST PUBL. Publishers written by P. Purohit.


(ii) To display cost of all the books published for EPB.
(iii) Depreciate the price of all books of EPB publishers by 5%.
(iv) To display the BOOK_NAME and price of the books, more than 5 copies of which
have been issued.
(v) To show total cost of books of each type.

11. Consider the tables given below.


TABLE: STOCK

TABLE: DEALER

DBMS Worksheet – 1 - 5 Marks Page 7


(i) To display all the information about items containing the word “pen” in the field
Itname in the table STOCK.
(ii) List all the itname sold by Vikash Stationers.
(iii) List all the Itname and StkDate in ascending order of StkDate.
(iv) List all the Itname, Qty and Dname for all the items for the items quantity more than
40.
(v) List all the details of the items for which UnitPrc is more than 10 and <= 50.
12. Write SQL commands for the following queries (i) to (v) based on the relations
Teacher and Posting given below:

i. To show all information about the teacher of History department.


ii. To list the names of female teachers who are in Mathematics department.
iii. To list the names of all teachers with their date of joining in ascending order.
iv. To display teacher’s name, salary, age for male teachers only. v. To display name,
bonus for each teacher where bonus is 10% of salary.

13. Anmol maintains that database of Medicines for his pharmacy using SQL to store
the data. The structure of the table PHARMA for the purpose is as follows :
Name of the table – PHARMA
The attributes of PHARMA are as follows :
MID - numeric
DBMS Worksheet – 1 - 5 Marks Page 8
MNAME - character of size 20
PRICE - numeric
UNITS - numeric
EXPIRY - date
Table : PHARMA

(a) Write the degree and cardinality of the table PHARMA.


(b) Identify the attribute best suitable to be declared as a primary key.
(c) Anmol has received a new medicine to be added into his stock, but for which he
does not know the number of UNITS. So he decides to add the medicine without
its value for UNITS. The rest of the values are as follows :

Write the SQL command which Anmol should execute to perform the required
task.
(d) Anmol wants to change the name of the attribute UNITS to QUANTITY in the table
PHARMA. Which of the following commands will he use for the purpose ?
(i) UPDATE (ii) DROP TABLE
(iii) CREATE TABLE (iv) ALTER TABLE
(e) Now Anmol wants to increase the PRICE of all medicines by 5. Which of the
following commands will he use for the purpose ?
(i) UPDATE SET (ii) INCREASE BY
(iii) ALTER TABLE (iv) INSERT INTO

DBMS Worksheet – 1 - 5 Marks Page 9


14. Write SQL statements for the following queries (i) to (v) based on the relations
CUSTOMER and TRANSACTION given below :

(a) To display all information about the CUSTOMERs whose NAME starts with 'A'.
(b) To display the NAME and BALANCE of Female CUSTOMERs (with GENDER as 'F')
whose TRANSACTION Date (TDATE) is in the year 2019.
(c) To display the total number of CUSTOMERs for each GENDER.
(d) To display the CUSTOMER NAME and BALANCE in ascending order of GENDER.
(e) To display CUSTOMER NAME and their respective INTEREST for all CUSTOMERs
where INTEREST is calculated as 8% of BALANCE.
15. i) What do you mean by a Primary key in RDBMS ?
ii) Complete the following database connectivity program by writing the missing
statements and performing the given query
import ------------------- as mysql # statement 1
con=mysql. ---------(host=’localhost’,user=’root’,passwd=’123’ ,
database=’student’) # statement 2
cursor=con.cursor( )
cursor.execute(--------------------------------) # statement 3
data=cursor. ----------------------------------- # statement 4
for rec in data:
print(rec)

DBMS Worksheet – 1 - 5 Marks Page 10


con.close( )
a) Complete the statement 1 by writing the name of package need to be imported for
database connectivity .
b) Complete the statement 2 by writing the name of method require to create connection
between Python and mysql.
c) Complete the statement 3 by writing the query to display those students record whose
mark is between 50 and 90 from table “student”
d) Complete the statement 4 to retrieve all records from the result set.
OR
i) What is the difference between UNIQUE and PRIMARY KEY constraints ?
ii) Maya has created a table named BOOK in MYSQL database, LIBRARY
BNO(Book number )- integer
B_name(Name of the book) - string
Price (Price of one book) –integer
Note the following to establish connectivity between Python and
MySQL: Username – root, Password – writer,Host – localhost.
Maya, now wants to display the records of books whose price is more than 250. Help
Maya to write the program in Python

16. (i) What is the difference between a Candidate Key and an Alternate Key.
(ii) Virat has created a table named TRAVELS in MySQL:
Tour_ID – string
Destination – String
Geo_Cond– String
Distance – integer (In KM)
Note the following to establish connectivity between Python and MYSQL:
Username is root
Password is bharat
The table TRAVELS exists in a MYSQL database named TOUR.
The details Tour_ID, Destination, Geo_Cond and Distance are to be accepted
from the user.
Virat wants to display All Records of TRAVELS relation whose Geographical conditionis
hilly area and distance less than 1000 KM. Help Virat to write program in python.
OR

DBMS Worksheet – 1 - 5 Marks Page 11


(i) Write one point of difference between PRIMARY KEY and UNIQUE KEY in SQL.
(ii) Aarya has created a table named Emp in MySQL:
EmpNo – integer
EmpName – string
Age– integer
Salary – integer
Note the following to establish connectivity between Python and MYSQL:
Username - root
Password - tiger
Host - localhost
The Emp table exists in a MYSQL database named company.
The details of Emp table (EmpNo, EmpName, Age and Salary)
Aarya wants to display All Records of Emp relation whose age is greater than 55. Help
Aarya to write program in python.

17. (i) How many candidate key and primary key a table can have in a Database?
(ii) Manish wants to write a program in Python to create the following table
named “EMP” in MYSQL database, ORGANISATION:
Eno (Employee No )- integer , Ename (Employee Name) - string
Edept (Employee Department)-string, Sal (salary)-integer
Note the following to establish connectivity between Python and MySQL:
Username – root , Password – admin , Host - localhost
The values of fields eno, ename, edept and Sal has to be accepted from the
user. Help Manish to write the program in Python to insert record in the above
table..
OR
(i) Differentiate between degree & cardinality key in RDBMS?
(iii) Vihaan wants to write a program in Python to create the following table
named “EMP” in MYSQL database, ORGANISATION:
Eno (Employee No )- integer , Ename (Employee Name) - string
Edept (Employee Department)-string, Sal (salary)-integer
Note the following to establish connectivity between Python and MySQL:
Username – root , Password – admin , Host - localhost
Help Vihaan to write the program in Python to Alter the above table with new

DBMS Worksheet – 1 - 5 Marks Page 12


column named Bonus (int).
18. Consider the following table Cab:

(i) Which column qualifies to be the primary key?


(ii) Write a command to display the fields of the table along with their types and sizes.
(iii) Write statements to :
(a) Add a new column Driver varchar(30)
(b) Change data type of Rate column to float(6,1).
(Option for part (iii) only)
(a) To display the cab type whose rate is more than 25.
(b) To display cab id and Number of passengers for cab sedan.
19. Consider the following table

i) What would be the width of Dateofadm field?


(ii) Write commands to remove the records of “Cardiology” department.
(iii) Write statements to :
(a) Display a report showing Name, charges and discount (15%) for all patients.
(b) Display names of female patients .
OR (option for part (iii) only)
(a) Which function will find the total charges of all patients?
(b) Name the constraint that will restrict duplicate values in Name column.
20. Consider the following table ORDERS :

DBMS Worksheet – 1 - 5 Marks Page 13


(i) Write a statement to create the above table.
(ii) Write a command to change the width of Customer column to varchar(30)
(iii) Write statements to :
(a) Display the field names, their type , size and constraints .
(b) Display details of orders where orderprice is in the range 500 to 1500
OR (Option for part iii only)
(a) Write a command to increase orderprice of all orders by 15%.
(b) Name the constraint that will restrict both NULL and DUPLICATE values in the O_Id
field.
20. Consider the following table FLIGHTS :

(i) The command to create the table was written as :


Create table FLIGHTS( FL_NO integer, STARTING char(20), ENDING char(30),
NO_FLIGHT integer, NO_STOPS integer);
What is wrong with command ?
(ii) What is the cardinality of the table ?
(iii) Which functions will be used to :
(a) Display total number of flights .
(b) Display number of flights whose FL_NO starts with “IC”
(option for part (iii) only)

DBMS Worksheet – 1 - 5 Marks Page 14


Write function names to :
(a) Show the average Number of stops.
(b) Show the maximum number of stops.
21. i) Give one point of difference between an equi-join and a natural join.
ii) Write the user defined function display ( ) in python to execute the query that fetches
records of the employees coming from the city ‘Delhi’.
E_code - string
E_name - String
Sal = Integer
City - string
Note the following to establish connectivity between Python and MySQL:
❖ Username is root
❖ Password is root
❖ The table exists in a MySQL database named emp.
❖ The details (E_code, E_name, Sal, City) are the attributes of the table.
22. i) Are count (*) and count()the same functions? Why/why not?
ii) The code given below inserts the following record in the table Emp:
EmpNo – integer
EName – string
Desig – string
Salary – integer
Note the following to establish connectivity between Python and MYSQL:
Username is admin
Password is 22admin66
The table exists in a MYSQL database named company.
The details (EmpNo, EName, Desig and Salary) are to be accepted from the user. Write
the program in Python to meet the above need.
23. i. Define the term Degree with respect to RDBMS. Give one example to support your
answer
ii. Kavyawants to write a program in Python to insert the following recordin the table
named Inventory in MYSQL database,
WAREHOUSE:
Inv_No(Inventory Number )- integer
Inv_name(Name) – string

DBMS Worksheet – 1 - 5 Marks Page 15


Inv_Entry(Date )
Inv_price – Decimal
Note the following to establish connectivity between Python andMySQL:
Username - root
Password - 12345
Host - localhost
The values of fields Inv_No, Inv_name, Inv_Entryand Inv_price has to be accepted
fromthe user. Help Kavyato write the program in Python.

DBMS Worksheet – 1 - 5 Marks Page 16


Grade: 12 Computer Science
Computer Networks
Worksheet - 1
1 Marks
1. Fill in the blank:
______ is a communication methodology designed to deliver both voice and multimedia
communications over Internet protocol.
(A) SMTP (B) VoIP (C) PPP (D) HTTP
2. Which of the following is used to receive emails over Internet?
a) SMTP b) POP c) PPP d) VoIP
3. What is the size of IPv4 address? (a)32 bits (b) 64 bits (c) 64 bytes (d) 32 bytes
4. Fill in the blank:
_________ protocol provides access to command line interface on a remote computer.

(a) FTP (b) PPP (c) Telnet (d) SMTP


5. Which switching technique follows the store and forward mechanism?
(a) Circuit switching (b) message switching (c) packet switching d. None of these
6. Which protocol is used for transferring files over a TCP/IP network?
a) FTP b) SMTP c) PPP d) HTTP
7. Which switching technique follows the store and forward mechanism?
(a)Circuit switching (b) message switching
(c) packet switching (d) All of these
8. SMTP stands for___________________________
9. Which protocol is used for sending, but can also be used for receiving e-mail?
a) VoIP b) SMTP c) PPP d)HTTP
10. ____is a standard mail protocol used to receive emails from a remote server to a local
email client.
(a) SMTP (b) POP (c) HTTP (d) FTP
11. Network in which every computer is capable of playing the role of a client, or a server
or both at same time is called
a) local area network b) peer-to-peer network
c) dedicated server network d) wide area network

Computer Networks Worksheet - 1 - 1 Marks Page 1


12. ……………………is a communication methodology designed to establish a direct and
dedicated communication between an internet user and his/her ISP.
(a) VoIP (b) SMTP (c) PPP (d)HTTP
13. Identify the device on the network which is responsible for forwarding data from one
device to another
(a) NIC (b) Router (c) RJ45 (d) Repeater
14. Name the protocol that is used to transfer file from one computer to another.
15. Name the Transmission media which consists of an inner copper core and a second
conducting outer sheath.
16. What is a Firewall in Computer Network?
A. The physical boundary of Network
B. An operating System of Computer Network
C. A system designed to prevent unauthorized access
D. A web browsing Software
17. A device used to connect dissimilar networks is called ...........
a) hub b) switch c) bridge d)gateway
18. Arrange the following media in decreasing order of transmission rates.
Twisted Pair Cables, Optical Fiber, Coaxial Cables.
19. Name two web scripting languages
20. Name the transmission media suitable to establish PAN.
21. Name the transmission media best suitable for connecting to hilly areas.
22. Write the expanded form of Wi-Fi.
23. TCP/IP stands for
a) Transmission Communication Protocol / Internet Protocol
b) Transmission Control Protocol / Internet Protocol
c) Transport Control Protocol / Interwork Protocol
d) Transport Control Protocol / Internet Protocol
24. Write full form of VoIP.
25. Rearrange the following terms in increasing order of data transfer rates.
Gbps, Mbps, Tbps, Kbps, bps

Computer Networks Worksheet - 1 - 1 Marks Page 2


Grade: 12 Computer Science
Computer Networks
Worksheet - 1
2 Marks

1. Write two points of difference between Bus topology and star topology.
2. Write two points of difference between XML and HTML.
3. Write the full forms of the following:
(A) (i) HTTP (ii) FTP
(B) What is the use of TELNET?
4. Mention two differences between a Hub and a switch in networking.
5. Mention one advantage and one disadvantage of Star Topology.
6. a) Expand the following abbreviations: i) URL ii) TCP
b) What is the use of VoIP?
7. Write two points of difference between Web Page and Web site.
8. (a) Write the full forms of the following: (i) SMTP (ii) PPP
(b) What is the use of TELNET?
9. Write two advantages and two disadvantages of circuit switching
10. Differentiate between Web server and web browser. Write any two popular web
browsers.
11. (a) Write the full forms of the following: (i) FTP (ii) HTTPS
(b)Name the protocols which are used for sending and receiving emails?
12. Write two points of difference between LAN & WAN.
13. Write two points of difference between XML and HTML.
14. a. Expand the following terms: SMTP, FTP
b. What do you mean by modem?
15. Write two differences between Coaxial and Fiber transmission media.
16. Write components of data communication.
17. (a) Write the full forms of the following: (i) FTP (ii) MAC
(b) What is the use of TELNET?
18. Name two top level domain names with their area of application.
19. (a) Write the full forms of the following: (i) VoIP (ii) IMAP
(b) Name the communication medium which is used for WiFi.
20. Write two points of difference between LAN and MAN.
21. Write two points of difference between HTML and XML.
Computer Networks Worksheet – 1 - 2 Marks Page 1
22. (a) Expand the following abbreviations:
i)POP ii)HTTPS
(b) What is a URL?
23. Give difference between Video Conferencing and Chatting
24. Write two points of difference between Message Switching and Packet Switching
25. (a) Write the full forms of the following: (i)GSM (ii)XML
(b) What is the use of Modem?

Computer Networks Worksheet – 1 - 2 Marks Page 2


Grade: 12 Computer Science
Computer Networks
Worksheet –1
3/4 Marks

1. Aryan Infotech Solutions has set up its new center at Kamla Nagar for its office and
web based activities. The company compound has 4 buildings as shown in the diagram
below:

1. Suggest a cable layout of connections between the buildings.


2. Suggest the most suitable place (i.e. building) to house the server of this
organization with suitable reason
3. Suggest the placement for the following devices:
a. Internet connecting device / Modem
b. Switch
4. The organization is planning to link its sales counter situated in various parts
of same city, which types of network out of LAN, MAN or WAN will be formed?
Justify your answer.
5. What do your mean by PAN? Explain by giving an example.
2. Magnolia Infotech wants to set up their computer network in the Bangalore based
campus having four buildings. Each block has a number of computers that are required
to be connected for ease of communication, resource sharing and data security. You are
required to suggest the best answers to the questions i) to v) keeping in mind the
building layout on the campus.

Computer Networks Worksheet –1 - 3/4 Marks Page 1


i) Suggest the most appropriate block to host
the Server. Also justify your choice.
ii) Suggest the device that should should be
placed in the Server building so that they
can connect to Internet Service Provider to
avail Internet Services.
iii) Suggest the wired medium and draw the
cable block to block layout to economically
connect the various blocks.
iv) Suggest the placement of Switches and
Repeaters in the network with
justification.
v) Suggest the high-speed wired
communication medium between
Bangalore Campus and Mysore campus to
establish a data network.
3. MakeInIndia Corporation, an Uttarakhand based IT training company, is planning to
set up training centres in various cities in next 2 years. Their first campus is coming up
in Kashipur district. At Kashipur campus, they are planning to have 3 different blocks
for App development, Web designing and Movie editing. Each block has number of
computers, which are required to be connected in a network for communication, data
and resource sharing. As a network consultant of this company, you have to suggest the
best network related solutions for them for issues/problems raised in question nos. (i) to
(v), keeping in mind the distances between various block /locationand other parameter
Distance between various blocks/locations:
(i) Suggest the most appropriate
block/location to house the SERVER in
the Kashipur campus (out of the 3
blocks) to get the best and effective
connectivity. Justify your answer.

Computer Networks Worksheet –1 - 3/4 Marks Page 2


(ii) Suggest a device/software to be
installed in the Kashipur Campus to
take care of data security.
(iii) Suggest the best wired medium and
draw the cable layout (Block to Block)
to economically connect various blocks
within the Kashipur Campus.
(iv) Suggest the placement of the following
devices with appropriate reasons:
aSwitch / Hub b Repeater
(v) Suggest a protocol that shall be needed
to provide Video Conferencing solution
between Kashipur Campus and
Mussoorie Campus.
4. An International Bank has to set up its new data center in Delhi, India. It has five
blocks of buildings – A, B, C, D and E.

Distance between the blocks and number of computers in each block are as given below:

(i) Suggest the most suitable block to host the server. Justify your answer.
(ii) Draw the cable layout (Block to Block) to economically connect various blocks within
the Delhi campus of International Bank.
(iii) Suggest the placement of the following devices with justification: (a) Repeater (b)
Hub/Switch
(iv)The bank is planning to connect its head office in London. Which type of network out
of LAN, MAN, or WAN will be formed? Justify your answer.

Computer Networks Worksheet –1 - 3/4 Marks Page 3


(v) Suggest a device/software to be installed in the Delhi Campus to take care of data
security.
5. Ravya Industries has set up its new center at Kaka Nagar for its office and web based
activities. The company compound has 4 buildings as shown in the diagram below:

6. Trine Tech Corporation (TTC) is a professional consultancy company. The company is


planning to set up their new offices in India with its hub at Hyderabad. As a network
adviser, you have to understand their requirement and suggest them the best available
solutions. Their queries are mentioned as (i) to (v) below

Computer Networks Worksheet –1 - 3/4 Marks Page 4


a) Which will be the most appropriate block, where TTC should plan to install their
server? b) Draw a block to block cable layout to connect all the buildings in the most
appropriate manner for efficient communication.
c) What will be the best possible connectivity out of the following, you will suggest to
connect the new setup of offices in Bengalore with its London based office.
● Satellite Link
● Infrared
● Ethernet
d) Which of the following device will be suggested by you to connect each computer in
each of the buildings?
● Switch
● Modem
● Gateway
e) Company is planning to connect its offices in Hyderabad which is less than 1 km.
Which type of network will be formed?
7. FutureTech Corporation, a Bihar based IT training and development company, is
planning to set up training centers in various cities in the coming year. Their first center
is coming up in Surajpur district. At Surajpurcenter, they are planning to have 3
different blocks - one for Admin, one for Training and one for Development. Each block
has number of computers, which are required to be connected in a network for
communication, data and resource sharing. As a network consultant of this company,
you have to suggest the best network related solutions for them for issues/problems

Computer Networks Worksheet –1 - 3/4 Marks Page 5


raised in question nos. (i) to (v), keeping in mind the distances between various
blocks/locations and other given parameters.

(i) Suggest the most appropriate block/location to house the SERVER in the
Surajpurcenter (out of the 3 blocks) to get the best and effective connectivity. Justify
your answer. (ii) Suggest why should a firewall be installed at the SurajpurCenter?
(iii) Suggest the best wired medium and draw the cable layout (Block to Block) to most
efficiently connect various blocks within the SurajpurCenter.
(iv) Suggest the placement of the following devices with appropriate reasons:
a) Switch/Hub b) Router
(v) Suggest the best possible way to provide wireless connectivity between
SurajpurCenter and Raipur Center.
8. Perfect Edu Services Ltd. is an educational organization. It is planning to setup its
India campus at Chennai with its head office at Delhi. The Chennai campus has 4 main
buildings – ADMIN, ENGINEERING, BUSINESS and MEDIA. You as a network expert
have to suggest the best network related solutions for their problems raised in (i) to (v),
keeping in mind the distances between the buildings and other given parameters.

Computer Networks Worksheet –1 - 3/4 Marks Page 6


(i) Suggest the most appropriate location of the server inside the CHENNAI campus (out
of the 4 buildings), to get the best connectivity for maximum no. of computers. Justify
your answer.
(ii) Suggest and draw the cable layout to efficiently connect various buildings within the
CHENNAI campus for connecting the computers.
(iii) Which hardware device will you suggest to be procured by the company to be
installed to protect and control the internet uses within the campus ?
(iv) Which of the following will you suggest to establish the online face-to-face
communication between the people in the Admin Office of CHENNAI campus and DELHI
Head Office ?
(a) Cable TV (b) Email (c) Video Conferencing (d) Text Chat
(v) Name protocols used to send and receive emails between CHENNAI and DELHI office?
9. Quick Learn University is setting up its academic blocks at Prayag Nagar and
planning to set up a network. The university has 3 academic blocks and one human
resource Centre as shown in the diagram given below:

Centre-to-Centre distance between Number of computers in each of the


various blocks is as follows: buildings is as follows:

(a) Suggest a cable layout of connection between the blocks.


(b) Suggest the most suitable place to house the server of the organization with suitable
reason.
(c) Which device should be placed/installed in each of these blocks to efficiently connect
all the computers within these blocks?
(d) The university is planning to link its sales counters situated in various parts of the
CITY. Which type of network out of LAN, MAN or WAN will be formed?

Computer Networks Worksheet –1 - 3/4 Marks Page 7


(e) Which network topology may be preferred between these blocks?

10. Rehaana Medicos Center has set up its new center in Dubai. It has four buildings as
shown in the diagram given below:

Distances between various buildings are No of Computers


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 Repeater device with justification.
iv) Suggest a system (hardware/software) to prevent unauthorized access to or from the
network.
(v) Suggest the placement of the Hub/ Switch with justification.
11. “VidyaDaan” an NGO is planning to setup its new campus at Nagpur for its web-
based activities. The campus has four(04) UNITS as shown below:

Computer Networks Worksheet –1 - 3/4 Marks Page 8


i) Suggest an ideal cable layout for connecting the above UNITs.
ii) Suggest the most suitable place i.e. UNIT to install the server for the above
iii) Which network device is used to connect the computers in all UNITs?
iv) Suggest the placement of Repeater in the UNITs of above network.
v) NGO is planning to connect its Regional Office at Kota, Rajasthan. Which out of the
following wired communication, will you suggest for a very high-speed Connectivity ?
(a) Twisted Pair cable (b) Ethernet cable (c) Optical Fiber
12. India Tech Solutions (ITS) is a professional consultancy company. The company is
planning to set up their new offices in India with its hub at Hyderabad. As a network
adviser, you have to understand their requirement and suggest them the best available
solutions. Their queries are mentioned as (i) to (v) below.
Physical locations of the blocks of TTC

(i)Which will be the most appropriate block, where TTC should plan to install their
server? (ii) Draw a block to block cable layout to connect all the buildings in the most
appropriate manner for efficient communication.

Computer Networks Worksheet –1 - 3/4 Marks Page 9


(iii)What will be the best possible connectivity out of the following, you will suggest to
connect the new set up of offices in Bengalore with its London based office.
• Satellite Link • lnfrared • Ethernet
(iv)Which of the following device will be suggested by you to connect each computer in
each of the buildings? • l Switch • l Modem • l Gateway
(v) Company is planning to connect its offices in Hyderabad which is less than 1 km.
Which type of network will be formed?
13. Total-IT Corporation, a Karnataka based IT training company, is planning to set up
training centers in various cities in next 2 years. Their first campus is coming up in
Kodagu district. At Kodagu campus, they are planning to have 3 different blocks, one for
AI, IoT and DS (Data Sciences) each. Each block has number of computers, which are
required to be connected in a network for communication, data and resource sharing. As
a network consultant of this company, you have to suggest the best network related
solutions for them for issues/problems raised in question nos. (i) to (v), keeping in mind
the distances between various blocks/locations and other given parameters.

Distance between various Number of computers:


blocks/locations:

(i) Suggest the most appropriate block/location to house the SERVER in the Kodagu
campus (out of the 3 blocks) to get the best and effective connectivity. Justify your
answer. (ii) Suggest a device/software to be installed in the Kodagu Campus to take care
of data security.
(iii) Suggest the best wired medium and draw the cable layout (Block to Block) to most
efficiently connect various blocks within the Kodagu Campus.
(iv) Suggest the placement of the following devices with appropriate reasons: a)
Switch/Hub b) Router

Computer Networks Worksheet –1 - 3/4 Marks Page 10


(v) Suggest a protocol that shall be needed to provide Video Conferencing solution
between Kodagu Campus and Coimbatore Campus.
14. Intelligent Hub India is a knowledge community aimed to uplift the standard of skills
and knowledge in the society. It is planning to setup its training centres in multiple
towns and villages of India with its head offices in the nearest cities. They have created a
model of their network with a city, a town and 3 villages as given. As a network
consultant, you have to suggest the best network related solution for their
issues/problems raised in (i) to (v) keeping in mind the distance between various
locations and given parameters.

Note: * In Villages, there are community centres, in which one room has been given as
training center to this organization to install computers. * The organization has got
financial support from the government and top IT companies.
1. Suggest the most appropriate location of the SERVER in the YHUB (out of the 4
locations), to get the best and effective connectivity. Justify your answer.
2. Suggest the best wired medium and draw the cable layout (location to location) to
efficiently connect various locations within the YHUB.
3. Which hardware device will you suggest to connect all the computers within each
location of YHUB?
4. Which server/protocol will be most helpful to conduct live interaction of Experts from
Head office and people at YHUB locations?

Computer Networks Worksheet –1 - 3/4 Marks Page 11


5. Suggest a device/software and its placement that would provide data security for the
entire network of the YHUB
15. PVS Computers decided to open a new office at Ernakulum, the office consist of Five
Buildings and each contains number of computers. The details are shown below.

Computers in each building are networked but buildings are not networked so far. The
Company has now decided to connect building also.
(i) Suggest a cable layout for connecting the buildings
(ii) Do you think anywhere Repeaters required in the campus? Why
(iii) The company wants to link this office to their head office at Delhi
(a) Which type of transmission medium is appropriate for such a link?
(b) What type of network would this connection result into?
(iv) Where server is to be installed? Why?
(v) Suggest the wired Transmission Media used to connect all buildings efficiently.

Computer Networks Worksheet –1 - 3/4 Marks Page 12

You might also like