# 200 + Important CBSE Computer Science Class 12 previous year questions In this article, I am going to provide you with important CBSE computer science class 12 previous year questions. Here we go!

Topics Covered

## Type of questions for computer science class 12 previous year questions

In CBSE board exams, computer science question paper has 1 mark, 2 marks, 3, marks, 4 marks, 5 marks, 6 marks and 8 marks questions in various sections. In this article computer science class 12 previous year questions I will try to cover all of the topic-wise. Let us begin!

As per the CBSE syllabus, these are the main topics for a computer science class 12:

So let us starts with a Revision tour of class XI.

## Revision Tour computer science class 12 previous year questions

Let’s begin computer science class 12 previous year questions with 1 mark questions. This section includes objective-type questions such as MCQs, Fill in the blanks, True-False and 1-word answers. So here we go!

### Python revision tour class 12 – 1 Mark Questions

 Find the invalid identifier from the following:

a) MyName

b) True

c) 2ndName

d) My_Name

 Given the lists L=[1,3,6,82,5,7,11,92] , write the output of print(L[2:5]).

 Identify the valid arithmetic operator in Python from the following.

a) ?

b) <

c) **

d) and

 Suppose a tuple T is declared as T = (10, 12, 43, 39), which of the following is incorrect?

a) print(T)

b) T = -29

c) print(max(T))

d) print(len(T))

 Write a statement in Python to declare a dictionary whose keys are 1, 2, 3 and values are Monday, Tuesday and Wednesday respectively.

 A tuple is declared as T = (2,5,6,9,8) What will be the value of sum(T)?

 If the following code is executed, what will be the output of the following code?

``````name="ComputerSciencewithPython"
print(name[3:10])``````

 Find the invalid identifier from the following:

a. none

c. Name

d. pass

 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

 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)

 Which of the following operator cannot be used with string data type?

a. +

b. in

c. *

d. /

 Consider a tuple tup1 = (10, 15, 25, and 30). Identify the statement that will result in an error.

a. print(tup1)

b. tup1 = 20

c. print(min(tup1))

d. print(len(tup1)

 Which one of the following is the default extension of a Python file?

a. .exe

b. .p++

c. .py

d. .p

 Which of the following symbol is used in Python for single-line comment?

a. /

b. /*

c. //

d. #

 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 aren’t ordered

d) Dictionaries are mutable

 What is the output of the following code:

T=(100)

print(T*2)

a. Syntax error

b. (200,)

c. 200

d. (100,100)

 Identify the output of the following Python statements.

``````x = [[10.0, 11.0, 12.0],[13.0, 14.0, 15.0]]
y = x
print(y)
``````

a. 12.0

b. 13.0

c. 14.0

d. 15.0

 Identify the output of the following Python statements.

``````x = 2
while x < 9:
print(x, end='')
x = x + 1``````

a. 12345678

b. 123456789

c. 2345678

d. 23456789

 Identify the output of the following Python statements.

``````b = 1
for a in range(1, 10, 2):
b += a + 2
print(b)
``````

a. 31

b. 33

c. 36

d. 39

 Identify the output of the following Python statements.

``````lst1 = [10, 15, 20, 25, 30]
lst1.insert( 3, 4)
lst1.insert( 2, 3)
print (lst1[-5]) ``````

a. 2

b. 3

c. 4

d. 20

Watch this video for a clear understanding:

 Evaluate the following expression and identify the correct answer.

16 – (4 + 2) * 5 + 2**3 * 4

a. 54

b. 46

c. 18

d. 32

 State True or False “Variable declaration is implicit in Python.”

 Which of the following is an invalid datatype in Python?

(a) Set

(b) None

(c) Integer

(d) Real

 Given the following dictionaries :

``````dict_exam={"Exam":"AISSCE", "Year":2023}
dict_result={"Total":500, "Pass_Marks":165}
``````

Which statement will merge the contents of both dictionaries?

a. dict_exam.update(dict_result)

b. dict_exam + dict_result

d. dict_exam.merge(dict_result)

 Consider the given expression:

not True and False or True

Which of the following will be the correct output if the given expression is evaluated?

(a) True

(b) False

(c) NONE

(d) NULL

 Select the correct output of the code:

``````a = "Year 2022 at All the best"
a = a.split('2')
b = a + ". " + a + ". " + a
print (b) ``````

(a) Year . 0. at All the best

(b) Year 0. at All the best

(c) Year . 022. at All the best

(d) Year . 0. at all the best

 Which of the following statement(s) would give an error after executing the following code?

``````S="Welcome to class XII" # Statement 1
print(S) # Statement 2
S="Thank you" # Statement 3
S= '@' # Statement 4
S=S+"Thank you" # Statement 5 ``````

(a) Statement 3

(b) Statement 4

(c) Statement 5

(d) Statement 4 and 5

 What will the following expression be evaluated to in Python? print(15.0 / 4 + (8 + 3.0))

(a) 14.75

(b)14.0

(c) 15

(d) 15.5

 What will be the output of the following code?

``````tup1 = (1,2,[1,2],3)
tup1=3.14
print(tup1)
``````

a. (1,2,[3.14,2],3)

b. (1,2,[1,3.14],3)

c. (1,2,[1,2],3.14)

d. Error Message

 Which is the correct form of declaration of dictionary?

a. Day={1:’monday’,2:’tuesday’,3:’wednesday’}

b. Day=(1;’monday’,2;’tuesday’,3;’wednesday’)

c. Day=[1:’monday’,2:’tuesday’,3:’wednesday’]

d. Day={1’monday’,2’tuesday’,3’wednesday’]

 Kunj has declared a variable as follows:

L=[1,45,’hello’,54.6]

Identify L?

a. List

b. Tuple

c. Dictionary

d. Function

 Write the output of following:

``````x = "abcdef"
i = "a"
while i in x:
print(i, end = " ")``````

a. abcdef

b. abcde

c. bcde

d. infinite loop

 Observe the following code written by Rupal. She has used ++ in place of the exponential operator. Rewrite the correct code after removing all errors.

``````r=3.5,h=2.5
area=2*pi*r*h+2*(r++2)
print (area)``````

Which of the following operator will replace ++?

a. //

b. *

c. **

d. %

 Given is a Python string declaration:

``````myexam="@@CBSE Examination 2022@@"
Write the output of: print(myexam[::-2])``````

a. @20 otnmx SC@

b. @@CBSE Examination 2022

c. @2202 noitanimaxE ESBC

d. None of these

 Write the output of the code given below:

``````my_dict = {"name": "Aman", "age": 26}
my_dict['age'] = 27
print(my_dict.items())
``````

a. dict_items([(‘name’, ‘Aman’), (‘age’, 27), (‘address’, ‘Delhi’)])

b. dict_items([(‘name’,’Aman’),(‘age’,26)])

d. Error Message

Watch this video for more understanding:

 For the given declaration in Python as s=’WELCOME’:

Which of the following will be the correct output of print(S[1::2])?

a) WEL

b) COME

c) WLOE

d) ECM

 Which of the following is the correct output for the execution of the following Python statement?

print (5 + 3 ** 2 /2)

a) 82

b) 9.5

c) 8.0

d) 32.0

 Which of the following is not a Tuple in Python?

a) (1,2,3)

b) (“One”,”Two”, “Three”)

c) (10,)

d) (“one”)

 Which of the following is not a valid Python string operation?

a) ‘Welcome’ + ’10’

b) Welcome’ * 10

c) ‘Welcome’ * 10.0

d) “10” + ‘Welcome”

 What will be the output for the following Python statements?

``````L =[10, 20, 30, 40, 50]
L = L + 5
print (L)``````

a) [10, 20, 30, 40, 50, 5]

b) [15, 25, 35, 45,55]

c) [5,10, 20, 30, 40, 50]

d) Error

  What will be the output for the following Python statements:

``````D={ "AMIT" :90, "RESHMA" : 96,”SUKHBIR”:92, “JOHN”:95}
print(“JOHN” in D, 90 in D, sep=’#’)
``````

a) True#False

b) False#True

c) True#True

d) False#False

 Nitish has declared a tuple T in Python as follows:

T = (10, 20, 30)

Now, he wants to insert an element 40 after these three elements of T so that the tuple may contain (10,20, 30, 40).

Which of the following statements shall Nitish write to accomplish the above task?

a) T = T + 40

b) T = T+ (40)

c) T = T + (40,)

d) Nitish cannot insert 40 into the tuple since Tuples are immutable

 Identify the output of the following Python statements:

``````L = []
for i in range (4):
L.append (2*i+1)
print (L[::-1])
``````

a) [4,3,2,1]

b) [9,7,5,3]

c) [7,5,3,1]

d) [1,2,3,4]

 Identify the output of the following Python statements:

``````D={}
T= ("ZEESHAN", "NISHANT", "GURMEET"  , "LISA")
for i in range (1,5):
D[i]=T[i-1]
print (D)
``````

a) {“ZEESHAN”, “NISHANT”, “GURMEET”,”LISA”}

b) “ZEESHAN”, “NISHANT”, ” GURMEET”,”LISA”

c) [1, “ZEESHAN”], [2, “NISHANT”], [3, “GURMEET”], [4,” LISA”]

d) {1:” ZEESHAN” , 2:”NISHANT”, 3: “GURMEET” , 4: “LISA”}

 Identify the output of the following Python statements :

``````L1, L2= [10, 15, 20, 25], []
for i in range (len (L1)):
L2. insert( i,Ll.pop ())
print (LI, L2, sep="&" )
``````

a) [] & [25, 20, 15, 10]

b) [10, 15, 20, 25] & [25, 20, 15,10]

c) [10, 15, 20, 25]&[10, 15, 20, 25]

d) [25, 20, 15, 10]&[]

 Which of the following option can be the output for the following Python code?

``````Ll= [10,20,30,20,10]
L2=[]
for i in Ll:
if i not in L2:
L2.append (i)
print (Ll, L2,sep="&")
``````

a) [10,20,30,20,10]&[10,20,30, 20,10]

b) [10,20,30,20,10] [10,20,30,20,10]&

c) [10,20,30,20,10]&[30,20,10]

d) [10,20,30,20,10]&[10,20,30]

 Identify the output of the following Python code:

``````D={1:"One", 2:"Two", 3: "Three"}
L=[]
for K,V in D. items ():
if V[0l=="T":
L.append (K)
print (L)
``````

a) [1,2,3]

b) [“One”, “Two”, “Three”]

c) [2,3]

d) [“Two”, “Three”]

 What will be the output of the following Python code ?

``````L = [10, 201]
L1=[30,40]
L2=[50,60]
L.append (L1)
L.extend (L2)
print (L)``````

a) [60, 50, 40, 30, 20, 10]

b) [10, 20, 30, 40, 50, 60]

c) [10, 20, 30, 40, [50, 60]]

d) [10, 20, [30, 40], 50, 60]

 Find and write the output of the following python code :

``````for Name in ['John', 'Garima','Seema','Karan']:
print(Name)
if Name=='S':
break
else:
print ('Completed!')
print('Weldone!')``````

a) John

Completed

Garima

Completed

Seema Completed

b) John
Completed!
Garima
Completed!
Seema
Weldone!

c) John Completed!
Garima Completed!
Seema Weldone!

d) Error

 What will be the output of the following Python code?

``````S="UVW" ;L=[10,20,301]
D={}
N=len (S)
for I in range (N):
D[I] = S[I]
for K,V in D.items ():
print (K,V, sep="*" ,end="")
``````

a) U*10,V*20,W*30,

b) 10*U, 20*v, 30*W,

c) 10,20,30,u*v*w*

d) Error

Watch this video for more understanding:

### Python revision tour class 12 – 2 Marks Questions

 What do you understand by the term Iteration? Write the types of iterative statements supported by python.

 What is a dictionary? How to create a dictionary in python?

 Write type of operators from the following:

1. /=
2. ==
3. =
4. and

 Identify only arithmetic operators from the following:

//=,//,**,==,%,+

 Yashvi has given the following symbols and word to identify which types of tokens are they, help her to identify them:

1. If
2. r_no
3. True
4. in

 Rewrite the following code after removing errors:

``````30=To
for i in range(0,To)
IF i%4==0
print (i*4) -
Else
print (i+3)
``````

Ans.:

``````To=30
for i in range(0,To):
if i%4==0:
print(i*4)
else:
print(i+3) ``````

 Find the output for the following:

``````l = [6 , 3 , 8 , 10 , 4 , 6 , 7]
print( '@', l - l)
for i in range (len(l)-1,-1,-2) :
print( '@',l[i],end=''  )
``````

 Evaluate the following expressions:

a) 6 * 3 + 4**2 // 5 – 8

b) 10 > 5 and 7 > 12 or not 18 > 3

 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)
Elseif val%5==0:
print (VAL+3)
else
print(VAL+10)
``````

Ans:

``````Value=30
for VAL in range(0,Value):
if VAL%4==0:
print (VAL*4)
elif VAL%5==0:
print (VAL+3)
else:
print(VAL+10)``````

 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:
new_list.append(i)
new_tuple = tuple(new_list)
print(new_tuple)
``````

 Predict the output of the code given below:

``````s="welcome2cs"
n = len(s)
m=""
for i in range(0, n):
if (s[i] >= 'a' and s[i] <= 'm'):
m = m +s[i].upper()
elif (s[i] >= 'n' and s[i] <= 'z'):
m = m +s[i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
else:
m = m +'&'
print(m)``````

 Find and write the output of the following python code :

``````for Name in ['John', 'Garima','Seema','Karan']:
print(Name)
if Name=='S':
break
else:
print('Completed!')
print('Weldone!')
``````

 Write a program in python to display the elements of list twice, if it is a number and display the element terminated with ‘*’ if it is not a number. For example, if the content of list is as follows : MyList=[‘RAMAN’,’21’,’YOGRAJ’,’3′,’TARA’]

The output should be

RAMAN*

2121

YOGRAJ*

33

TARA*

Ans.:

``````MyList=['RAMAN','21','YOGRAJ','3','TARA']
for i in MyList:
if i.isdigit():
print(i*2)
else:
print(i+'*')

``````

 Rewrite the following code in Python after removing all syntax errors. Underline the corrections.

``````for Name in [Ramesh, Suraj, Priya]
IF Name=’S’:
print(Name)
``````

Ans.:

``````for Name in [Ramesh, Suraj, Priya]:
if Name==’S’:
print(Name)
``````

 Find the output of the following:

``````values = [10,20,30,40]
for v in values:
for i in range(1, v%9):
print(i,’*’,end=’’)
print()
``````

 Find and write the output of the following Python code :

``````Data = ["P",20,"R",10,"S",30]
Times = 0
Alpha = ""
for C in range(1,6,2):
Times = Times + C
Alpha = Alpha + Data[C-1]+"\$"
``````

 Rewrite the following code in python after removing all syntax error(s). Underline each correction done in the code.

``````25=Val
for I in the range(0,Val)
if I%2==0:
print I+1
Else:
print I–1
``````

Ans.:

``````Val=25
for I in the range(0,Val):
if I%2==0:
print(I+1)
else:
print(I–1)
``````

 Find and write the output of the following python code :

``````Text1="SSCE 2023"
Text2=" "
I=0
while I<len(Text1):
if Textl[I]>="0" and Textl[I]<="9":
Val = int(Textl[I])
Val = Val + 1
Text2=Text2 + str(Val)
elif Textl[I]>="A" and Textl[I] <="Z":
Text2=Text2 + (Text1[I+1])
else :
Text2=Text2 + "*"
I=I+1
print(Text2)``````

 Write the names of any four data types available in Python.

 Rewrite the following code in python after removing all syntax error(s). Underline each correction done in the code.

``````250 = Number
WHILE Number<=1000:
if Number=>750:
print Number
Number=Number+100
else
print Number*2
Number=Number+50``````

Ans.:

``````Number = 250
while Number<=1000:
if Number=>750:
print(Number)
Number=Number+100
else:
print(Number*2)
Number=Number+50
``````

 Find and write the output of the following python code :

``````Msg1="WeLcOME"
Msg2="GUeSTs"
Msg3=""
for I in range(0,len(Msg2)+1):
if Msg1[I]>="A" and Msg1[I]<="M":
Msg3=Msg3+Msg1[I]
elif Msg1[I]>="N" and Msg1[I]<="Z":
Msg3=Msg3+Msg2[I]
else:
Msg3=Msg3+"*"
print(Msg3)
``````

Watch this video for more understanding:

## Functions computer science class 12 previous year questions

Now in the next section of computer science class 12 previous year questions I am going to cover questions from Functions. From this topic functions 1 mark, 2 marks, 3 marks and 4 marks will be asked.

Let us begin with 1 marks questions. Here we go

### Functions Class 12 Computer Science 1 Marks Questions

 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)

 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()

 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

 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) ``````

a. 50#50

b. 50#5

c. 50#30

d. 5#50#

 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

 What is the output of the following code snippet?

``````def ChangeVal(M,N):
for i 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)
for i in L:
print(i,end="#")``````

a) 5#8#15#4#

b) 5#8#5#4#

c) 5#8#15#14#

d) 5#18#15#4#

 Find the output of the following code:

``````def convert():
Name="PythoN3.10"
R=""
for x in range(len(Name)):
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)``````

a. pYTHOn##10

b. pYTHOnN#1

c. pYTHOn#.1

d. pYTHOnN#.1

 What will be the output of the following code?

``````x = 3
def myfunc():
global x
x+=2
print(x, end=' ')
print(x, end=' ')
myfunc()
print(x, end=' ') ``````

a. 3 3 3

b. 3 4 5

c. 3 3 5

d. 3 5 5

 What will be the output of the following Python code?

``````def add (num1, num2):
sum = num1 + num2
print(sum)
``````

a. 50

b. 0

c. Null

d. None

 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 first contains default argument(s) followed by positional argument(s).

(a) Both A and R are true and R is the correct explanation for A

(b) Both A and R are true and R is not the correct explanation for A

(c) A is True but R is False

(d) A is false but R is True

 Which of the following is not correct in the context of Positional and Default parameters in Python functions?

a) Default parameters must occur to the right of Positional parameters

b) Positional parameters must occur to the right of Default parameters

c) Positional parameters must occur to the left of Default parameters

d) All parameters to the right of a Default parameter must also have default values

 For a function header as follows:

def Calc (X, Y=20)

Which of the following function calls will give an Error?

a) Calc (15,25)

b) Calc (X=15,Y=25)

c) Calc (Y=25)

d) Calc (X=25)

 Which of the following is not correct in the context of scope of variables ?

a) global keyword is used to change the value of a global variable in a local scope

b) local keyword is used to change the value of a local variable in a global scope

c) global variables can be accessed without using the global keyword in a local scope

d) local variables cannot be used outside its scope

 Which of the following is not a function/method of the random module in Python?

a) randfloat ()

b) randint ()

c) random()

d) randrange ()

 Identify the output of the following Python statements:

S =”GoOD MORNING”

print (S.capitalize (),s.title () ,end=”! “)

(a) GOOD MORNING !Good morning

(b) Good Morning!Good morning

(c) Good morning! Good Morning!

(d) God morning Good Morning!

 What will be the output of the following Python code?

``````S="WELcOME"
def Change (T) :
T="HELLO"
print (T, end='@')
Change (S)
print (S)
``````

a) WELcOME@ HELLO

b) HELLO@HELLO

c) HELLO@WELcOME

d) WELCOME@WELCOME

 Identify the correct possible output for the following Python code :

``````import random
for N in range (2,5,2):
print (random. randrange (1,N) ,end="#")
``````

a) 1#3#5#

b) 2#3#

c) 1#4#

d) 1#3#

 What are the possible outcome(s) executed from the following code? Also specify the maximum and minimum values that can be assigned to variable COUNT.

``````TEXT="CBSEONLINE"
COUNT=random.randint(0,3)
C=9
while TEXT[C]!='L':
print (TEXT[C]+TEXT[COUNT]+'*', end='')
COUNT=COUNT+1
C=C-1
``````

a) EC*NB*IS*

b) NS*IE*LO*

c) ES*NE*IO*

d) LE*NO*ON*

 What will be the output of the following Python code ?

``````def FunStr (S):
T=''
for i in S:
if i.isdigit ():
T = T +i
return T
X= "PYTHON 3.9"
Y = FunStr (X)
print (X, Y, sep="*")``````

a) PYTHON 3.9

b) PYTHON 3.9*3.9

c) PYTHON 3.9*39

d) Error

 What will be the output of the following Python code?

``````V=50
def Change (N):
global V
V, N = N, V
print (V, N, sep="#",end="@")
Change (20)
print (V)``````

a) 20#50@20

b) 50@20#50

c) 50#50#50

d) 20@50#20

 What is the output of the following Python code ?ff

``````def ListChange () :
for i in range (len (L)):
if L[i]%2 == 0:
L[i]=L[i]*2
if L[i]%3==0:
L[i]=L[i]*3
else:
L[i]=L[ij*5
L = [2,6,9,10]
ListChange ()
for i in L:
print (i,end="#")``````

a) 4#12#27#20#

b) 20#36#27#100#

c) 6#18#27#50#

d) Error

 What will be the output of the following Python code?

``````V = 25
def Fun (Ch):
V=50
print (V, end=Ch)
V *= 2
print (V, end=Ch)
print (V, end="*")
Fun ("!")
print (V)``````

a) 25*50! 100 !25

b) 50*100 !100!100

c) 25*50! 100!100

d) Error

 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=' ')
``````

a) 22 # 40 # 9 # 13 #

b) 9 # 22 # 13 # 53 #

c) 9 # -30 # 22 # 22

d) Error

Watch this video for more understnading:

In the next section of computer science class 12 previous year questions I am going to cover 2 marks questions from functions class 12 computer science. This section includes questions such as definitions, differetiates, output and error based questions. Here we go!

### Functions Class 12 Computer Science 2 Marks Questions

 Rewrite the following code in python after removing all syntax error(s). Underline each correction done in the code.

``````def Sum(Count) #Method to find sum
S=0
for I in Range(1,Count+1):
S+=I
RETURN S
print (Sum) #Function Call
print (Sum)
``````

Ans.:

``````def Sum(Count): #Method to find sum
S=0
for I in range(1,Count+1):
S+=I
return S
print (Sum(2)) #Function Call
print (Sum(5))  ``````

 Find the output for the following:

``````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+'#'
print(m)
fun('BoardExam@2K23')``````

 Find and write the output of the following python code :

``````def Changer(P,Q=10):
P=P/Q
Q=P%Q
print(P,"#",Q)
return P
A=200
B=20
A=Changer(A,B)
print( A,"\$",B)
B=Changer(B)
print( A,"\$",B)
A=Changer(A)
print (A,"\$",B)
``````

 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#

 Differentiate between actual parameter(s) and formal parameter(s) with a suitable example for each.

Ans.:

 Explain the use of a global keyword used in a function with the help of a suitable example.

 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()
elif str[i].islower():
m=m+str[i].upper()
else:
if i%2==0:
m=m+str[i-1]
else:
m=m+"#"
print(m)
Display('Fun@Python3.0')``````

 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):
if n%i=0:
print("Number is not prime \n")
break
else:
print("Number is prime \n’)
``````

Ans.:

``````def prime():
n=int(input("Enter number to check :: "))
for i in range (2, n//2):
if n%i==0:
print("Number is not prime \n")
break
else:
print("Number is prime \n")
break``````

 Write the output of the code given below:

``````p=5
def sum(q,r=2):
global p
p=r+q**2
print(p, end= '#')
a=10
b=5
sum(a,b)
sum(r=5,q=1)``````

 Write a Python method/function SwapParts(Word) to swap the first part and the second part of the string Word. Assuming there are an even number of letters in the string Word. The function should finally display the changed Word.

For example :

If Word = ‘Elephant’ then the function should convert Word to ‘hantElep’ and display the output as:

Changed Word is hantElep

Ans.:

``````def SwapParts(word):
l=len(word)
hf=l//2
nw=''
if l%2==0:
nw=word[hf:]+word[:hf]
return nw

w=input("Enter the word:")
print(SwapParts(w))
``````

 Write a Python method/function Noun2Adj(Word) which checks if the string Word ends with the letter ‘y’. If so, it replaces the last letter ‘y’ with the string ‘iful’ and then displays the changed Word. For example if the Word is “Beauty”, then the Word should be changed to “Beautiful”.  Otherwise it should display Not ending with “y”.

Ans.:

``````def Nount2Adj(word):
nw=''
rw='iful'
if word.endswith('y'):
word=word[:-1]+rw
else:
print("Word not ending with y.")
return word
w=input("Enter word endwith y")
``````

 Write the output for the following:

``````a=10
def call():
global a
a=15
b=20
print(a)
call()``````

 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.

 Write the definition of a method/function AddOddEven(VALUES) to display sum of odd and even values separately from the list of VALUES.

For example :

If the VALUES contain [15, 26, 37, 10, 22, 13]

The function should display

Even Sum: 58

Odd Sum: 65

Ans.:

``````def AddOddEven(VALUES):
esum=0
osum=0
for i in VALUES:
if i%2==0:
esum+=i
else:
osum+=i
print("Even Sum:",esum)
print("Odd Sum:",osum)
n=int(input("Enter no. of elements:"))
l=[]
for i in range(n):
l.append(v)
``````

### Functions Class 12 Computer Science 3 Marks Questions

Now its turns to 3 marks questions from the topic function computer science class 12. Mostly in 3 marks questions, output and error-based questions as well as write-a-function type questions will come. So here we go!

 Write a method in python to find and display the composite numbers between 2 to N. Pass N as an argument to the method.

Ans.:

``````def dis_CompoSite(N):
print("Composite Numbers between 2 to N:",end='')
for i in range(2,N+1):
count=0
for j in range(2,i//2+1):
if i%j==0:
count+=1
if count>=1:
print(i,end=',')
n=int(input("Enter the value:"))
dis_CompoSite(n)``````

 Write the definition of a method/function TenTimesEven(VALUES) to add and display the sum of ten times the even values present in the list of VALUES.

For example, If the Nums contain [5,2,3,6,3,4]

The method/function should display Sum: 120

Ans.:

``````def TenTimesEven(VALUES):
s=0
for i in VALUES:
if i%2==0:
s=s+(i*10)
print("Sum:",s)
n=int(input("Enter the value:"))
l=[]
for i in range(n):
v=int(input("Enter value:"))
l.append(v)
TenTimesEven(l)
``````

 Write the definition of a method/function EndingA(Names) to search and display those strings from the list of Names, which are ending with ‘A’.

For example, If the Names contain [“JAYA”,”KAREEM”,”TARUNA”,”LOVISH”]

The method/function should display JAYA TARUNA

Ans.:

``````def EndingA(names):
for i in names:
if i.endswith('a'):
print(i,end=' ')

n=int(input("Enter the value:"))
l=[]
for i in range(n):
l.append(v)
EndingA(l)
``````

 Write a python method/function Scroller(Lineup) to scroll all the elements of a list Lineup by one element ahead and move the last element to the first. Also, display the changed content of the list. For Example: If the list has the following values in it [25,30,90,110,16]

After changing the list content should be displayed as [16,25,30,90,110]

Ans.:

``````def Scroller(Lineup):
Lineup=Lineup[-1:]+Lineup[:-1]
print(str(Lineup))
n=int(input("Enter the value:"))
l=[]
for i in range(n):
l.append(v)
Scroller(l)``````

 Write a python method/function REVERSAR(Number) to find a new number Reverse from Number with each of the digits of Number in reversed order and display the content of Reverse on screen.

For Example:

If the value of Number is 3451

The method/function should be displayed as 1543

Ans.:

``````def REVERSAR(number):
r=0
while number!=0:
r=(number%10)+(r*10)
number//=10
print("Reverse:",r)
n=int(input("Enter the value:"))
REVERSAR(n)``````

 Write the definition of a method/function HowMany(ID,Val) to count and display number of times the value of Val is present in the list ID.

For example : If the ID contains [115,122,137,110,122,113] and Val contains 122

The function should display 122 found 2 Times

Ans.:

``````def HowMany(ID,val):
c=0
for i in ID:
if i==val:
c+=1
print(val, "found ",c," time")
n=int(input("Enter total no. of values:"))
s=int(input("Enter number to search:"))
l=[]
for i in range(n):
l.append(v)
HowMany(l,s)
``````

 Write a python method/function Swapper(Numbers) to swap the first half of the content of a list of Numbers with the second half of the content of the list of Numbers and display the swapped values

Note : Assuming that the list has even number of values in it.

For example :

If the list Numbers contains  [35,67,89,23,12,45]

After swapping the list content should be displayed as [23,12,45,35,67,89]

Ans.:

``````def swapper(Numbers):
if len(Numbers)%2 == 0:
start = 0
else:
start = 1
hf = len(Numbers)//2
for i in range(hf):
temp = Numbers[i]
Numbers[i] = Numbers[i+hf+start]
Numbers[i+hf+start] = temp
n=int(input("Enter no. of elements:"))
l=[]
for i in range(n):
v=int(input("Enter value to append:"))
l.append(v)
swapper(l)
print(l)``````

 Write a python method/function Count3and7(N) to find and display the count of all those numbers which are between 1 and N, which are either divisible by 3 or by 7.

For example :

If the value of N is 15

The sum should be displayed as 7 (as 3,6,7,9,12,14,15 in between 1 to 15 are either divisible by 3 or 7)

Ans.:

``````def Count3and7(N):
c=0
for i in range(1,N+1):
if i%3==0 or i%7==0:
c+=1
print("Numbers divisible by 3 and 7 are:",c)
n=int(input("Enter a number:"))
Count3and7(n)``````

 Find the output for the following:

``````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)
``````

Ans.;

250 # 150
250 # 100
130 # 100

 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]

Ans.:

``````def Lshift(Arr,n):
print(Arr[n:]+Arr[:n])

l=[]
m=int(input("Enter no. of elements"))
n=int(input("Enter no. shift elements:"))

for i in range(m):
v=int(input("Enter value to add into the list:"))
l.append(v)
Lshift(l,n)
``````

 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,6]

The indexList will have – [0,1,3,5]

Ans.:

``````def index_list(L):
il=[]
for i in range(len(L)):
if L[i]!=0:
il.append(i)
return il

l=[]
n=int(input("Enter no. of elements"))

for i in range(n):
v=int(input("Enter value to add into the list:"))
l.append(v)
print(index_list(l))
``````

 Write the output of the following:

``````def Convert(X=45,Y=30) :
X=X+Y Y=X–Y
print(X,"&",Y)
return X
A=250
B=150
A=Convert(A,B)
print (A,"&",B)
B=Convert(B)
print(A,"&",B)
A=Convert(A)
print(A,"&",B)
``````

Ans.:

400 & 250
400 & 150
180 & 150
400 & 180
430 & 400
430 & 180

That’s all from topic function computer science class 12 questions asked in the previous year’s board exams. Now let us move ahead with the next topic data file handling. Here we go!

## Data file handling computer science class 12 previous year questions

Data file handling computer science class 12 is another important topic in the curriculum of computer science. From this chapter 1 mark, 2 marks, 3 marks, 4 marks and 5 marks questions were asked in board exams. So let us see the questions asked in the previous year’s board exam. Let’s begin!

### Data file handling 1 mark questions computer science class 12

 Consider the following directory structure.

Suppose the present working directory is MyCompany. What will be the relative path of the file Transactions.Dat?

a) MyCompany/Transactions.Dat

b) MyCompany/Accounts/Transactions.Dat

c) Accounts/Transactions.Dat

d) ../Transactions.Dat

 Suppose the content of “Rhymes.txt” is:

Hickory Dickory Dock

The mouse went up the clock

``````F = open ("Rhymes. txt")
X = ["the", "ock"]
for i in L:
for W in i.split () :
if W in X:
print (W, end = "*")
``````

a) the*

b) Dock*The*the*clock*

c) Dock*the*clock*

d) Error

 Suppose the content of “Rhymes.txt” is:

What will be the output of the following Python code?

``````F = open ("Rhymes.txt")
for W in L:
if W.lower () == W[::-1].lower ():
print (W)
``````

a) Good

b) Morning

d) Error

 Suppose the content of “Rhymes.txt” is:

One, two, three, four, five

Once. I caught a fish alive.

What will be the output of the following Python code?

``````F = open ("Rhymes.txt")
print (S.count('e',20))
``````

a) 20

b) 1

c) 3

d) 6

 Suppose the content of “Rhymes.txt” is:

Baa baa black sheep

have you any wool?

What will be the output of the following Python code?

``````F = open ("Rhymes.txt")
L = S.split ()
for i in L:
if len (i)%3!=0:
print (i, end= " ")
``````

a) Baa baa you any

b) black have wool?

c) black sheep, have wool?

d) Error

 Suppose the content of a text file “Rhymes.txt” is as follows:

Jack & Jill

went up the hill

What will be the output of the following Python code ?

``````F = open ("Rhymes.txt")
for i in L:
S=i.split()
print (len (S) ,end="#")
``````

a) 2#4#

b) 3#4#

c) 2#

d) 7#

 Which of the following function is used with the csv module in Python to read of the contents a csv file into an object?

 Which of the following Python modules is imported to store and retrieve objects using the process of serialization and deserialization?

a) csv

b) binary

c) math

d) pickle

 Suppose the content of a text file Notes.txt is:

The way to get started is to quit talking and begin doing

What will be the output of the following Python code?

``````F = open ("Rhymes.txt")
F.seek (29)
print (S)
``````

a) The way to get started is to

b) quit talking and begin doing

c) The way to get started is to quit talking and begin doing

d) gniod nigeb dna gniklat tiuq ot si detrats teg ot yaw ehT

 Which of the following is the default character for the newline parameter for a csv file object opened in write mode in Python IDLE ?

a) \n

b) \t

c) ,

d) ;

 If the following statement is used to read the contents of a textfile object F: X-F.readlines( )

Which of the following is the correct data type of x?

a) list

b) dictionary

c) string

d) tuple

 Which of the following is the correct expansion of CSV ?

a) Comma Separated Values

b) Centrally Secured Values

c) Computerised Secured Values

d) Comma Secured Values

 What is the significance of the seek() method?

a) It seeks the absolute path of the file

b) It tells the current byte position of the file pointer within the file

c) It places the file pointer at the desired offset within the file

d) It seeks the entire content of the file

 Which of the following statement is incorrect in the context of pickled binary files?

a) csv module is used for reading and writing objects in binary files

b) pickle module is used for reading and writing objects in binary files

c) load () of the pickle module is used to read objects

d) dump () of the pickle module is used to write objects

 Which of the following option is the correct usage for the tell() of a file object?

a) It places the file pointer at the desired offset in a file

b) It returns the entire content of a file

c)It returns the byte position of the file pointer as an integer

d) It tells the details about the file

 A text file opened using following statement:

MyFile =open(‘Notes.txt’)

Which of the following is the correct statement to close it?

a) MyFile=close(‘Notes.txt’)

b) MyEile.close ( ‘Notes.txt’)

c) close.MyFile ()

d) MyFile.close ()

 Which of the following is not a correct python statement to open a text file “Notes.txt” to write content into it?

a) F = open(“Notes.txt”,”w”)

b) F = open(“Notes.txt”,”a”)

c) F = open(“Notes.txt”,”A”)

d) F = open(“Notes.txt”,”w+”)

 Which of the following is the correct python statement to read and display the first 10 characters from a text file Notes.txt?

b) F = open(“notes.txt”);print(F.dump(10))

d) F = open(“notes.txt”);print(F.write(10))

 Which of the following statement is not correct?

a) We can write content into text file opened using ‘w’ mode

b) We can write content into text file opened using ‘w+’ mode

c) We can write content into text file opened using ‘r’ mode

d) We can write content into text file opened using ‘r+’ mode

 Which of the following is a function/method of the pickle module?

c) writer()

Watch this video for more understanding:

 Suppose content of ‘Myfile.txt’ is :

Ek Bharat Shreshtha Bharat

What will be the output of the following code?

``````myfile = open("Myfile.txt")
vlist = list("aeiouAEIOU")
vc=0
for y in x:
if(y in vlist):
vc+=1
print(vc)
myfile.close() ``````

a. 6

b. 7

c. 8

d. 9

 Which of the following statement is incorrect in the context of binary files?

a. Information is stored in the same format in which the information is held in memory.

b. No character translation takes place

c. Every line ends with a new line character

d. pickle module is used for reading and writing

 Which of the following statement is not true?

a. pickling creates an object from a sequence of bytes

b. pickling is used for object serialization

c. pickling is used for object deserialization

d. pickling is used to manage all types of files in Python

 Syntax of seek function in Python is myfile.seek(offset, reference_point) where myfile is the file object. What is the default value of reference_point?

a. 0

b. 1

c. 2

d. 3

 Which of the following character acts as default delimiter in a csv file?

a. (colon) :

b. (hyphen) –

c. (comma) ,

d. (vertical line) |

 Syntax for opening Student.csv file in write mode is myfile = open(“Student.csv”,”w”,newline=”). What is the importance of newline=”?

a. A newline gets added to the file

b. Empty string gets appended to the first line

c. Empty string gets appended to all lines

d. EOL translation is suppressed

 What is the correct expansion of CSV files?

a. Comma Separable Values

b. Comma Separated Values

c. Comma Split Values

d. Comma Separation Values

 Which of the following is not a function / method of csv module in Python?

c. writer()

d. writerow()

 Which of the following statement opens a binary file record.bin in write mode and writes data from a list lst1 = [1,2,3,4] on the binary file?

a. with open(‘record.bin’,’wb’) as myfile: pickle.dump(lst1,myfile)

b. with open(‘record.bin’,’wb’) as myfile: pickle.dump(myfile,lst1)

c. with open(‘record.bin’,’wb+’) as myfile: pickle.dump(myfile,lst1)

d. with open(‘record.bin’,’ab’) as myfile: pickle.dump(myfile,lst1)

 Suppose the content of ‘Myfile.txt’ is:

“Twinkle twinkle little star

How I wonder what you are

Up above the world so high

Like a diamond in the sky “

What will be the output of the following code?

``````myfile = open("Myfile.txt")

print(len(data))

myfile.close()``````

a. 3

b. 4

c. 5

d. 6

 Raghav is trying to write a tuple tup1 = (1,2,3,4,5) on a binary file test.bin. Consider the following code written by him.

``````import pickle
tup1 = (1,2,3,4,5)
myfile = open("test.bin",'wb')
pickle._______ #Statement 1
myfile.close()
``````

Identify the missing code in Statement 1.

a. dump(myfile,tup1)

b. dump(tup1, myfile)

c. write(tup1,myfile)

 A binary file employee.dat has the following data :

``````def display(eno):
f=open("employee.dat","rb")
totSum=0
try:
while True:
if R==eno:
__________ #Line1
totSum=totSum+R
except:
f.close()
print(totSum)
``````

When the above-mentioned function, display (103) is executed, the output displayed is 190000.

Write an appropriate jump statement from the following to obtain the above output.

a. jump

b. break

c. continue

d. return

 A text file student.txt is stored in the storage device. Identify the correct option out of the following options to open the file in reading mode.

i. myfile = open(‘student.txt’,’rb’)

ii. myfile = open(‘student.txt’,’w’)

iii. myfile = open(‘student.txt’,’r’)

iv. myfile = open(‘student.txt’)

a. only i

b. both i and iv

c. both iii and iv

d. both i and ii

 Suppose content of ‘Myfile.txt’ is

Humpty Dumpty sat on a wall

Humpty Dumpty had a great fall

All the king’s horses and all the king’s men

Couldn’t put Humpty together again

What will be the output of the following code?

``````myfile = open("Myfile.txt")
print(len(record))
myfile.close()
``````

a. 24

b. 25

c. 26

d. 27

 Suppose content of ‘Myfile.txt’ is

Honesty is the best policy.

What will be the output of the following code?

``````myfile = open("Myfile.txt")
print(len(x))
myfile.close()
``````

a. 5

b. 25

c. 26

d. 27

 Suppose the content of ‘Myfile.txt’ is :

Culture is the widening of the mind and of the spirit.

What will be the output of the following code?

``````myfile = open("Myfile.txt")
y = x.count('the')
print(y)
myfile.close()
``````

a. 2

b. 3

c. 4

d. 5

 Suppose the content of ‘Myfile.txt’ is :

Twinkle twinkle little star

How I wonder what you are

Up above the world so high

Like a diamond in the sky

Twinkle twinkle little star

What will be the output of the following code?

``````myfile = open("MyFile.txt")
line_count = 0
for line in data:
if line == 'T':
line_count += 1
print(line_count)
myfile.close() ``````

a. 2

b. 3

c. 4

d. 5

 Which of the following mode in the file opening statement results or generates an error if the file does not exist?

(a) a+

(b) r+

(c) w+

(d) None of the above

 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)

 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.

(a) Both A and R are true and R is the correct explanation for A

(b) Both A and R are true and R is not the correct explanation for A (c) A is True but R is False

(d) A is false but R is True

 Consider the following directory structure:

Suppose root directory (School) and present working directory are the same. What will be the absolute path of the file Syllabus.jpg?

a. School/syllabus.jpg

d. School/Examination/syllabus.jpg

 Assume the content of the text file, ‘student.txt’ is:

Arjun Kumar

Ismail Khan

Joseph B

Hanika Kiran

What will be the data type of data_rec?

``````myfile = open("Myfile.txt")
myfile.close()
``````

a. string

b. list

c. tuple

d. dictionary

 Which of the following option is not correct?

a. if we try to read a text file that does not exist, an error occurs.

b. if we try to read a text file that does not exist, the file gets created.

c. if we try to write on a text file that does not exist, no error occurs.

d. if we try to write on a text file that does not exist, the file gets Created.

 Which of the following options can be used to read the first line of a text file Myfile.txt?

 Assume that the position of the file pointer is at the beginning of 3rd line in a text file. Which of the following option can be used to read all the remaining lines?

Watch this video for more understanding:

### 2 Marks Questions File Handling Class 12 Computer Science

In this section of computer science class 12 previous year questions I am going to discuss 2 marks questions file handling class 12 computer science. Here we go!

Steps are given just for explanation not required in the answer.

 Write a statement in Python to open a text file MARKER.TXT so that existing content can be read from it.

Ans.:

Steps:

1. Create a file object/handle f to open the file “marker.txt” in read mode using the open() function.
2. Create an object data and store the data using the read() function.
3. Print the data stored in the data object using the print() function.
4. Close the file using the close() function.

Code:

``````f=open("MARKER.txt")
print(data)
f.close()``````

 Write a statement in Python to open a text file DATA.TXT so that new content can be written in it.

Ans.:

Steps:

1. Create a file object/handle f to open the file “data.txt” in w (write) mode using the open() function.
2. Use write () function to add new content to the file.
3. Close the file using the close() function.
``Code:``
``````f=open("DATA.TXT","w")
f.write("Data file is ready to get data.")
f.close()``````

 Write a method/function ABLINES( ) in python to read contents from a text file LINES.TXT, to display those lines, which is starting with either the alphabet ‘A’ or alphabet ‘B’.

For example:

If the content of the file is :

A BOY IS PLAYING OUTSIDE

THE PLAYGROUND IS BIG

BANYAN TREE IS IN THE GROUND

The method/function should display:

A BOY IS PLAYING OUTSIDE

BANYAN TREE IS IN THE GROUND

Ans.:

Steps:

Method 1 Using starts with method

1. Create a function using def as given in the question.
2. Create a file object myfile and open the file “lines.txt” in read (r) mode.
3. Declare an object d and store the contents of files in the list using readlines() function.
4. Traverse the list using for loop.
5. Now use the if condition to check the lines having the first letter is either ‘A’ or ‘B’ using startswith() function.
6. Print the lines.
7. Close the file.
``````def ABLINES():
myfile = open("lines.txt",'r')
for i in d:
if i.startswith('A') or i.startswith('B'):
print(i,end='')
myfile.close() ``````

Method 2 Using index 0

Steps:

1. Create a function ABLINES() starting with def keyword.
2. Create an object myfile to open “MyFile.txt” in read (r) mode.
3. Create an object d to store the lines of the text file using readlines() function.
4. Traverse the list using for loop.
5. Use if condition to print the lines starts with ‘A’ or ‘B’ using the initial index 0.
6. Print the lines.
7. Close the file.
``````def ABLINES():
myfile = open("MyFile.txt",'r')
for i in d:
if i=='A' or i=='B':
print(i,end='')
myfile.close()
``````

 Write a method/function SHORTWORDS( ) in python to read lines from a text file WORDBANK.TXT, and display those words, which are lesser than 5 characters.

For example :

If the content of the file is :

HAPPY JOY WELCOME KITE

LOVELY POSITIVE FUN

The method /function should display :

JOY

KITE

FUN

Ans.:

Steps:

1. Create a function SHORTWODS() starting with the def keyword.
2. Create a file object wb and open the file “wordbank.txt” in read (r) mode.
3. Now declare object d to store the contents of the file using read() function.
4. Declare a variable w to store the data received from the file into a d object to split in words using split() function.
5. Traverse the words list object w using for loop.
6. Use if condition to print the words having less than 5 characters using relation operator < and len() function.
7. Close the file.
``````def SHORTWORDS():
wb = open("wordbank.txt",'r')
w=d.split()
for i in w:
if len(i)<5:
print(i)
wb.close()
SHORTWORDS()``````

 Differentiate between the following :

1.  f = open(‘diary.txt’, ‘a’)
2.  f = open(‘diary.txt’, ‘w’)

Ans.:

 Write a method in python to read the Write function definition for TOWER( ) in python to read the content of a text file WRITEUP.TXT, count the presence of word TOWER and display the number of occurrences of this word.

Note : – The word TOWER should be an independent word – Ignore type cases (i.e. lower/upper case)

Example :

If the content of the file WRITEUP.TXT is as follwos :

Tower of hanoi is an interesting problem. Mobile phone tower is away from here. Views from EIFFEL TOWER are amazing.

The function TOWER( ) should display : 3

Ans.:

``````def TOWER():
wp = open("WriteUP.txt",'r')
w=d.split()
c=0
for i in w:
if 'tower' in i.lower():
c+=1
print("Tower word occurs:",c, " times in the file.")
wp.close()

``````

 Write a function in python to count the number of lines in a text file ‘STORY.TXT’ which is starting with an alphabet ‘A’ .

Ans.:

``````def begins_A():
f = open("Story.txt",'r')
c=0
for i in d:
if i=='A':
c+=1
print("The file story.txt contains", c," lines starting with A.")
f.close()``````

 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.

Ans.:

``````def DISPLAYWORDS():
f = open("STORY.txt",'r')
w=d.split()
for i in w:
if len(i)<4:
print(i,end=' ')
f.close()``````

 Write a method in python to read the content from a text file story.txt line by line and display the same on screen.

Ans.:

``````def read_lines():
f = open("story.txt",'r')
for i in d:
print(i,end='')
f.close()``````

 Write a method in Python to read lines from a text file INDIA.TXT, to find and display the occurrence of the word ‘‘India’’.

For example :

If the content of the file is

‘‘India is the fastest growing economy. India is looking for more investments around the globe. The whole world is looking at India as a great market. Most of the Indians can foresee the heights that India is capable of reaching.

The output should be 4.

Ans.:

``````def india_freq():
myfile = open("india.txt",'r')
w=d.split()
c=0
for i in w:
if i.lower()=='india':
c+=1
print("India found",c, " times.")
myfile.close()``````

 Write a statement in Python to open a text file WRITEUP.TXT so that new content can be written in it.

 Write a statement in Python to open a text file README.TXT so that existing content can be read from it.

 Write a method/function ISTOUPCOUNT() in python to read contents from a text file WRITER.TXT, to count and display the occurrence of the word ‘‘IS’’ or ‘‘TO’’ or ‘‘UP’’.

For example :

If the content of the file is –

IT IS UP TO US TO TAKE CARE OF OUR SURROUNDING. IT IS NOT POSSIBLE ONLY FOR THE GOVERNMENT TO TAKE RESPONSIBILITY

The method/function should display

Count of IS TO and UP is 6

Ans.:

``````def istoupcount():
myfile = open("writer.txt",'r')
w=d.split()
c=0
for i in w:
if i.lower()=='is' or i.lower()=='up' or i.lower()=='to':
c+=1
print("Count of is, up and to is:",c)
myfile.close()
``````

 Write a method/function AEDISP() in python to read lines from a text file WRITER.TXT, and display those lines, which are starting either with A or starting with E.

For example :

If the content of the file is

A CLEAN ENVIRONMENT IS NECESSARY FOR OUR GOOD HEALTH. WE SHOULD TAKE CARE OF OUR ENVIRONMENT. EDUCATIONAL INSTITUTIONS SHOULD TAKE THE LEAD.

The method should display

A CLEAN ENVIRONMENT IS NECESSARY FOR OUR GOOD HEALTH.

EDUCATIONAL INSTITUTIONS SHOULD TAKE THE LEAD.

Ans.:

``````def AEDISP():
myfile = open("writer.txt",'r')
for i in d:
if i=='A' or i=='E':
print(i,end='')
myfile.close()
``````

 A text file named SOLUTION.TXT contains some English sentences. Another text file named TEST.TXT needs to be created such that it replaces every occurrence of 3 consecutive letters ‘h’, ‘i’ and ‘s’ (irrespective of their cases) from each word of the file SOLUTION.TXT, with 3 underscores (‘___’).

For example :

If the file SOLUTION.TXT contains the following content :

“This is his history book.”

Then TEST.TXT should contain the following : “T ___ is ___ ___tory book.”

Write the definition for function CreateTest()in Python that would perform the above task of creating TEST.TXT from the already existing file SOLUTION.TXT.

Ans.:

``````def Create_Test():
myfile = open("solution.txt",'r')
t=d.replace('his','___')
myfile = open("Test.txt",'w')
myfile.write(t)
myfile.close()
myfile = open("Test.txt",'r')
``````

 A text file named AGENCIES.TXT contains some text. Write the definition for a function Showsites() in Python which displays all such words of the file which have more than 9 characters and start with “www.”.

For example :

If the file AGENCIES.TXT contains :

“Name: TechnoCraft, Website: www.technocraft.com, Name: DataTech, Website: www.datatech.com”

Then the function Showsites() should display the output as : www.technocraft.com

www.datatech.com

Ans.:

``````def ShowSites():
f=open("Agencies.txt")
words=data.split()
for i in words:
if len(i)>9 and i.startswith('www'):
print(i)``````

### Computer Science Class 12 Data file handling 3 marks questions

 Write a function in Python that counts the number of “Me” or “My” words present in a text file “STORY.TXT”.

If the “STORY.TXT” contents are as follows:

My first book was Me and My Family. It gave me chance to be Known to the world.

The output of the function should be:

Count of Me/My in file: 4

``````def CountMyorMy():
f=open("story.txt")
words=data.split()
c=0
for i in words:
if 'Me' in i or 'My' in i:
c+=1
print("Count of Me/My in file:",c)
``````

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

Example:

If the file content is as follows:

Updated information As simplified by official websites.

The AMCount() function should display the output as:

A or a:4

M or m :2

Ans.:

``````def AMCount():
f=open("story.txt")
ca=cm=0
for i in data:
if 'a' in i.lower():
ca+=1
if 'm' in i.lower():
cm+=1
print("A or a:",ca)
print("M or m:",cm)``````

 Write a method COUNTLINES() in Python to read lines from text file ‘TESTFILE.TXT’ and display the lines which are not starting with any vowel.

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.

The COUNTLINES() function should display the output as:

The number of lines not starting with any vowel – 1

Ans.:

``````def COUNTLINES():
f = open("testfile.txt",'r')
c=0
for i in d:
if i not in 'AEIOUaeiou':
c+=1
print("The number of lines not starting with any vowel - ",c)
f.close()

``````

 Write a function ETCount() in Python, which should read each character of a text file “TESTFILE.TXT” and then count and display the count of occurrence of alphabets E and T individually (including small cases e and t too).

Example:

If the file content is as follows:

Today is a pleasant day. It might rain today. It is mentioned on weather sites

The ETCount() function should display the output as:

E or e: 6

T or t : 9

Ans.:

``````def ETCount():
f = open("testfile.txt",'r')
ec=0
tc=0
for i in d:
if i.lower()=='e':
ec+=1
if i.lower()=='t':
tc+=1
print("E or e:",ec)
print("T or t:",tc)
f.close()
ETCount()
``````

 Aman 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 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_data():
rec={}
fin=open("record.dat","rb")
fout=open("_____________") #Statement 2
found=False
eid=int(input("Enter employee id to update their salary :: "))
while True:
try:
rec=______________ #Statement 3
if rec["Employee id"]==eid:
found=True
rec["Salary"]=int(input("Enter new salary :: "))
pickle.____________ #Statement 4
else:
pickle.dump(rec,fout)
except:
break
if found==True  :
print("The salary of employee id ",eid," has been updated.")
else:
fin.close()
fout.close()``````
1. Which module should be imported in the program? (Statement 1)
2. Write the correct statement required to open a temporary file named temp.dat. (Statement 2)
3. Which statement should Aman 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?

Ans.:

1. pickle
2. open(“temp.dat”,”wb”)
4. pickle.dump(rec,fout)

### 5 Marks Questions File Handling Class 12 Computer Science

 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
f=open(' user.csv','________') # Line 2
newFileWriter = csv.writer(f)
f.close()
with open(' user.csv','r') as newFile:
newFileReader = csv._________(newFile) # Line 3
print (row,row)
newFile.______________ # Line 4
``````

(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.

Ans.:

(a) csv

(b) w mode

(d) close()

(e) Frieda myname@FRD

 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 it to Book.dat.

ii. Write a function CountRec(Author) in Python which accepts the Author name as a parameter and count and return the number of books by the given Author stored in the binary file “Book.dat”.

Ans.:

``````import pickle
def CreateFile():
f=open("book.dat","ab")
book_no=int(input("Enter Book No.:"))
book_name=input("Enter Book Name:")
author=input("Enter author name:")
price=float(input("Enter Price:"))
l=[book_no,book_name,author,price]
pickle.dump(l,f)
f.close()
def CountRec(Author):
c=0
f=open("book.dat","rb")
while True:
try:
if rec==Author:
c+=1
except EOFError:
break
f.close()
return c
CreateFile()
a=input("Enter author to search:")
print("No. of books:",CountRec(a))``````

 A binary file “STUDENT.DAT” has a 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 the number of students scoring above 75%.

``````import pickle
def countrec():
f=open("student.dat","rb")
c=0
while True:
try:
if rec>75:
print(rec,rec,rec)
c+=1
except EOFError:
break
f.close()``````

 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 such as empid, name, mobile, and employee salary respectively.

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

Ans.:

The advantages of using a CSV file for permanent storage are as follows:

1. It is a common file format used to store tabular data
2. It is human readable and easy to modify
3. It is very simple to implement and parse data
4. It can be opened by general-purpose software like notepad, MS Word, MS Excel
5. It is compact and faster to handle as well as small in size
``````import csv
f=open("record.csv","a",newline='')
emp_id=int(input("Enter employee id:"))
ename=input("Enter Name:")
mo=input("Enter Mobile No.:")
sal=int(input("Enter Salary:"))
l=[emp_id,ename,mo,sal]
w=csv.writer(f)
w.writerow(l)
f.close()

def COUNTR():
f=open("record.csv","r",newline='')
c=-1
for i in r:
c+=1
print("No. of records in CSV are:",c)
f.close()``````

 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.

Ans.:

1. Binary files process the data faster than CSV file.
2. Binary files can’t be read by any software by the user directly, CSV data can be read by notepad, MS Word or MS Excel.
3. The endline character or EndOfFile pointer is not present in binary file, the default endline character is /n.
``````import csv
f=open("furniture.csv","a",newline='')
fid=int(input("Enter Furniture ID:"))
fname=input("Enter Furniture Name:")
pri=int(input("Enter Price:"))
l=[fid,fname,pri]
w=csv.writer(f)
w.writerow(l)
f.close()

def search():
f=open("furniture.csv","r",newline='')
for i in r:
if int(i)>10000:
print(i)
f.close()

``````

 Rohit, a student of class 12, is learning CSV File Module in Python. During examination, he has been assigned an incomplete python code (shown below) to create a CSV File ‘Student.csv’ (content shown below). Help him in completing the code which creates the desired CSV File.

CSV File

1,AKSHAY,XII, A

2,ABHISHEK,XII, A

3,ARVIND,XII, A

4,RAVI,XII, A

5,ASHISH,XII,A

Incomplete Code

``````import _____ #Statement-1
fh = open(_____, _____, newline='') #Statement-2
stuwriter = csv._____ #Statement-3
data = [ ]
header = ['ROLL_NO', 'NAME', 'CLASS', 'SECTION']
for i in range(5):
roll_no = int(input("Enter Roll Number : "))
name = input("Enter Name : ")
Class = input("Enter Class : ")
section = input("Enter Section : ")
rec = [ _____ ] #Statement-4
data.append(_____) #Statement-5
stuwriter. _____ (data) #Statement-6
fh.close()
``````

i. Identify the suitable code for blank space in the line marked as Statement-1.

a) csv file

b) CSV

c) csv

d) cvs

Ans.: c) csv

ii. Identify the missing code for blank space in line marked as Statement-2.

a) “Student.csv”,”wb”

b) “Student.csv”,”w”

c) “Student.csv”,”r”

d) “Student.cvs”,”r”

Ans.: b) “Students.csv”,”w”

iii. Choose the function name (with argument) that should be used in the blank space of the line marked as Statement-3.

c) writer(fh)

d) writer(MyFile)

Ans.: c) writer(fh)

iv. Identify the suitable code for blank space in line marked as Statement-4.

a) ‘ROLL_NO’, ‘NAME’, ‘CLASS’, ‘SECTION’

b) ROLL_NO, NAME, CLASS, SECTION

c) ‘roll_no’,’name’,’Class’,’section’

d) roll_no,name,Class,section

Ans.: d) roll_no,name,Class,section

v. Identify the suitable code for blank space in the line marked as Statement-5.

a) data

b) record

c) rec

d) insert

Ans.: c) rec

vi. Choose the function name that should be used in the blank space of line marked as Statement-6 to create the desired CSV File?

a) dump()

c) writerows()

d) writerow()

Ans.: d) writerow()

 Nisha, an intern in ABC Pvt. Ltd., is developing a project using the csv module in Python. She has partially developed the code as follows leaving out statements about which she is not very confident. The code also contains errors in certain statements. Help her in completing the code to read the desired CSV File named “Employee.csv”.

#CSV File Content

ENO, NAME, DEPARTMENT

E1,ROSHAN SHARMA , ACCOUNTS

E2,AASMA KHALID, PRODUCTION

E3,AMRIK GILL,MARKETING

E4,SARAH WILLIAMS, HUMAN RESOURCE

#incomplete Code with Errors

``````import CSV #Statement-1
with open (______,_______ newline='') as. File: #Statement-2
ER= csv. ________ #Statement-3
for R in range (ER) #Statement-4
if __________=="ACCOUNTs" #Statement-5
print(________) #Statement-6``````

i) Nisha gets an Error for the module name used in Statement-1. What should she write in place of CSV to import the correct module ?

a) file

b) csv

c) Csv

d) pickle

Ans.: b) csv

ii) Identify the missing code for blank spaces in the line marked as Statement-2 to open the mentioned file.

a) “Employee.csv”, “r”

b) “Employee.csv”, “w”

c) “Employee.csv”, “rb”

d) “Employee.csv”, “w”

Ans.: a) “Employee.csv”,”r”

iii) Choose the function name (with parameter) that should be used in the line marked as Statement-3.

c) writer (File)

d) writerows (File)

iv) Nisha gets an Error in Statement-4. What should she write to correct the statement?

a) while R in range (ER) :

b) for R in ER:

c) for R = ER:

d) while R = ER:

Ans.: b) for R in ER:

v) Identify the suitable code for blank space in Statement-5 to match every row’s 3rd property with “ACCOUNTS”.

a) ER

b) ER

c) R

d) R

Ans.: c) R

vi) Identify the suitable code for blank space in Statement-6 to display every Employee’s Name and corresponding Department?

a) ER, R

b) R, ER

c) R, R

d) ER, ER

Ans.: c) R, R

Follow the below-given link for more important and most expected questions computer science class 12 from the topics Stack Data Structure, Networking, and Database Management System.

Thank you for visiting my blog. Your suggestions/views/feedback is appreciated, Feel free to share in the comment section.