Professional Documents
Culture Documents
txt="Term 1"
print(txt*2)
a) Term 1 Term 2
b) Term 1Term 1
c) Term 1 2
d) TTeerrmm 11
txt="SQP2021"
if txt.isalnum()==True:
else:
c) SQP2021
d) Error
print(txt.capitalize())
a) char(66)
b) ord(‘B’)
c) char(66)
d) chr(66)
a) t=[1,,2,3,4]
b) t={1,2,3,4}
c) t=<1,2,3,4>
d) t=(1,2,3,4)
51. Which of the following statement is correct?
t=(4,5,6)
t1=t*2
print(t1)
a) (4,5,6,4,5,6)
b) (4,4,5,5,6,6)
c) (8,10,12)
t=(4,5,6)
del t[1]
print(t)
a) (4,6)
b) ([4,6])
c) [4,6]
d) Error
54. Which of the following operation is supported in python with respect to tuple t?
a) t[1]=33
b) t.append(33)
c) t=t+t
d) t.sum()
• print(t[:-1]) , print(t[0:2])
• print(t[3]), print(t[:-3])
• print(t[2:3]), print(3:2)
• print(t[0,2]), print[2,3]
t=(4,5,6,7,8,9,3,2,1)
print(t[5:-1])
a) (8,9,3,2,1)
b) (9,3,2)
c) (4,5,6,7)
d) (2,3,9)
Now next questions for MCQ Term 1 Computer Science Class 12 are based on dictionary topics.
a) mappings
b) hashes
c) associative arrays
a) Mutable
b) Immutable
c) simple
d) complex
59. Mr Subodh is working with a dictionary in python for his project. He wants to display the key, and
value pair but confuse by these statements, choose the correct statement for him:
a) dict.values()
b) disct.keys()
c) dict.keysvalues()
d) dict.items()
60. The fromkeys() method assigns ________ value to key in dictionary by default.
a) 0
b) None
c) Empty
d) Blank
61. Which one of the following is the correct statement for creating a dictionary for assigning a day
number to weekdays using short names?
a) d ={1:Mon,2:Tue,3:Wed,4:Thur}
b) d ={1:’Mon’,2:’Tue’,3:’Wed’,4:’Thur’}
c) d ={1;’Mon’,2;’Tue’,3;’Wed’,4;’Thur’}
d) d ={1-‘Mon’,2-‘Tue’,3-‘Wed’,4-‘Thur’}
62. Om is learning the concept of a dictionary in python. He read something about a dictionary related
to a set of elements. But he forgot the term which type of set of elements, suggest from the below-
given options:
a) sorted
b) ordered
c) unordered
d) random
63. Eshika is trying to delete an element from the dictionary, but she is getting an error – “the given
key is not found in the dictionary”. Which of the following command she has used in the python
a) del dict[key]
b) dict.pop(key)
c) dict.popitem(key)
d) remove dict[key]
64. Which of the following is the correct statement for checking the presence of a key in the
dictionary?
a) <key> in <dictionary_object>
print(d['Virat Kohli'])
a) India
b) India-Virat Kohli
c) Virat Kohli
d) KeyError
print("india" in d)
a) True
b) False
c) Error
d) None
dict={'Manthan':34,'Vishwa':45,'Mayank':50}
print(dict[0])
a) Manthan:34
b) 34
c)Manthan
d) Error
68. Marks in the above-created dictionary are changed after rechecking, where Vishwa got 48 marks
and Mayank got 49 marks. Choose the correct statement for the same:
a) dict.change({‘Vishva’:48,’Mayank’:49})
b) dict.alter({‘Vishva’:48,’Mayank’:49})
c) dict.update({‘Vishva’:48,’Mayank’:49})
d) dict.loc({‘Vishva’:48,’Mayank’:49})
69. What happens when the following statement will be written for the same dictionary created in
Que. No. 67?
dict.update({'Sameer':44})
b) It will add a new key and value at the end of the dictionary
c) It will replace the last key and value with the given key and value
d) It will add a new key and value at the beginning of the dictionary
70. Which of the following code will print output as 3 for the dictionary created in Que. No. 67?
a) print(dict.size)
b) print(size(dict))
c) print(length(dict))
d) print(len(dict))
dict={'x':11,'y':13,'z':15}
s=""
for i in dict:
s=s+str(dict[i])+" "
s1=s[:-1]
print(s1[::-1])
a) 15 13 11
b) 11 13 15
c) 51 31 11
d) 10 13 14
In the next section of MCQ Term 1 Computer Science Class 12, you will get the term 1 MCQ
questions based on working with functions.
a) function
b) start
c) def
d) fun
a) start_game()
b) start game()
c) start-game()
a) function header
b) return statement
c) parameter list
d) function keyword
4. If the return statement is not used in the function then which type of value will be returned by the
function?
a) int
b) str
c) float
d) None
6. The subprogram that acts on data and returns the value sometimes is known as
a) Function
b) Module
c) Class
d) Package
a) Statement A is correct
b) Statement B is correct
c) Statement A is correct but Statement B is not correct
8. Richa is working with a program where she gave some values to the function. She doesn’t know
the term to relate these values. Help her by selecting the correct option.
a) function value
b) arguments or parameters
c) return values
d) function call
9. Mohini wants to know that the symbol : (colon) must be required with which of the following
function part?
a) function header
d) function body
c) return statement
d) parameters
10. Which of the function part contains the instructions for the tasks to be done in the function?
a) function header
d) function body
c) return statement
d) parameters
11. Ananya is trying to understand the features of python functions. She is not understanding the
feature that distributes the work in small parts. Select the appropriate term for her out of the following:
a) Modularity
b) Reusability
c) Simplicity
d) Abstraction
12. Which of the following is not a feature supported by python functions
a) Modularity
b) Reusability
c) Simplicity
d) Data Hiding
13. Divya wants to print the identity of the object used in the function. Which of the following function
is used to print the same?
a) identity()
b) ide()
c) id()
d) idy()
14. Rashmin is learning the python functions He read the topic types of python functions. He read that
functions already available in the python library is called ___________. Fill appropriate word in this
blank :
b) Built-in Functions
c) Modules
d) Reusable Function
15. Which of the following sentence is not correct for the python function?
16. Pranjal wants to write a function to compute the square of a given number. But he missed one
statement in the function. Select the statement for the following code:
def sq(n):
____________
print(sq(3))
a) return square of n
b) return n**2
c) return n
d) print(“n**n”)
17. Select the proper order of execution for the following code:
A. def diff(a,b):
B. c=a-b
D. x,y =7,3
E. diff(x,y)
F. print(“Finished”)
18. What is the maximum and minimum value of c in the following code snippet?
import random
a = random.randint(3,5)
b = random.randint(2,3)
c=a+b
print(c)
a) 3 , 5
b) 5, 8
c) 2, 3
d) 3, 3
19. By default python names the segment with top-level statement as __________________
a) def main()
b) main()
c) __main__
d) _main
a) flow of execution
b) order of execution
c) sequence of execution
d) process of execution
21. In python function, the function calling another function is known as ________________ and the
function being called is known _________
a) main, keyword
b) caller, called
c) called, caller
d) executer, execute
22. Archi is confused between arguments and parameters. Select the fact about argument and
parameter and solve her doubt
a) arguments are those values being passed and parameters are those values received
b) parameters are those values being passed and arguments are those values received
c) arguments appear in the function header and parameters appear in the function call
d) arguments can have same name and parameters can have value type
23. The value is passed through a function call statement is called _________ and the values being
received in the definition is known as __________
a) required arguments
b) mandatory arguments
c) Both a and b
d) None of them
26. The default valued parameter specified in the function header becomes optional in the function
calling statement.
a) Yes
b) No
c) Not Sure
d) May be
27. Which of the following function header is correct :
a) def discount(rate=7,qty,dis=5)
b) def discount(rate=7,qty,dis)
c) def discount(rate,qty,dis=5)
d) def discount(qty,rate=7,dis)
Statement A: Default arguments can be used to add new parameters to the existing functions
Statement B: Default arguments can be used to combine similar functions into one
a) Statement A is correct
b) Statement B is correct
x+=5
y=y-3
return x*y
print(fun(5),fun())
a) 20, 200
b) 170, 255
c) 85, 200
d) 300, 500
def display(n):
global v
v = 15
if n%4==0:
v += n
else:
v -= n
print(v, end="#")
display(20)
print(v)
a) 80#80
b) 80#100
c) 80#35
d 80#20
31. Observe the following lines written for the calling statement and select the appropriate
ele_bill(past_reading=200,rate=6,current_reading=345)
ele_bill(current_reading=345,rate=6,past_reading=200)
ele_bill(rate=6,past_reading=200,current_reading=345)
b) Only line 1 will execute and the rest will raise an error
c) All lines are correct and no errors
def Val(m,n):
for i in range(n):
if m[i]<30:
m[i]//=5
elif m[i]%5 == 0:
m[i]//=3
else:
m[i]//=2
l = [25,8,75,12]
Val(l,4)
for i in l:
print(i,end="$")
a) 1$1$2$25$2$
b) 5$1$25$2$
c) 1$4$25$3$
d) 5$2$15$2$
def or_cap_update(pl,r,i):
pl['Runs']+=r
pl['Innings']+=i
pl1={'S.No':1,'Name':'K L Rahul','Runs':528,'Innings':12}
pl2={'S.No':2,'Name':'Rituraj Gaikwad','Runs':521,'Innings':13}
or_cap_update(pl1,35,1)
or_cap_update(pl2,35,1)
print(pl1)
print(pl2)
a)
b)
c)
d)
a) local
b) global
c) enclosed
d) All of these
[35] Observe the following code and select appropriate answers for the given questions:
total = 1
def multiply(l):#Line 1
for x in l:
total *= x
l=[2,3,4]
print(multiply(_____),end="") # Line4
a) Folder
b) File
c) Package
d) Library
[2] The ____________ are the files that store data pertaining to a specific application, for later use.
a) Data File
b) Program File
c) Source Code
d) Program Code
[3] Which of the following format of files can be created programmatically through python program?
a) Data Files
b) Video Files
c) Media Files
d) Binary Files
[4] Suketu is learning the concept of file handling in python. Where he knew that a type of file stores
information in ASCII or UNICODE characters and each line is terminated by EOL. But he forgets the
file type. Select the appropriate file type for the same.
a) ASCII File
b) Data File
c) Text File
d) Binary File
[5] Supriya doesn’t know about the text file extension. Help her to identify the same out of these:
a) .text
b) .txt
c) .txf
d) .tfx
[6] In python which of the following is the default EOL character?
a) \eol
b) \enter
c) \n
d) \newline
[8] Which of the following statement is not correct for text file?
a) A and B only
b) A, B and C
c) A, C and D
d) All of them
[9] Shiv wants to store the data of his customer using the python program. Suggest the best way to
store the data?
a) Text Files
b) CSV files
c) Binary Files
d) Module File
[10] A basic approach to share large data among different organizations carried out through
a) text files
b) binary files
c) spreadsheets or database
d) email attachments
[11] A ___________ is a simple flat file in a human-readable format that is used to store data in a
spreadsheet or database.
a) text file
b) database file
c) binary file
d) CSV file
a) tuple
b) data/record
c) field
d) format
Statement B: CSV helps into organize a huge amount of data in a proper and systematic way
b) small in size
d) All of them
[16] While opening a file for any operation python looks for
[17] The default directory for performing most of the functions is known as
a) active directory
b) current directory
c) working directory
d) open directory
[18] Biswajit wants to working with files and directories through python. Select the python module to
help him to do finish his work:
a) os
b) csv
c) pickle
d) sys
[19] Manoj wants to get the name of the current directory. Select appropriate statement for the same:
a) os.getcd()
b) os.getcurrentdirectory()
c) os.getcwd()
d) os.currentdirectory()
[20] Identify the function to read first 5 characters of the file from the beginning out of the following:
a) f.read(5)
b) f.read()=5
c) f.readline()
d) f.readlines(5)
[21] Priya has placed the file pointer at 4th line in the text file. Now she wants to read all remaining
lines of a text file. Which function is suitable for her, select the correct one:
a) f.read()
b) f.readlines()
c) f.read(n)
d) f.readlines()
[22] A file customer.txt has been created. Now Which of the following function(s) can be used to open
the file in only reading mode?
i) f=open(“customer.txt”,’r’)
ii) f=open(“customer.txt”,’r+’)
iii) f=open(“customer.txt”)
iv) f=open(“customer.txt”,”rb”)
b) i, ii and iii
c) ii and iii
d) iv only
[23] In which of the following mode the file offset position is not at the begging of the file?
iii) a, a+ or +a
a) i, ii and iii
b) i, and ii only
c) iii only
[24] Which of the following statement is correct for opening file for read and write both mode?
a) r
b) rb
c) a
d) r+ or +r
[24] Puru wants to close a file after reading operation for the file object f. Suggest the correct function
to him.
a) f.close()
b) f.close
c) f.quit()
d) f.exit()
[25] Statement A: It is always a good practice to close the file when read/write operations done in the
file.
Statement B: While closing a file system frees the memory allocated to it.
a) Statement A is Correct
b) Statement B is Correct
[26] Disha is looking for a function to write a stream of bytes in the text file. Which of the following
function is correct?
a) write()
b) writestream()
c) writestatement()
d) writeline()
[27] Atul wants to know that he has closed the file after performing the tasks. Which of the following
function he can used to check whether the file is closed or not?
a) f.close()
b) f.closing()
c) f.closed()
a) access_mode
b) process_mode
c) open_mode
d) select_mode
[29] Which of the following statement is correct about the file closing?
a) If the file object is re-assigned to another file, the previous file is automatically closed
b) every time you need to close the file when you want to re-assign file object to another file
d) None of these
[30] _________ clause close the opened file automatically once control comes outside the clause.
a) for clause
b) while clause
c) with clause
d) None of these
[31] The with clause plays an important role in file handling when
c) File is closed
d) Exception occurs
[32] Statement A: An existing file is opened in the write mode the previous data will be erased.
Statement B: When the existing file is opened in write mode the file object will be positioned at the
end of the file.
a) Statement A is Wrong
b) Statement B is wrong
[33] The ________ mode allows adding data into the existing file at the end of the file.
a) read
b) write
c) binary
d) append
[34] Which of the following function requires a new line character at the end of every sentence to
mark the end of line in writing mode?
a) write()
b) writeline()
c) writelines()
d) dump()
[36] Jenny wants to transfer data into csv from the python console screen. Which of the following is
the correct statement to import the module csv in python?
a) import csv as cv
b) import csv_file as cv
c) import CSV as cv
d) import csv.*
[37] To write data into CSV from python console, which of the following function is correct?
a) csv.write(file)
b) csv.writer(file)
c) csv.Write(file)
d) csv.writerow()
[39] Vansh has created a file names ‘data.txt’. Now he wants to add content as like that data will be
added into the file without erasing old data.
Kindly share your views by filling up this feedback form. Select the appropriate code to do so.
a) f=open(“data.txt”, ‘w’)
b) f=open(“data.txt”,’r’)
c) f=open(“data.txt”,’wb’)
d) f=open(“data.txt”,’a’)
a) f=close()
b) f.exit()
c) f.quit
d) with statement
i) all the resources allocated the file objects get deallocated automatically when the user stops using
the file
a) i, ii and iii
b) i, iii and iv
c) ii, ii and iv
[42] which of the following is the correct statement for with statement?
a) f = open with(‘data’txt’,’w’)
b) with (‘data.txt’,’w’)
c) with open(‘data.txt’,’w’) as f:
d) with open=(‘data.txt’,’w’) as f:
[43] Mr. Alpesh wants to know the standard stream which reads the standard input in python. Select
the correct stream from the following:
a) sys.stdin
b) sys.stdinput
c) sys.input
d) sys.standardin
[44] To use the standard streams, which of the following module can be used?
a) pickle
b) system
c) sys
d) standard
Statement B: Data are written to sys.stdout can be linked to the standard input of another program
with a pipe.
a) Statement A is True
b) Statement B is False
c) Statement B is True
d) Both statements A and B are True
iii) It does not print only exceptions but prints error messages with debugging comments
iv) Can be linked to the standard input of another program with a pipe symbol
b) i, ii and iv
c) i and iv only
d) i, ii and iii
[47] The process of transforming data or an object in RAM to a stream of bytes is _______.
i) Transformation
ii) Pickling
iii) Serialization
iv) Deserialization
a) i and ii
b) ii and iii
c) iii and iv
d) i and iv
a) pickling
b) unpickling
c) decomposition
d) composition
a) 1
b) 2
c) 0
d) None of these
a) object, fileobject
b) fileobject, object
c) filename, filemode
d) None of these
a) Yes, it must be
[52] Which of the following function is used to write steam data from python console to binary file?
a) load()
b) dumps()
c) dump()
d) write()
a) 0
b) 1
c) 2
d) 3
a) read()
b) readdata()
c) dump()
d) load()
a) C – B – A
b) A – B – C
c) A – C – B
d) C – B – A
f=open('story.txt','r')
for i in ____:
print(i,end="")
f.close()
a) range(f)
b) f
c) len(f)
d) None of these
[57] Rani wants to replace the for loop given in the above question:
a) for i in f.readline():
b) for i in f.read():
c) for i in f.readlines():
d) for i in range(len(f)):
[57] Observe the following code that reads the text file ‘para.txt’, choose the correct line code to
count and print those lines end with full stop or comma.
c=0
for i in f:
______________________
c=c+1
print(“count=”,c)
a) if i[len(i)-2]==’.’ or i[len(i)-2]==’,’ :
b) if i[len(i)]==’.’ or i[len(i)]==’,’:
c) if i==’.’ or i==’,’
d) if ‘.’ in i or ‘,’ in i:
Python Revision Tour – MCQs\1 marks Questions
[1] State True or False – ‘Tuple is one of the datat ypes of python having data in key-value
pair.”
[2] State True or False “Python has a set of keywords that can also be used to declare
variables.”
a) %
b) in
c) #
d) **
print(2**3**2)
a) 64
b) 256
c) 512
d) 32
a) eval
b) nonlocal
c) assert
d) pass
d_marks={“Physics”:84,”Chemistry”:85}
a) d_std + d_marks
b) d_std.merge(d_marks)
c) d_std.add(d_marks)
d) d_std.update(d_marks)
[7] What will be the output of the following python dictionary operation?
print(data)
a) True
b) False
c) None
d) Null
Choose one option from the following that will be the correct output after executing the above python
expression.
a) False
b) True
c) or
d) not
s=’CSTutorial@TutorialAICSIP’
o=s.partition(‘Tutorial’)
print(o[0]+o[2])
a) CSTutorial
b) CSTutorialAICSIP
c) CS@TutorialAICSIP
d)Tutorial@TutorialAICSIP
t = str.split(“program”)
print(t)
c) [‘My’,’ is’]
d) [‘My’]
a) “PYTHON”*2
b) “PYTHON” + “10”
c) “PYTHON” + 10
d) “PYTHON” + “PYTHON”
d={‘EmpID’:1111,’Name’:’Ankit Mishra’,’PayHeads’:[‘Basic’,’DA’,’TA’],’Salary’:(15123,30254,5700)}
#S1
d[‘PayHeads’][2]=’HRA’ #S2
d[‘Salary’][2]=8000 #S3
print(d) #S4
But he is not getting output. Select which of the following statement has errors?
a) S1
b) S2 and S3
c) S3
d) S4
a) 30.0
b) 30.5
c) 30.6
d) 30.1
Reason(R): The ‘+’ operator works as concatenate operator with strings and join the given strings
(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
a) Conversion
b) Declaration
c) Calling of Function
d) Function Header
a) Boolean
b) integers
c) strings
d) Class
dict={"Exam":"SSCE", "Year":2022}
dict.update({"Year”:2023} )
a) It will create a new dictionary dict={” Year”:2023} and an old dictionary will be deleted
4+3%5
a) 2
b) 6
c) 0
d) 7
a = a.split('2')
print (b)
[21] Which of the following statement(s) would give an error after executing the following
code?
print(S) # Statement 2
a) Statement 3
b) Statement 4
c) Statement 5
d) Statement 4 and 5
a) int
b) tuple
c) list
d) set
a) else_if
b) for
c) pass
d) 2count
Which of the following will be the correct output if the given expression is evaluated?
a) True
b) False
c)’5’
d)’bye’
[26] Select the correct output of the code:
for i in "CS12":
print([i.lower()], end="#")
a) ‘c’#’s’#’1’#’2’#
b) [“cs12#’]
c) [‘c’]#[‘s’]#[‘1’]#[‘2’]#
(d) [‘cs12’]#
[27] Which of the following Statement(s) would give an error after executing the following
code?
sum_keys =0 #Statement 2
print(sum_keys)
a) Statement 2
b) Statement 4
c) Statement 1
d) Statement 3
print(25//4 +3**1**2*2)
a) 24
b)18
c) 6
d) 12
a) (1,3,4)
b) (0,3,4)
c) (1,12,Error)
d) (1,3,#error)
(b) 144
(c) 121
(d) 1936
message='FirstPreBoardExam@2022-23'
d1={'rno':21, 'name':'Rajveer'}
d2={'name':'Sujal', 'age':17,'class':'XII-A'}
d2.update(d1)
print(d2.keys())
Ans.:
Steps:
a)
F i r s t P r e B o a r d E x a m @ 2 0 2
-25 -24 -23 -22 -21 -20 -19 -18 -17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -
F S R O D A 2
b)
Steps:
a) 322ADORSF
dt=["P",10,"Q",30,"R",50]
t=0
a=""
ad=0
for i in range(1,6,2):
t=t+i
a = a + dt [i-1] + "@"
ad = ad + dt[i]
print (t, ad, a)
Ans.:
Steps:
Iteration Values
i=1
t=t+i
1 t=0+1=1
a=””+”P”+”@”=P@
ad=0+10=10
i=3
t=1+3=4
2
a=’P@’+’Q’+’@’=P@Q@
ad=10+30=40
i=5
t=4+5=9
3
a=’P@Q@’+’R’+’@’
ad=40+50=90
9 90 P@Q@R@
L=[11,22,33,44,55]
Lst=[]
for i in range(len(L)):
if i%2==1:
t=(L[i],L[i]*2)
Lst.append(t)
print(Lst)
Ans.:
Steps:
Iteration Values
0 Condition False
i=1
1 t=(22,44)
Lst=[(22,44)]
2 Condition False
i=3
3 t=(44,88)
Lst=[(22,44),(44,88)]
4 Condition False
str="PYTHON@LANGUAGE"
print(str[2:12:2])
data = [11,int(ord('a')),12,int(ord('b'))]
for x in data:
x = x + 10
print(x,end=' ')
Ans.:
Steps:
a)
P Y T H O N @ L A N G U A G E
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
T O @ A G
b)
Iteration Values
x=11
1
x=x+10=21
x=97
2
x=x+10=97+10=107
x=12
3
x=x+10=12+10=22
X=98
4
X=X+10=98+10=108
a) TO@AG
b) 21 107 22 108
5. Write the output of the following code and the difference between a*3 and (a,a,a)?
a=(1,2,3)
print(a*3)
print(a,a,a)
Ans.:
(1, 2, 3, 1, 2, 3, 1, 2, 3)
Difference:
a*3 will repeate the tuple 3 times where as (a,a,a) will repeat tuple 3 times into a separate tuple.
s="ComputerScience23"
n = len(s)
m=""
m = m +s[i].upper()
m = m +s[i-1]
elif (s[i].isupper()):
m=m+s[i].lower()
else:
m=m+’#’
print(m)
Ans.:
Steps:
C o m p u t e r S c i e n c e 2 3
if: a-n M E C I E C E
elif: n-z C m p u e e
elif-upper c s
else # #
cCMmpuEesCIEeCE##
lst1=[39,45,23,15,25,60]
x=["rahul",5, "B",20,30]
x.insert(1,3)
x.insert(3, "akon")
print(x[2])
Ans.:
Steps:
a)
39 45 23 15 25 60
Index 0 1 2 3 4 5
Index(15) 3+2=5
b)
‘rahul’ 5 ‘B’ 20 30
index 0 1 2 3 4 5 6
insert 1 3
insert 2 akon
x[2] 5
a) 5
b) 5
count=4
while True:
if st=="p":
st=st[2:]
elif st[-2]=="n":
st =st[:4]
else:
count+=1
break
print(st)
print(count)
Ans.:
p y t h o n p r o g r a m m i n g
if False
elif p y t h True
else 4+1=5
pyth
alpha =0
beta = ""
gama = 0
for i in range(1,6,2):
alpha +=i
9 A#B#C# 120
10. Rewrite the following code in python after removing all syntax error(s). Underline each
correction done in the code.
Num=int(rawinput("Number:"))
sum=0
for i in range(10,Num,3)
sum+=1
if i%2=0:
print(i*2)
else:
print(i*3)
print (Sum)
Ans.:
sum=0
sum+=1
print(i*2)
else:
print(i*3)
data = [2,4,2,1,2,1,3,3,4,4]
d = {}
for x in data:
if x in d:
d[x]=d[x]+1
else:
d[x]=1
print(d)
Ans.:
data = [2,4,2,1,2,1,3,3,4,4]
x=2
if 2 in {}:
d[2]=1
if 4 in {2:1}:
d[4]=1
if 2 in {2:1,4:1}:
d[2]=d[2]+1=1+1=2
if 1 in {2:2,4:1}:
d[1]=1
if 2 in {2:2,4:1,1:1}:
d[2]=d[2]+1=2+1=3
if 1 in {2:3,4:1,1:1}:
d[1]=d[1]+1=1+1=2
if 3 in {2:3,4:1,1:2}:
d[3]=1
if 3 in {2:3,4:1,1:2,3:1}:
d[3]=d[3]+1=1+1=2
if 4 in {2:3,4:1,1:2,3:2}:
d[4]=d[4]+1=1+1=2
if 4 in {2:3,4:2,1:2,3:2}:
d[4]=d[4]+1=2+1=3
Ans.:{2:3,4:3,1:2,3:2}
[2] Vivek has written a code to input a number and check whether it is even or odd number.
His code is having errors. Rewrite the correct code and underline the corrections made.
Def checkNumber(N):
status = N%2
return
#main-code
k=checkNumber(num)
if k = 0:
else
Ans.:
def checkNumber(N):
status = N%2
return status
#main-code
k=checkNumber(num)
if k == 0:
else:
[3] Sameer has written a python function to compute the reverse of a number. He has however
committed a few errors in his code. Rewrite the code after removing errors also underline the
corrections made.
define reverse(num):
rev = 0
num = num/10
return rev
print(reverse(1234))
Ans.:
def reverse(num):
rev = 0
while num > 0:
num = num//10
return rev
print(reverse(1234))
def printMe(q,r=2):
p=r+q**3
print(p)
#main-code
a=10
b=5
printMe(a,b)
printMe(r=4,q=2)
Ans.:
a=10
b=5
printMe(10,5)
q=10
r=5
p=r+q**3
=5+10**3
=5+1000
=1005
printMe(4,2)
q=2
r=4
p=r+q**3
=4+2**3
=4+8
=12
Output:
1005
12
def foo(s1,s2):
l1=[]
l2=[]
for x in s1:
l1.append(x)
for x in s2:
l2.append(x)
return l1,l2
a,b=foo("FUN",'DAY')
print(a,b)
Ans:
a,b=foo("FUN","DAY")
foo('FUN','DAY')
l1=[]
l2=[]
for x in 'FUN':
l1.append(x)
So l1=['F','U','N']
for x im 'DAY':
l2.append(x)
So l2=['D','A','Y']
[6] Preety has written a code to add two numbers . Her code is having errors. Rewrite the
correct code and underline the corrections made.
def sum(arg1,arg2):
total=arg1+arg2;
print(”Total:”,total)
return total;
sum(10,20)
print(”Total:”,total)
Ans.:
def sum(arg1,arg2):
print(”Total:”,total)
print(”Total:”,total)
[7] What do you understand the default argument in function? Which function parameter must
be given default argument if it is used? Give example of function header to illustrate default
argument.
Ans.:
The value provided in the formal arguments in the definition header of a function is called as default argument in function.
They should always be from right side argument to the left in sequence.
For example:
[8] Ravi a python programmer is working on a project, for some requirement, he has to define
a function with name CalculateInterest(), he defined it as:
# code
But this code is not working, Can you help Ravi to identify the error in the above function and
what is the solution?
In the function CalculateInterest (Principal, Rate=.06,Time) parameters should be default parameters from right to left hence either
Time should be provided with some default value or default value of Rate should be removed
[9] Rewrite the following code in python after removing all the syntax errors. Underline each
correction done in the code.
Function F1():
num1,num2 = 10
num1+=20
num2+=30
Else:
print('hello')
Ans.:
def F1():
num1,num2 = 10, value is missing
num1+=20
num2+=30
else:
print('hello')
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.:
R=150
S=100
R=change(150,100)
p=p+q
=150+100
=250
q=p-q
=250-100
=150
r=250
s=150
Print 1 - 250#150
Print 2 - 250#100
R=100
S=30
R=change(100,30)
p=p+q
=100+30
=130
q=p-q
=130-30
=150
Print 3 - 130#100
250#150
250#100
130#100
130#100
For example:
Ans.:
def ThreeLetters(L):
l3=[]
for i in range(len(L)):
if len(L[i])==3:
l3.append(L[i])
l3.append(i)
return l3
print(ThreeLetters(l))
[2] Write a function modifySal(lst) that accepts a list of numbers as an argument and increases
the value of the elements (basic) by 3% if the elements are divisible by 10. The new basic must
be integer values.
For example:
Ans.:
def modifySal(lst):
for i in range(len(lst)):
if lst[i]%10==0:
lst[i]=int(lst[i]+(lst[i]*0.03))
return lst
basic_li=[25000,15130,10135,12146,15030]
print(modifySal(basic_li))
[3] Write a function not1digit(li), where li is the list of elements passed as an argument to the
function. The function returns another list that stores the indices of all numbers except 1-digit
elements of li.
For example:
If L contains [22,3,2,19,1,69]
Ans.:
def not1digit(li):
l=[]
for i in range(len(li)):
if li[i]>9:
l.append(li[i])
return l
li=[22,3,2,19,1,69]
print(not1digit(li))
[4] Write a function shiftLeft(li, n) in Python, which accepts a list li of numbers, and n is a numeric
value by which all elements of the list are shifted to the left.
def LeftShift(li,n):
li[:]=li[n:]+li[:n]
return li
print(LeftShift(aList,n))
[5] Write a function cube_list(lst), where lst is the list of elements passed as an argument to
the function. The function returns another list named ‘cube_List’ that stores the cubes of all
Non-Zero Elements of lst.
For example:
If L contains [2,3,0,5,0,4,0]
def cube_list(lst):
cube_list=[]
for i in range(len(lst)):
if lst[i]!=0:
cube_list.append(lst[i]**3)
return cube_list
l=[2,3,0,5,0,4,0]
print(cube_list(l))
[6] Write a function in Python OddEvenTrans(li) to replace elements having even values with
their 25% and elements having odd values with thrice (three times more) of their value in a list.
For example:
def OddEvenTrans(li):
for i in range(len(li)):
if l[i]%2==0:
l[i]=l[i]*0.25
else:
l[i]=l[i]*3
return li
l=[10,8,13,11,4]
print(OddEvenTrans(l))
[7] Write a function listReverse(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:
Ans.:
def reverseList(li):
rev_li=[]
for i in range(-1,-len(li)-1,-1):
rev_li.append(li[i])
return rev_li
l=[79,56,23,28,98,99]
print(reverseList(l))
[8] Write a function in python named Swap50_50(lst), which accepts a list 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.
l= [8, 9, 7,1,2,3]
Output = [1,2,3,8,9,7]
ddef Swap50_50(lst):
s1=s2=0
L=len(lst)
for i in range(0,L//2):
s1+=lst[i]
s2+=lst[i]
if s1>s2:
for i in range(0,L//2):
lst[i],lst[i+L//2]=lst[i+L//2],lst[i]
l=[8,9,7,1,2,3]
Swap50_50(l)
[9] Write a function vowel_Index(S), where S is a string. The function returns a list named ‘il’
that stores the indices of all vowels of S.
For example: If S is “TutorialAICISP”, then index List should be [1,4,6]
def vowel_Index(S):
il=[]
for i in range(len(S)):
if S[i] in 'aeiouAEIOU':
il.append(i)
return il
s='TutorialAICSIP'
print(vowel_Index(s))
[10] Write a function NEW_LIST(L), where L is the list of numbers integers and float together. Now
separate integer numbers into another list int_li.
For example:
If L contains [123,34.8, 54.5,0,8.75,19,86.12,56,78,6.6]
The NewList will have [123,0,19,56,78]
def NEW_LIST(L):
int_li=[]
for i in range(len(L)):
if type(L[i])==int:
int_li.append(L[i])
return int_li
l=[123,34.8, 54.5,0,8.75,19,86.12,56,78,6.6]
print(NEW_LIST(l))
Important Questions File Handling
File handling 2/3 marks questions
[1] 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.
Ans.:
def countVowel():
c=0
f=open('info.txt')
dt=f.read()
for ch in data:
if ch.lower() in 'aeiou':
c=c+1
[2] 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:
He wants to be perfect.
Ans.:
def displaywords():
f= open('data.txt','r')
s= f.read()
lst = s.split()
for x in lst:
if len(x)>3:
f.close()
[3] Write a function countINDIA() which read a text file ‘myfile.txt’ and print the frequency of word
‘India’ in each line. (Ignore its case)
Example:
INDIA is my country.
Ans.:
def displaywords():
f = open('data.txt','r')
s = f.read()
lst = s.split()
for x in lst:
if len(x)>3:
f.close()
[4] 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)
Ans.:
def COUNT_AND( ):
c=0
f=open(‘STORY.TXT','r')
dt = f.read()
w = dt.split()
for i in w:
if i.lower()=='and':
c=c+1
f.close()
[5] Write a function DISPLAYWORDS( ) in python to display the count of words starting with “t” or “T”
in a text file ‘STORY.TXT’.
def DISPLAYWORDS( ):
c=0
f=open('STORY.TXT','r')
l = f.read()
w = l.split()
for i in w:
if i[0]=="T" or i[0]=="t":
c=c+1
f.close()
1 Aditya 2021
2 Arjun 2018
3 Aryan 2016
4 Sagar 2022
Code:
def client_names():
count_rec=0
count_s=0
if row[1][0].lower() == "s":
print(row[0],",",row[1],",",row[2])
count_s += 1
count_rec += 1
print(count_rec, count_s)
Read the questions given below and fill in the gaps accordingly: 1 + 1 + 2
[2] Arpan is a Python programmer. He has written code and created a binary file school.dat
with rollno, name, class, and marks. The file contains few records. He now has to search
records based on rollno in the file school.dat. As a Python expert, help him to complete the
following code based on
the requirement given above:
Code:
def find_records():
f=open(______________________) # staement2
found=False
try:
while True:
data=_______________ # statement 3
for rec in data:
if r==_______: # staement4
found=True
print('Name: ',rec[1])
print('Class : ',rec[2])
print('Marks :',rec[3])
break
except Exception:
f.close()
if found==True:
print('Search successful')
else:
Help Arpan to answer the following questions to fill in the given gaps: 1 + 1 + 2
[3] Arjun 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:
1. GetPatients() to create a binary file called PATIENT.DAT containing student information – case
number, name, and charges of each patient.
2. FindPatients() to display the name and charges of those patients who have charges greater than 8000.
In case there is no patient having charges > 8000 the function displays an appropriate message. The
function should also display the average charges also.
Ans.:
import pickle
def GetPatient():
f=open("patient.dat","wb")
while True:
pickle.dump(l,f)
if Choice in "nN":
break
f.close()
def FindPatient():
total=0
cr=0
more_8k=0
with open("patient.dat","rb") as F:
while True:
try:
R=pickle.load(F)
cr+=1
total+=R[2]
more_8k+=1
except:
break
try:
except ZeroDivisionError:
GetPatient()
FindPatient()
[4] Mitul is a Python programmer. He has written a code and created a binary file
emprecords.dat with employeeid, name, and salary. The file contains 5 records.
1. 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.
2. The records which are not to be updated also have to be written to the file temp.dat.
3. 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("emprecords.dat","rb")
fout=open("_____________") #Statement2
found=False
while True:
try:
rec=______________#Statement 3
if rec["Employee id"]==eid:
found=True
pickle.____________ #Statement 4
else:
pickle.dump(rec,fout)
except:
break
if found==True:
else:
print("No employee with such id is found")
fin.close()
fout.close()
[5] Nandini has written a program to read and write using a csv file. She has written the
following code but is not able to complete code.
tr = ['BookID','Title','Publisher']
f = open('books.csv','w', newline="")
csvwriter = csv.writer(f)
csvwriter.writerow(tr)
_______________ #Statement 2
f.close()
f = open('books.csv','r')
csvreader = csv.reader(f)
print(top_row)
print(x)
Help her to complete the program by writing the missing lines by following the questions:
a) Statement 1 – Write the python statement that will allow Nandini to work with csv file.
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 into the top_row object.
d) Statement 4 – Write the object that contains the data that has been read from the file.
In the next section of Most expected questions in Computer Science class 12, we are going to cover
questions from data file handling which can be asked in 5 marks. Let us begin!
(i) insert() – To accept and add data of a apps to a CSV file ‘apps.csv’. Each record consists of a list
with field elements as app_id, name and mobile to store id, app name and number of downloads
respectively.
(ii) no_of_records() – To count the number of records present in the CSV file named ‘apps.csv’.
Ans.:
import csv
def insert():
f=open('apps.csv','a',newline='')
model=input("Enter Model:")
company=input("Enter Company:")
l=[app_id,app_name,model,company,downloads]
wo=csv.writer(f)
wo.writerow(l)
f.close()
Method 1
def no_of_records():
f=open("apps.csv",'r')
ro=csv.reader(f)
l=list(ro)
print("No. of records:",len(l))
f.close()
Method 2
def no_of_records():
f=open("apps.csv",'r')
ro=csv.reader(f)
c=0
for i in ro:
c+=1
print("No. of records:",c)
f.close()
Function Calling:
insert()
no_of_records()
[2] 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 ‘emp.csv’. Each record consists of a
list with field elements as eid, name and salary to store employee id, employee name and employee
salary respectively.
(ii) search()- To display the records of the employee whose salary is more than 40000.
Ans.:
The binary file contains data in 0s and 1s form CSV file contains data in tabular form
def add():
f=open('emp.csv','a',newline='')
empid=int(input("Enter employee ID:"))
sal=float(input("Enter Salary:"))
l=[empid,empname,sal]
wo=csv.writer(f)
wo.writerow(l)
f.close()
def search():
f=open("emp.csv",'r')
ro=csv.reader(f)
for i in ro:
if float(i[2])>40000:
print(i)
f.close()
Function Calling:
add()
search()
[3] What is delimiter in CSV file? Write a program in python that defines and calls the following user
defined function:
i) Add() – To accept data and add data of 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.
ii) CountR():To count number of records present in CSV file named ‘record.csv’.
Ans.:
Delimiter refers to a character used to separate the values or lines in CSV file. By default delimiter for
CSV file values is a comma and the new line is ‘\n’. Users can change it anytime.
[4] Give any one point of difference between a text file and csv file. Write a python program which
defines and calls the following functions:
i) add() – To accept and add data of a furniture to a csv file ‘furdata.csv’. Each record consists of a list
with field elements such as fid, name and fprice to store furniture id, furniture name and furniture price
respectively.
ii) search() – To display records of sofa whose price is more than 12000.
Ans.:
It represents data into ASCII format. It represents data into ASCII form and in tabular form.
def add():
f=open('furdata.csv','a',newline='')
price=float(input("Enter price:"))
l=[fid,fname,price]
wo=csv.writer(f)
wo.writerow(l)
f.close()
Code for search()
def search():
f=open("furdata.csv",'r')
ro=csv.reader(f)
for i in ro:
print(i)
f.close()
[5] Archi of class 12 is writing a program to create a CSV file “user.csv” which contains user name
and password for some entries. He has written the following code. As a programmer, help her to
successfully execute the given task.
f=open('user.csv','_') #Line2
w=csv.writer(f)
w.writerow([UserName,Password])
f.close( )
with open('user.csv','r') as f:
ro=csv.________________(newFile) #Line3
for i in ro:
print(i)
f.__________ #Line4
addCsvFile('Aditya','987@555')
addCsvFile('Archi','arc@maj')
addCsvFile('Krish','krisha@Patel')
readCsvFile()
OUTPUT___________________ #Line 5
1. What module should be imported in #Line1 for successful execution of the program?
2. In which mode file should be opened to work with user.csv file in#Line2
3. Fill in the blank in #Line3 to read data from csv file
4. Fill in the blank in #Line4 to close the file
5. Write the output he will obtain while executing Line5
Ans.:
1. csv
2. ‘a’
3. reader
4. close
5. Output:
['Aditya'.'987@555']
['Archi','arc@maj']
['Krish','Krisha@Patel']
b) Overflow
c) Underflow
d) Clear Stack
[2] ____________ is an effective and reliable way to represent, store, organize and manage data in
systematic way.
a) Information
b) Data
c) Data Structure
d) Abstract Data
a) Data item
b) Data Structure
c) Raw Data
d) None of these
[5] Statement A: Data Type defines a set of values alog with well-defined operations starting its input-
output behavior
Statement B: Data Structure is a physical implementation that clearly defines a way of storing,
accessing, manipulating data.
a) dictionary
b) set
c) tuple
d) list
[7] The Data Structures can be classified into which of the following two types?
a) Stack
b) Queue
c) Linked List
d) Tree
[10] Which of the following is/are an example(s) of python ‘s built-in linear data structure?
a) List
b) Tuple
c) Set
d) All of these
[11] _____________ is a linear data structure implemented in LIFO manner where insertion and
deletion are restricted to one end only.
a) Stack
b) Queue
c) Tree
d) Linked List
[13] Which of the following operation of stack is performed while inserting an element into the stack?
a) push
b) pop
c) peep
d) Overflow
[14] Which of the folloiwng operation is considered as deletion of element from stack?
a) push
b) pop
c) underflow
d) overflow
a) front
b) top
c) middle
d) bottom
a) push
b) pop
c) peek
d) underflow
[11,20,45,67,23]
push(19)
pop()
push(24)
pus(42)
pop()
push(3)
a) [11,20,45,67,23]
b) [3,24,11,20,67,23]
c) [42,24,11,20,67,23]
d) [24,11,20,67,23]
a) FILO
b) FIFO
c) FOFI
d) LOFI
11
22
23
34
91
34
91
a) delete()
b) pop()
c) remove()
d) clear()
[6] What is LIFO data structure? Give any two applications of a stack?
[7] Name any two linear Data Structures? What do you understand by the term LIFO?
[11] Consider STACK=[23,45,67,89,51]. Write the STACK content after each operations:
1. STACK.pop( )
2. STACK.append(99)
3. STACK.append(87)
4. STACK.pop( )
Ans.:
def push(student):
student.append(name)
def pop(student):
if student==[]:
print("Underflow")
else:
student.pop()
2. Write PUSH(Names) and POP(Names) methods in python to add Names and Remove names
considering them to act as Push and Pop operations of Stack.
def PUSH(Names):
name=input("Enter name:")
Names.append(name)
def POP(Names):
if Names==[]:
print("Underflow")
else:
Names.pop()
3. Ram has created a dictionary containing names and age as key value pairs of 5 students.
Write a program, with separate user defined functions to perform the following operations:
Push the keys (name of the student) of the dictionary into a stack, where the corresponding
value(age) is lesser than 40. Pop and display the content of the stack.
R={“OM”:35,”JAI”:40,”BOB”:53,”ALI”:66,”ANU”:19}
ANU OM
R={"OM":35,"JAI":40,"BOB":53,"ALI":66,"ANU":19}
def Push(stk,n):
stk.append(n)
def Pop(stk):
if stk!=[]:
return stk.pop()
else:
return None
s=[]
for i in R:
if R[i]<40:
Push(s,i)
while True:
if s!=[]:
print(Pop(s),end=" ")
else:
break
4. SHEELA has a list containing 5 integers. You need to help Her create a program with
separate user defined functions to perform the following operations based on this list.
1. Traverse the content of the list and push the odd numbers into a stack.
2. Pop and display the content of the stack.
For Example:
N=[79,98,22,35,38]
N=[79,98,22,35,38]
def Push(stk,on):
stk.append(on)
def Pop(stk):
if stk==[]:
return None
else:
return stk.pop()
stk=[]
for i in N:
if i%2!=0:
Push(stk,i)
while True:
if stk!=[]:
print(Pop(stk),end=" ")
else:
break
5. Write a function in Python PUSH_IN(L), where L is a list of numbers. From this list, push all
even numbers into a stack which is implemented by using another list.
N=[79,98,22,35,38]
def Push(stk,on):
stk.append(on)
def Pop(stk):
if stk==[]:
return None
else:
return stk.pop()
stk=[]
for i in N:
if i%2==0:
Push(stk,i)
while True:
if stk!=[]:
print(Pop(stk),end=" ")
else:
break
def POP_OUT(Stk):
if Stk==[]:
return None
else:
return Stk.pop()
7. Julie has created a dictionary containing names and marks as key value pairs of 6 students.
Write a program, with separate user defined functions to perform the following operations:
1. Push the keys (name of the student) of the dictionary into a stack, where the corresponding
value (marks) is greater than 75.
2. Pop and display the content of the stack.
For example:
The output from the program should be: TOM ANU BOB OM
def Push(stk,n):
stk.append(n)
def Pop(stk):
if stk!=[]:
return stk.pop()
else:
return None
s=[]
for i in R:
if R[i]>75:
Push(s,i)
while True:
if s!=[]:
print(Pop(s),end=" ")
else:
break
8. Raju has created a dictionary containing employee names and their salaries as key value
pairs of 6 employees. Write a program, with separate user defined functions to perform the
following operations:
1. Push the keys (employee name) of the dictionary into a stack, where the corresponding value
(salary) is less than 85000.
2. Pop and display the content of the stack.
For example:
def Push(stk,sal):
stk.append(sal)
def Pop(stk):
if stk==[]:
return None
else:
return stk.pop()
stk=[]
for i in Emp:
if Emp[i]<85000:
Push(stk,i)
while True:
if stk!=[]:
print(Pop(),end=" ")
else:
break
9. Anjali has a list containing temperatures of 10 cities. You need to help her create a program with
separate user-defined functions to perform the following operations based on this list.
1. Traverse the content of the list and push the negative temperatures into a stack.
2. Pop and display the content of the stack.
For Example:
def Push(s,n):
s.append(n)
def Pop(s):
if s!=[]:
return s.pop()
else:
return None
s=[]
for i in T:
if i<0:
Push(s,i)
while True:
if s!=[]:
else:
break
10. Ms.Suman has a list of integers. Help her to create separate user defined functions to
perform following operations on the list.
def DoPush(elt):
L= [2,5,6,11,18,24,32,37,42,47]
for i in L:
for j in range(2,i):
if i % j ==0:
break
else:
elt.append(i)
def DoPop(s):
if s!=[]:
return s.pop()
else:
return None
s=[]
DoPush(s)
while True:
if s!=[]:
print(DoPop(s),end=" ")
else:
break
11. Mr. Ramesh has created a dictionary containing Student IDs and Marks as key value pairs
of students. Write a program to perform the following operations Using separate user defined
functions.
1. Push the keys (IDs) of the dictionary into the stack, if the corresponding marks is >50
2. Pop and display the content of the stack
Do Yourself…
12. Write AddNew (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?
def AddNew(Book):
Book.append(name)
def Remove(Book):
if Book==[]:
print("Underflow")
else:
Book.pop()
13. Assume a dictionary names RO having Regional Offices and Number of nodal centre
schools as key-value pairs. Write a program with separate user-defined functions to perform
the following operations:
1. Push the keys (Name of Region Office) of the dictionary into a stack, where the corresponding
value (Number of Nodal Centre Schools) is more than 100.
2. Pop and display the content of the stack.
For example
Do yourself…
14. Write a function in Python PUSH (Lst), where Lst is a list of numbers. From this list push
all numbers not divisible by 7 into a stack implemented by using a list. Display the stack if it
has at least one element, otherwise display appropriate error message.
def PUSH(Lst):
stk=[]
for i in range(len(Lst)):
if Lst[i]%7==0:
stk.append(Lst[i])
if len(stk)==0:
print("Stack is underflow")
else:
print(stk)
15. Write a function in Python POP(Lst), where Lst is a stack implemented by a list of
numbers. The function returns the value deleted from the stack.
def POP(Lst):
if len(stk)==0:
return None
else:
return Lst.pop()
16. Reva has created a dictionary containing Product names and prices as key value pairs of 4
products. Write a user defined function for the following:
PRODPUSH() which takes a list as stack and the above dictionary as the parameters. Push the keys
(Pname of the product) of the dictionary into a stack, where the corresponding price of the products is
less than 6000. Also write the statement to call the above function.
17. Pankaj has to create a record of books containing BookNo, BookName and BookPrice.
Write a user- defined function to create a stack and perform the following operations:
1. Input the Book No, BookName and BookPrice from the user and Push into the stack.
2. Display the status of stack after each insertion.
def Push():
books=[]
stk=[]
books=[bno,bname,bprice]
stk.append(books)
print(stk)
>>> mydict={9446789123:”Ram”,8889912345:”Sam”,7789012367:”Sree”}
>>> push(mydict)
Phone number: 9446789123 last digit is less than five which can’t be pushed
mydict={9446789123:"Ram",8889912345:"Sam",7789012367:"Sree"}
def Push(mydict):
stk=[]
for i in mydict:
if i%10>=5:
stk.append(i)
print(stk)
Push(mydict)
19. Write a function to push an element in a stack which adds the name of passengers on a
train, which starts with capital ‘S’. Display the list of passengers using stack.
L = ['Satish','Manish','Sagar','Vipul']
def Push(L,name):
L.append(name)
stk=[]
for i in L:
if i[0]=='S':
Push(stk,i)
print(stk)
20. In a school a sports club maintains a list of its activities. When a new activity is added
details are entered in a dictionary and a list implemented as a stack. Write a push() and pop()
function that adds and removes the record of activity. Ask user to entre details like Activity,
Type of activity, no. of players required and charges for the same.
Do Yourself…
Answers:
1. IoT
2. router
3. Network bandwidth
4. Email
5. People can take e-waste to recycling centres
6. SMTP
7. Cyber Stalking
8. Radiowave or Microwave
9. Wireless Fidelity
10. bps -> Kbps -> Mbps -> Gbps -> Tbps
11. VoIP
12. Wired – Optical Fibre, Wireless – Microwave
[3] Dhara wants to connect her telephone network with the internet. Suggest a device she
should use for the same and write any two functions of the device.
[5] Bharti wants to know the term used for the process of converting a domain name into IP
address. How it works?
[6] Illustrate the layout for connecting 5 computers in a Bus and a Star topology of Networks.
bus-
topology-class-12-computer-science
start-
topology-computer-science-class-12-imp-questions
[7]
(a) Santosh wants a client/server protocol, in which e-mail is received and held by him on his
computer from an Internet server. Regularly, it should check his mailbox on the email server
and download mails to his computer. Which protocol out of the following will be ideal for the
same?
(i) POP3
(ii) SMTP
(iii) VoIP
(iv) HTTP
(b) Riya is in India and she is interested in communicating with her friend in Canada. She
wants to show one of her paintings to him and also wants to explain how it was prepared
without physically going to Canada. Which protocol out of the following will be ideal for the
same?
(i) POP3
(ii) SMTP
(iii) VoIP
(iv) HTTP
[8]
(a) Ketan is working as a team leader in Resonance LTD. Company. He wants to host an online
meeting for all the branches of India and present an annual report. Which technology is best
suited for such a task?
(b) Mahi is accessing remote computers and data over TCP/IP networks. Which protocol is
used to do this?
[9] Write short note on packet switching, message switching and circuit switching.
[10] Out of the following wired and wireless mediums of communication, which is the fastest:
[11] Vidya College has three departments that are to be connected into a network.
(a) Which of the following communication medium out of the given options should be used by
the college for connecting their departments for very effective high-speed communication?
1. Coaxial cable
2. Optical Fibre
3. Ethernet Cable
(b) Also name the type of network out of (LAN/WAN/MAN) formed between various
departments of the college.
[12]
(a) Which network device regenerates the signal over the same network before the signal
becomes too weak or corrupted .
(b) Which network device connects two different networks together that work upon different
networking models so that two networks can communicate properly.
[13]
(iii) Node
(i) Star
(ii) Bus
(iii) Ring
(iv) Ethernet
[14] Identify the following media out of guided and unguided media?
1. This device links two networks together and is not a broadcast device, as it filters traffic depending
upon the receiver’s MAC address.
2. This device offers a dedicated bandwidth.
[16] Expand TCP/IP. Write the purpose of TCP/IP in the communication of data on a network.
[17] Write the expanded names for the following abbreviated terms used in Networking:
(i) MBPS
(ii) WAN
(iii) CDMA
(iv) WLL
1. TV Remotes
2. Cellular Networks
[24] (i) Name the connector used to connect ethernet cable to computer and hub or switch.
[25] (i) Name a network topology, which is used to maximize speed and make each computer
independent of the network.
(ii) Suggest a switching technique in which the information is transferred using Store and
Forward mechanism.
[26] Write two advantages of using an optical Fiber cable over a Twisted Pair cable to connect
two service stations which are 200m away from each other.
[27] What is the difference between hub and switch? Which is preferable in a large network of
computers and why?
[29] Prakash wishes to install a wireless network in his office. Explain him the differences
between guided and unguided media.
[30] Which media is best for the following:
(iv) 4G
[2] Yashvi wants to change the structure of table in MySQL. Select an appropriate SQL command and
help her to accomplish her task.
a) update
b) alter
c) modify
d) change
[3] Alpesh wants to remove a column from a table in SQL. Which command is used to remove a
column from a table in SQL?
a) update
b) remove
c) alter
d) drop
[4] Observe the given keywords used in mysql queries and identify which keyword is not used
with DDL comamnd?
a) DROP
b) MODIFY
c) DISTINCT
d) ADD
[5] Bhavi wants to assign NULL as the value for all the tuples of a new Attribute in a relation. Select
an appropriate command to fulfill her need.
a) MODIFY
b) DROP
c) ADD
d) ALTER
[6] Kiran wants to remove rows from a table. She has given the following commands but she
is confused about which one is the correct command. Help her to identify the correct
command to accomplish her task.
a) DELETE command
b) DROP Command
c) REMOVE Command
d) ALTER Command
[7] State true or false – “Drop command will remove the entire database from MySQL.”
[8] There are various keys associated with database relations. Select an appropriate invalid
key out of the following:
a) Primary Key
b) Master key
c) Foreign Key
d) Unique Key
[10] Raj is preparing for DBA. He read something as a non-key attribute of a relation whose
values are derived from the primary key of another table. Help him to identify the term he read
about.
a) Primary key
b) Foreign key
c) candidate key
d) Alternate key
[12] Anirudh wants to use the SELECT statement combined with the clause which returns
records without repetition. Help him by selecting appropriate keyword to fulfill his task.
a) distinct
b) describe
c) unique
d) null
[13] Vinay wants to identify the keyword used to obtain unique values in a SELECT query from
the following
a) UNIQUE
b) DISTINCT
c) SET
d) HAVING
[14] Priyank wants to display total number of records from MySQL database table. Which
command help him to the task out of the following?
a) total(*)
b) sum(*)
c) count(*)
d) all(*)
[15] Udit is learning the concept of operators in SQL. Help him to identify the Logical
Operators used in SQL by selecting the appropriate option.
a) AND,OR,NOT
b) &&,||,!
c) $,|,!
d) None of these
[16] Hriday wants to fetch records from a table that contains some null values. Which of the
following ignores the NULL values in SQL?
a) Count(*)
b) count(column_name)
c) total(*)
d) None of these
[2] Hetal is inserting “Rathod” in the “LastName” column of the “Emp” table but an error is
being displayed. Write the correct SQL statement.
[3] Darsh created the following table with the name ‘Friends’ :
Table : Friends
Now, Darsh wants to delete the ‘Hobbies’ column. Write the MySQL statement.
[4] Mr. Nikunj entered the following SQL statement to display all Salespersons of the cities
“Chennai” and ‘Mumbai’ from the table ‘Sales’.
Table: Sales
He is getting the Empty Set as output. Explain the problem with the statement and rewrite the
correct statement.
[5] Is NULL value the same as 0 (zero) ? Write the reason for your answer.
[6] Write the UPDATE command to increase the commission (Column name : COMM) by 500 of
all the Salesmen who have achieved Sales (Column name : SALES) more than 200000. The
table’s name is COMPANY.
[7] While using SQL pattern matching, what is the difference between ‘_’ (underscore) and ‘%’
wildcard symbols?
[8] What is the meaning of open source and open source database management system?
[9] In a table employee, a column occupation contains many duplicate values. Which keyword
would you use if wish to list of only different values? Support your answer with example.
[11] Charvi wants to delete the records where the first name is Rama in the emp table. She has
entered the following SQL statement. An error is being displayed. Rewrite the correct
statement.
[13] Rani wants to add another column ‘Hobbies’ with datatype and size as VARCHAR(50) in
the already existing table ‘Student’. She has written the following statement. However, it has
errors. Rewrite the correct statement.
MODIFY TABLE Student Hobbies VARCHAR;
[14] Write SQL query to display employee details from table named ‘Employee’ whose
‘firstname’ ends with ‘n’ and firstname contains a total of 4 characters (including n).
[17] What is MySQL used for? Ajay wants to start learning MySQL. From where can he obtain
the MySQL software?
[18] In the table ‘‘Student’’, Priya wanted to increase the Marks (Column Name:Marks) of those
students by 5 who have got Marks below 33. She has entered the following statement :
(i) Name the Data type that should be used to store AccountCodes like ‘‘A1001’’ of Customers.
(ii) Name two Data types that require data to be enclosed in quotes.
Table – Player
Pcode Points
P001 95
P002 82
P003 74
P004 93
P005 77
[21] Differentiate between char and varchar. Priya has created a table and used char(10) and
varchar(10) as a datatype for two of the columns of her table. What (10) indicate here?
[22] ‘Employee’ table has a column named ‘CITY’ that stores city in which each employee
resides. Write SQL query to display details of all rows except those rows that have CITY as
‘DELHI’ or ‘MUMBAI’ or ‘CHANDIGARH’.
(i) Ajay will certainly have to insert a value in this field when he inserts a new row in the table.
[24] ‘STUDENT’ table has a column named ‘REMARK’ that stores Remarks. The values stored
in REMARK column in different rows are “PASS” or “NOT PASS” or “COMPTT” etc. Write SQL
query to display details of all rows except those that have REMARK as “PASS”.
S001 250
S002 100
S002 200
Table : Hotel
Mr. Vinay wanted to display the average salary of each Category. He entered the following SQL
statement. Identify error(s) and Rewrite the correct SQL statement.
Field Constraint
OrderAmount
StoreID
1. What is the data type of columns OrderId and OrderDate in the table Order?
2. Namrata is now trying to insert the following row : O102, NULL, 59000, S105
[28] Write SQL query to create a table ‘Event’ with the following structure :
Foreign Key
clientid integer
Parent table (Client)
eventdate date
[29] How is a Primary key constraint different from a Unique key constraint?
[30] Write two similarities between CHAR and VARCHAR data types.
[31] Consider “TravelPackage” table with “source” column. Entering data for the Location
column is optional. If one enters data for a row with no value for the “source” column, what
value will be saved in the “source” column? Write SQL statement to display the details of
rows in the “travelpackage” table whose location is left blank.
[35] A NULL value can be inserted into a foreign key? Justify your answer.
[36] Ravindra is confused about what is a domain? Clear his confusion with an example.
1001 1 Shailesh X 76
1003 3 Dinesh XI 85
[39] A table “clustergames” exists with 4 columns and 6 rows. What is its degree and
cardinality, initially? 2 rows are added to the table and 1 column deleted. What will be the
degree and cardinality now?
[40] Sejal wants to create a table patient. Help her to do the following:
(i) She is confused about how the dates are stored in MySQL? Suggest the date format.
(ii) She want to display all records from the table and she wrote the following command:
[41] What is sorting? Which keyword is used to sort data from the table in SQL?
[42] Rajni wants to apply sorting on a table through SQL. But he is not aware about how to use
order by clause. Explain the order by clause in short to him with example.
Table – Participant
1. When the table ‘‘PARTICIPANT’’ was first created, the column ‘NAME’ was planned as the Primary key
by the Programmer. Later a field ADMNO had to be set up as Primary key. Explain the reason.
2. Identify data type and size to be used for column ACTIVITYCODE in table ACTIVITY.
3. Write a query to display Activity Code along with the number of participants participating in each activity
(Activity Code wise) from the table Participant.
4. How many rows will be there in the Cartesian product of the two tables in consideration here?
5. To display Names of Participants, Activity Code, and Activity Name in alphabetic ascending order of
names of participants.
6. To display Names of Participants along with Activity Codes and Activity Names for only those
participants who are taking part in Activities that have ‘quiz’ in their Activity Names and Points of activity
are above 150.
[2] Consider the following tables SUPPLIER and ITEM and answer the questions
Table – Supplier
Table – Item
1. Which column should be set as the Primary key for SUPPLIER table ?
2. Mr. Vijay, the Database Manager feels that Email column will not be the right choice for Primary key.
State reason(s) why Email will not be the right choice.
3. Write the data type and size of INo column of ‘ITEM’ table.
4. To display names of Items, SNo and Names of Suppliers supplying those items for those suppliers who
have stores located in Naroda.
5. To display Names of Items, SNo, Price and Corresponding names of their suppliers of all the items in
ascending order of their Price.
6. To display Item Name wise, Minimum and Maximum Price of each item from the table item. i.e. display
IName, minimum price and maximum price for each IName.)
7. What will be the number of rows in the Cartesian product of the above two tables?
Table – Faculty
[4] Write commands in SQL for (1) to (4) and output for (5) and (6).
Table : Store
[7] Consider the following DEPT and EMPLOYEE tables. Write SQL queries for (1) to (4) and
find outputs for SQL queries (5) to (8).
Table:DEPT
10 AGRICULTURE ANAND
20 MINES NADIAD
30 TPP KHEDA
40 MECHANICAL AHMEDABAD
Table:EMP
1. To display Eno, Name, Gender from the table EMPLOYEE in ascending order of Eno.
2. To display the Name of all the MALE employees from the table EMPLOYEE.
3. To display the Eno and Name of those employees from the table EMPLOYEE who are born between
‘1997-01-01’ and ‘1999-12-01’.
4. To count and display FEMALE employees who have joined after ‘1999-01-01’.
5. SELECT COUNT(*),DCODE FROM EMPLOYEE GROUP BY DCODE HAVING COUNT(*)>1;
6. SELECT DISTINCT DEPARTMENT FROM DEPT;
7. SELECT NAME,DEPARTMENT FROM EMPLOYEE E,DEPT D WHERE E.DCODE=D.DCODE AND
ENO<1113
8. SELECT MAX(DOJ), MIN(DOB) FROM EMPLOYEE;
Most expected Questions interface of python with
MySQL
Most important MCQs Interface of Python with MySQL
[1] Alpa wants to establish a connection between MySQL database and Python. Which of the
following module except mysql.connector is used to fulfill her needs?
a) mysql.connect
b) pymysql
c) connect.mysql
d) connectmysql
[2] Krisha wants to connect her MySQL database with python. Suggest to her the method
which she can use after importing mysql.connector module?
a) connect()
b) connection()
c) connector()
d) join()
[3] Rishi has given few functions. He needs to extract a function that cannot be used to fetch
data from MySQL database which is connected with python. Assist him in selecting an
appropriate method.
a) Mycur.fetch()
b) Mycur.fetchone()
c) Mycur.fetchmany(n)
d) Mycur.fetchall()
[4] Kunjan has assigned a task to find the statement which is used to get the number of rows
fetched by execute method of the cursor. Assist him to find the same.
a) cursor.rowcount()
b) cursor.allrows()
c) cursor.rowscount()
d) cursor.countrows()
[5] Rearrange the steps for connecting MySQL database with python in the appropriate order.
a) i – ii – iii – iv – v
b) iv – ii – i – iii – v
c) v – i – iii – ii- iv
d) i – iii – v – ii – iv
[6] The connect method has few parameters. Which parameter is required to identify the name
of the database server?
a) host
b) localhost
c) dbserver
d) server
[7] A special control structure is used to do the processing of data row by row. This control
structure is
a) connection object
b) execute method
c) username and password
d) cursor object
a) import connector.mysql as cn
b) import MySQL.Connector as cn
c) import mysql.connector as cn
d) Import mysql.connectot AS cn
a) int object
b) connection object
c) list object
d) str object
[10] Observe the following code and select the correct statement with respect to create a
cursor object?
import mysql.connector as ms
cn=ms.connect(host="localhost",user='root',passwd='root',database='test')
cr=____________________
a) cn.cursor()
b) cn.Cursor()
c) cursor(cn)
d) Cursor(cn)
[11] Krupa has created connection between mysql database and python. Now she wants to
check the connection is properly established or not. Help her to select a proper function to
accomplish her task.
a) connected()
b) isConnected()
c) isconnected()
d) is_connected()
[12] Which function is used to perform DML or DDL operations on database in interface of
pyton with MySQL?
a) execute()
b) commit()
c) is_connected()
d) cursor()
[13] After completion of the work with interface of python with MySQL user need to clean up
the work environment. Which function is used to perform this task?
a) clear()
b) clean()
c) close()
d) destroy()
a) Only lists
b) Tuple of list
c) List of lists
d) List of tuples
[15] What will be returned by fetchone() method?
d) None of these
[16] State True or False: “The fetechone() method returns None if there are no more records in
database.”
[17] Which placeholder is required to be placed for string parameters in string template while
writing query to exdcute() method?
a) str
b) %s
c) %str
d) %string
d) None of these
[19] When fetchone() method is used, the cursor moves to ____________ record immediately
after getting the specified row.
a) next record
c) first record
d) previous record
[20] A string template refers to
i) MySQL Command
a) i) and ii)
b) i and iii)
[21] After executing the insert, update, or delete statement you must use which of the
following function?
a) commit()
b) save()
c) update()
d) store()
[5] Prakash has installed mysql connector. Now he wants to check whether its properly
installed or not. Suggest python command to do this task.
[11] Neel is trying to write the connect method. Help him by filling the given gaps:
import ____________ as ms
cn=ms.________(host=localhost,user='root',passwd='root',database='school')
cr=cn._____()
cn.______()
cn=mysql.connector.connect(_______=localhost,________='root',________='root',______='school')
[13] Babita wants to insert a record into the table using a python MySQL connector. Suggest
two methods that are used to execute the query using the cursor object.
[14] What are the methods used to read data from SQL tables?
import mysql.connector as ms
cn=ms.connect(host='localhost',user='root',passwd='root',database='IPL')
cr=cn.cursor()
r=cr.fetchone()
r=cr.fetchone()
r=cr.fetchone()
data=int(r[2])
print(data*2)
[18] Consider the table given in the above question and write the for this code snippet:
import mysql.connector as ms
cn=ms.connect(host='localhost',user='root',passwd='root',database='IPL')
cr=cn.cursor()
r=cr.fetchone()
r=cr.fetchmany(2)
[19] Consider the tabe given in question no. 17 and write python code to display the top 3 run-
scorer.
[20] Consider the table given in question 17 and write python code to display details for those
batsmen who score less than 500 runs.
[22] Write python code to update short team name GT to full team name Gujarat Titans.
• Username is root
• Password is root
• Database name – Transport
cn=msql.___________(_______,________,________,_______) #Statement 2
if cn.__________: # Statement 3
print("Successfully Connected...")
else:
[25] Consider the database and parameters given in [24] and complete the code below given partial
code of fetching records having vehicles model after 2010.
con1=mysql.connect(host="localhost",
user="root",
password="root",
database="Transport")
_______________ #Statement 1
_______________________ #Statement 2
print(rec)
[26] Consider the following facts for connecting an interface of python with MySQL and complete the
given partial code given for inserting a record into the database table:
• Username is root
• Password is root
• The table exists in a “school” database.
• The details (RollNo, Name, Standard, and Marks) are to be accepted by the user.
import mysql.connector as mysql
con1=mysql.connect(host="localhost",
user="root",
password="root",
database="school")
mycursor = con1.cursor()
querry=________________________________ #Statement 1
______________________ #Statement 2
______________________ # Statement 3
con1.close()
Best Wishes