Looking for Class 12 Computer Science most expected questions? Get chapter-wise important Python, DBMS, File Handling and Networking questions for CBSE 2026 board exam preparation. Here we go!
Topics Covered
Class 12 Computer Science Most Expected Questions
If you are preparing for the CBSE board exam, this collection of Class 12 Computer Science most expected questions will help you score high marks. These questions are carefully selected from previous year trends, important topics, and exam patterns.
This article includes chapter-wise important questions from Python, File Handling, Data Structures, DBMS, and Computer Networks for quick revision before the board exam.
Let us see the most expected questions computer science class 12 asked for 1, 2 and 3 marks questions.
Class 12 Computer Science Most Expected Questions Python revision tour
Let us start with python revision tour questions.
Python Revision Tour – MCQs\1 marks Questions
[1] State True or False – ‘Tuple is one of the datatypes of python having data in key-value pair.”
Ans. False
Correct Statement: Tuple is one of the datatypes of python having collection of data.
[2] State True or False “Python has a set of keywords that can also be used to declare variables.”
Ans.: False
Correct Statement: Python keywords are reserved words but cannot be used to decare variables.
[3] Which of the following is not a valid python operator?
a) %
b) in
c) #
d) **
Ans.: c) #
Explanation: # symbol is used to write a single line comment in python where % and ** is arithmatic operator where as in is membership operator.
[4] What will be the output of the following python expression?
print(2**3**2)
a) 64
b) 256
c) 512
d) 32
Ans.: c) 512
Explanation: As per execution from the statement 3**2 – 9 and 2**9 is 512
[5] Which of the following is not a keyword?
a) eval
b) nonlocal
c) assert
d) pass
Ans. : a) eval
Explanation: eval is a function rest all three are keywords.
[6] Observe the given dictionary:
d_std={“Roll_No”:53,”Name”:’Ajay Patel’}
d_marks={“Physics”:84,”Chemistry”:85}
Which of the following statement will combine both dictionaries?
a) d_std + d_marks
b) d_std.merge(d_marks)
c) d_std.add(d_marks)
d) d_std.update(d_marks)
Ans. d) d_std.update(d_marks)
Explanation: The + concates immutable objects as well as merge and add functions cannot be used for combine dictionary.
[7] What will be the output of the following python dictionary operation?
data = {‘A’:2000, ‘B’:2500, ‘C’:3000, ‘A’:4000}
print(data)
a) {‘A’:2000, ‘B’:2500, ‘C’:3000, ‘A’:4000}
b) {‘A’:2000, ‘B’:2500, ‘C’:3000}
c) {‘A’:4000, ‘B’:2500, ‘C’:3000}
d) It will generate an error
Ans.: c) {‘A’:4000,’B’:2500,’C’:3000}
Explanation: When a key is repated in dictionary declaration the latest key value is considered for repeated key.
[8] What will be the output for the following expression:
not ((False and True or True) and True)
a) True
b) False
c) None
d) Null
Ans. : b) False
Explanation:
not((False and True or True) and True)
not((False or True) and True)
not(True and True)
not True
False
[9] What will be the output for the following expression:
print(True or not True and False)
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
Ans. b) True
Explanation:
True or not True and False
True or False and False
True or False
True
[10] What will be the output of the given code?
s=’CSTutorial@TutorialAICSIP’
o=s.partition(‘Tutorial’)
print(o[0]+o[2])
a) CSTutorial
b) CSTutorialAICSIP
c) CS@TutorialAICSIP
d)Tutorial@TutorialAICSIP
Ans. c) CS@TutorialAICSIP
Explanation:
The s.partition(‘Tutorial’) will return tuple as – (‘CS’, ‘Tutorial’, ‘@TutorialAICSIP’)
Then o[0] return – CS and o[2] return TutorialAICSIP
[11] Select the correct output of the following python code:
str=”My program is program for you”
t = str.split(“program”)
print(t)
a) [‘My ‘, ‘ is ‘, ‘ for you’]
b) [‘My ‘, ‘ for you’]
c) [‘My’,’ is’]
d) [‘My’]
Ans.: a) [‘My’,’ is’,’ for you’]
Explanation: The split method will separate the string from given word.
[12] Which of the following operations on a string will generate an error?
a) “PYTHON”*2
b) “PYTHON” + “10”
c) “PYTHON” + 10
d) “PYTHON” + “PYTHON”
Ans.: c) “Python” + 10
Explanation: For string concatenation both operands should be string only. A string and number is invalid combination.
[13] Kevin has written the following code:
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
Ans.: c) S3
Explanation: The tuple is assigned as value for the key salary which is immutable.
[14] What will be the output of following expression in python?
print ( round (100.0 / 4 + (3 + 2.55) , 1 ) )
a) 30.0
b) 30.5
c) 30.6
d) 30.1
Ans.: c) 30.6
Explanation: The expressio will be executed in this manner:
(100.0/4+(3+2.55)
(100.0/4+5.55)
25.0+5.55
30.55 will round up to 1 digit i.e. 30.6
[15] Consider this statement: subject=’Computer’ + ‘ ’ + ‘Science 083’
Assertion(A): The output of statement is – “Computer Science 083”
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
(D) A is false but R is True
Ans.: (A) Both A and R are true and R is the correct explanaton for A
Watch this video for more understanding:
[16] Fill in the Blank:
The explicit ___________________ of an operand to a specific type is called type casting.
a) Conversion
b) Declaration
c) Calling of Function
d) Function Header
Ans.:a) Conversion
Explanation: Declaration is used to declare variables it does not convert any datatype, Calling function and function header will be not relevant options related to types casting here.
[17] Which of the following is not a core data type in Python?
a) Boolean
b) integers
c) strings
d) Class
Ans.: d) Class
Explanation: Core data types in python are boolean, integers and string.
[18] What will the following code do?
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
b) It will throw an error and the dictionary cannot be updated
c) It will make the content of the dictionary as dict={“Exam”:”AISSCE”, “Year”:2023}
d) It will throw an error and dictionary and do nothing
Ans.: c) It will make the content of the dictionary as dict={“Exam”:”AISSCE”, “Year”:2023}
Explanation: The update() function will make changes to the old dictionary and produce the new dictionary as values specified with update.
[19] What will be the value of the expression :
4+3%5
a) 2
b) 6
c) 0
d) 7
Ans.: d) 7
Explanation: In this expression 3%5 will execute first. So the value is 3 only then 4 + 3=7.
[20] Select the correct output of the code:
a= "Year 2022 at All the best"
a = a.split('2')
b = a[0] + ". " + a[1] + ". " + a[3]
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
Ans.: a) Year . 0. at All the best
Explanation: The split() function will split text from the specified digit 2.
a.split(‘2’) = [‘Year ‘, ‘0’, ”, ‘ at All the best’]
Now a[0] = ‘Year ‘
The “.” will be concatenated to the string as “Year .”
and finally a[3] = ‘ at All the best’ will be also added.
[21] 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[0]= '@' # Statement 4
S=S+"Thank you" # Statement 5
a) Statement 3
b) Statement 4
c) Statement 5
d) Statement 4 and 5
Ans. b) Statement 4
Explanation: String is immutable object of python, Hence it does not allow this operation. Rest all statements are correct.
[22] State true or false:
“A dictionary key must be of a data type that is mutable”.
Ans.: False
Explanation: Dictionary values are accessed through the keys itself and it uses a hash value which is associated with unique key. Hence it must be immutable.
[23] What will be the data type of p, if p=(15)?
a) int
b) tuple
c) list
d) set
Ans.: a) int
Explanation: p stores only single number in paranthesis. Parantehsis with comma becomes tuple, but only single number represents int in python.
[24] Which of the following is a valid identifier in python?
a) else_if
b) for
c) pass
d) 2count
Ans. a) else_if
Explanation: for and pass keywords in python and 2count is statrted with a digit which is viaolation of python variable naming convetion rule.
[25] Consider the given expression:
‘5’ or 4 and 10 and ‘bye’
Which of the following will be the correct output if the given expression is evaluated?
a) True
b) False
c)’5’
d)’bye’
Ans. c) ‘5’
Explanation: The expression is evaluated in this manner:
10 and ‘bye’ returns ‘bye’
4 and ‘bye’ returns ‘bye’
‘5’ or ‘bye’ returns ‘5’
[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’]#
Ans.: c) [‘c’]#[‘s’]#[‘1’]#[‘2’]#
Explanation:
C – [c.lower()], end=’#’ – [‘c’]#
S – [s.lower()],end=’#’ – [‘s’]#
1 and 2 remains same as [‘1’]#[‘2’]#
[27] Which of the following Statement(s) would give an error after executing the following code?
d={"A":1, "B": 2, "C":3, "D":4} #Statement 1
sum_keys =0 #Statement 2
for val in d.keys(): #Statement 3
sum_keys=sum_keys+ val #Statement 4
print(sum_keys)
a) Statement 2
b) Statement 4
c) Statement 1
d) Statement 3
Ans. b) Statement 4
[28] What will the following expression be evaluated to in Python?
print(25//4 +3**1**2*2)
a) 24
b)18
c) 6
d) 12
Ans.: d) 12
Explanation: First ** operator will execute from right to left
So 1**2 = 1
Then 3**1=3
Now the expression is 25//4+3*2.
So 6+3*2 = 6 + 6 = 12.
[29] What will be the output of the following expression?
24//6%3 , 24//4//2 , 48//3//4
a) (1,3,4)
b) (0,3,4)
c) (1,12,Error)
d) (1,3,#error)
Ans. a) (1,3,4)
Explanation:
Exp1- 24//6%3 = 4%3 = 1
Exp2 – 24//4//2 = 6//2 = 3
Exp3 – 48//3//4 = 16//4 = 4
[30] What will the following expression be evaluated to in Python?
print(23 + (5 + 6)**(1 + 1))
(a) 529
(b) 144
(c) 121
(d) 1936
Ans. b) 144
Explanation:
Bracket off – 11**2 = 121
Now 23+121 =144
Watch this video for more understanding:
Python Revision Tour – 2 Marks Questions
1. a) Given is a Python string declaration:
message='FirstPreBoardExam@2022-23'
Write the output of: print(message[ : : -3].upper())
b) Write the output of the code given below
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 | 2 | – | 2 | 3 |
| -25 | -24 | -23 | -22 | -21 | -20 | -19 | -18 | -17 | -16 | -15 | -14 | -13 | -12 | -11 | -10 | -9 | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
| F | S | R | O | D | A | 2 | 2 | 3 |
b)
Steps:
d2={‘name’:’Rajveer’, ‘age’:17,’class’:’XII-A’,’rno’:21, ‘rno’:21}
Now, d.keys() will return – dict_keys([‘name’,’age’,’class’,’rno’])
a) 322ADORSF
b) dict_keys(['name', 'age', 'class', 'rno'])
2. Predict the output of the following code:
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 |
| 1 | i=1 t=t+i t=0+1=1 a=””+”P”+”@”=P@ ad=0+10=10 |
| 2 | i=3 t=1+3=4 a=’P@’+’Q’+’@’=P@Q@ ad=10+30=40 |
| 3 | i=5 t=4+5=9 a=’P@Q@’+’R’+’@’ ad=40+50=90 |
| 4 | For Loop Ends |
9 90 P@Q@R@
3. Predict the output of the given code:
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 |
| 1 | i=1 t=(22,44) Lst=[(22,44)] |
| 2 | Condition False |
| 3 | i=3 t=(44,88) Lst=[(22,44),(44,88)] |
| 4 | Condition False |
| 5 | For loop Ends |
[(22, 44), (44, 88)]
4. a) What will be the output of the following string operation?
str="PYTHON@LANGUAGE"
print(str[2:12:2])
b) Write the output of the following code.
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 |
| 1 | x=11 x=x+10=21 |
| 2 | x=97 x=x+10=97+10=107 |
| 3 | x=12 x=x+10=12+10=22 |
| 4 | X=98 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)
((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.
6. Predict the output
s="ComputerScience23"
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)
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##
7. a) Given is a Python List declaration:
lst1=[39,45,23,15,25,60]
What will be the output of print(Ist1.index(15)+2)?
b) Write the output ot the code given below:
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
8. Predict the output of the python code given below:
st= "python programming"
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
5
9. Predict the output:
myvalue=["A", 40, "B", 60, "C", 20]
alpha =0
beta = ""
gama = 0
for i in range(1,6,2):
alpha +=i
beta +=myvalue[i-1]+ "#"
gama +=myvalue[i]
print(alpha, beta, gama)
Ans.: Steps are same as question 2.
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.:
Num=int(input("Number:")) #rawinput changed to input
sum=0
for i in range(10,Num,3):#Colon is missing to the end
sum+=1
if i%2==0:#equal sign is missing
print(i*2)
else:
print(i*3)
print(Sum) # Inentation and S of sum should be small
Watch this video for more understanding:
Watch the video Short answer questions
Computer Science Class 12
2 marks questions Python Revision Tour
Working with Functions Questions
In this topic, we are going to discuss the questions from the topic functions. Let us begin!
Working with Python Functions 2 marks Questions
From this topic working with functions output-based and error-based questions will be asked in 2 marks. So let us discuss working with python functions 2 marks questions. Here we go!
[1] Predict the output of the following python code:
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
num=int( input(“ Enter a number to check :"))
k=checkNumber(num)
if k = 0:
print(“This is EVEN number”)
else
print(“This is ODD number”)
Ans.:
def checkNumber(N):
status = N%2
return status
#main-code
num=int( input(“ Enter a number to check :"))
k=checkNumber(num)
if k == 0:
print(“This is EVEN number”)
else:
print(“This is ODD number”)
[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
While num > 0:
rem == num %10
rev = rev*10 + rem
num = num/10
return rev
print(reverse(1234))
Ans.:
def reverse(num):
rev = 0
while num > 0:
rem = num %10
rev = rev*10 + rem
num = num//10
return rev
print(reverse(1234))
[4] Predict the output for following code:
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
[5] Predict the output of the following python code:
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']
The output is:
['F','U','N']['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):
total=arg1+arg2 #Semicolon not required
print(”Total:”,total)
return total #Any one statement is enough either return or print
total=sum(10,20)#total variable needs to be call a function
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:
def func( a, b=2, c=5):
# definition of function func( )
here b and c are default arguments
[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:
def CalculateInterest (Principal, Rate=.06,Time):
# 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
While num1 % num2 = 0
num1+=20
num2+=30
Else:
print('hello')
Ans.:
def F1():
num1,num2 = 10, value is missing
while num1 % num2 == 0:
num1+=20
num2+=30
else:
print('hello')
[10] Predict the output of the following code fragment:
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.:
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
Answer:
250#150
250#100
130#100
130#100
Watch this video for more understanding:
List and Functions 3 Marks important questions Computer Science Class 12
[1] Write a function ThreeLetters(L), where L is the list of elements (list of words) passed as an argument to the function. The function returns another list named ‘l3’ that stores all three letter words along with its index.
For example:
If L contains [“RAJ”, “ANKIT”, “YUG”, “SHAAN”, “HET”]
The list l3 will have [“RAJ”,0,”YUG”,2,”HET”,4]
Support your answer with a function call statement.
Ans.:
[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:
If list L contains [25000,15130,10135,12146,15030]
Then the modifySal(lst) should make the list L as [25750,15584,10135,12146,15030]
Write a proper call statement for the function.
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]
The new list will have – [0,3,5]
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.
Sample input data of the list
Numlist= [23, 28, 31, 85, 69, 60, 71], n=3
Output Numlist-[85, 69, 60, 71, 23, 28, 31]
def LeftShift(li,n):
li[:]=li[n:]+li[:n]
return li
aList=[23, 28, 31, 85, 69, 60, 71]
n=int(input("Enter value to shift left:"))
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]
The SList will have – [8,27,125,64]
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:
if the list contains [10,8,13,11,4] then
The rearranged list is as [2.5,2,39,33,1]
Ans.:
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:
If the list initially contains [79,56,23,28,98,99]
then after reversal the list should contain [99,98,28,23,56,79]
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.
Sample Input Data 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]
for i in range(L//2, L):
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]
print("List before Swap:",l)
Swap50_50(l)
print("List after swap:",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 Computer Science Class 12
In this section of Most expected questions Computer Science we are going to cover the most important questions from File handling concepts for Computer Science Class 12. Here we go!
File handling MCQs/1M questions
Follow the given link for 1 marks questions of file handling computer science class 12.
| Topic | Article |
| 40+ questions based on text file | Explore Now |
| 25+ questions based on binary file | Explore Now |
| 40+ questions based on CSV file | Explore Now |
| Previous year Board questions | Watch Now Video 1 | Video 2 |
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
print('Total number of vowels are : ', c)
[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:
For the fie content:
A man always wants to strive higher in his life
He wants to be perfect.
The output after executing displayword() will be:
Always wants strive higher life wants perfect
Ans.:
def displaywords():
f= open('data.txt','r')
s= f.read()
lst = s.split()
for x in lst:
if len(x)>3:
print(x, end=" ")
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:
If file content is as follows:
INDIA is my country.
I live in India, India is best.
India has many states.
The function should return :
Frequency of India in Line 1 is: 1
Frequency of India in Line 2 is: 2
Frequency of India in Line 3 is: 1
Ans.:
def countINDIA():
f=open("myfile.txt")
lines=f.readlines()
for line in range(len(lines)):
c=0
w=lines[line].split()
for i in w:
if i.lower()=='india':
c+=1
print("Frequency of India in Line ",line+1," is:",c)
countINDIA()
[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
print("Word found ", c , " times")
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()
print("Words starting with t are:",c)
Data File Handling 4 Marks Questions
[1] Priya of class 12 is writing a program to create a CSV file “clients.csv”. She has written the following code to read the content of file clients.csv and display the clients’ record whose name begins with “A‟ and also count as well as show no. of clients with the first letter “A‟ out of total records. As a programmer, help her to successfully execute the given task.
Consider the following CSV file (clients.csv):
| 1 | Aditya | 2021 |
| 2 | Arjun | 2018 |
| 3 | Aryan | 2016 |
| 4 | Sagar | 2022 |
Code:
import _____ # Line-1
def client_names():
with open(______) as csvfile: # Line-2
myreader = csv.___ (csvfile, delimiter=",") # Line-3
count_rec=0
count_s=0
for row in myreader:
if row[1][0].lower() == "s":
print(row[0],",",row[1],",",row[2])
count_s += 1
count_rec += 1
print(count_rec, count_s)
Read the questions given below and fill in the gaps accordingly: 1 + 1 + 2
- State the module name required to be written in Line-1.
- Mention the name of the mode in which she should open a file.
- Fill in the gaps for given statements – Line-2 and Line-3.
Ans.:
1. csv
2. r mode
3. Line 2 – “client.csv”,”r”
Line 3 – reader
[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:
import _______ #Statement 1
def find_records():
r=int(input('Enter roll no of student to be searched'))
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:
print('Record not exist')
Help Arpan to answer the following questions to fill in the given gaps: 1 + 1 + 2
- Which module should be imported into the program? (Statement1)
- Write the correct statement required to open a file school.dat in the required mode (Statement 2)
- Which statement should Arpan fill in Statement 3 for reading data from the binary file school.dat? Also, Write the correct comparison to check the existence of the record (Statement 4).
Ans.:
1. pickle
2. school.dat,”rb”
3. pickle.load(f)
rec[0]
[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:
- GetPatients() to create a binary file called PATIENT.DAT containing student information – case number, name, and charges of each patient.
- 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:
case_no = int(input("Case No.:"))
pname = input("Name : ")
charges = float(input("Charges :"))
l = [case_no, pname, charges]
pickle.dump(l,f)
Choice = input("enter more (y/n): ")
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]
if R[2] > 8000:
print(R[1], " has charges =",R[2])
more_8k+=1
except:
break
try:
print("average percent of class = ",total/more_8k)
except ZeroDivisionError:
print("No patient found with amount more than 8000")
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.
- 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("emprecords.dat","rb")
fout=open("_____________") #Statement2
found=False
eid=int(input("Enter employee id to update 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:
print("No employee with such id is found")
fin.close()
fout.close()
Write answers for the following: (1 + 1 + 2)
- Which module should be imported in the program? (Statement 1)
- Write the correct statement required to open a temporary file named temp.dat. (Statement2)
- Which statement should Mitul fill in Statement 3 to read the data from the binary file, emprecords.dat, and in Statement 4 to write the updated data in the file, temp.dat?
Ans.:
1. pickle
2, “temp.dat”,”ab”
3. “emprecords.dat”,”rb”
pickle.dump(rec,fout)
[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.
import ___________ #Statement 1
tr = ['BookID','Title','Publisher']
dt = [['1', 'Computer Science','NCERT'],['2','Informatics Practices','NCERT'],['3','Artificial Intelligence','CBSE']]
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)
top_row = _______________ #Statement 3
print(top_row)
for i in _________: #Statement 4
if i[2]=='NCERT':
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.
Ans.:
1. csv
2. csvwriter.writerows(dt)
3. next(csvreader)
4. csvreader
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!
Data File Handling 5 Marks Questions
[1] 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) 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.:
Advantages of a csv file:
- It is human readable – can be opened in Excel and Notepad applications
- It is just like text file
- It is common structure file can be opened by notepad, spreadsheet software like MS Excel and MS word also
- Easy to process data in tabular form
(i) Code for Function insert():
import csv
def insert():
f=open('apps.csv','a',newline='')
app_id=int(input("Enter App ID:"))
app_name=input("Enter Name of App:")
model=input("Enter Model:")
company=input("Enter Company:")
downloads=int(input("Enter no. downloads in thousands:"))
l=[app_id,app_name,model,company,downloads]
wo=csv.writer(f)
wo.writerow(l)
f.close()
(ii) Code for no_of_records()
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.:
| Binary File | CSV File |
| The binary file contains data in 0s and 1s form | CSV file contains data in tabular form |
| It is saved by .bin or .dat extension | It is saved by .csv extension |
| It must be created by a python program only | It can be created by notepad or spreadsheet |
| It is not a humanly readable file | It is a humanly readable file |
Code for function add():
def add():
f=open('emp.csv','a',newline='')
empid=int(input("Enter employee ID:"))
empname=input("Enter Employee Name:")
sal=float(input("Enter Salary:"))
l=[empid,empname,sal]
wo=csv.writer(f)
wo.writerow(l)
f.close()
Code for function search()
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.
Code is similar as question 1, do yourself.
[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.:
| Text File | CSV File |
| It represents data into ASCII format. | It represents data into ASCII form and in tabular form. |
Code for add():
def add():
f=open('furdata.csv','a',newline='')
fid=int(input("Enter furniture ID:"))
fname=input("Enter furniture Name:")
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:
if i[1].lower()=='sofa' and float(i[2])>12000:
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.
import ___________ #Line1
def addCsvFile(user, pwd):
f=open('user.csv','_') #Line2
w=csv.writer(f)
w.writerow([UserName,Password])
f.close( )
csv file reading code
def readCsvFile(): #to read data from CSV file
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
- What module should be imported in #Line1 for successful execution of the program?
- In which mode file should be opened to work with user.csv file in#Line2
- Fill in the blank in #Line3 to read data from csv file
- Fill in the blank in #Line4 to close the file
- Write the output he will obtain while executing Line5
Ans.:
- csv
- ‘a’
- reader
- close
- Output:
['Aditya'.'987@555']
['Archi','arc@maj']
['Krish','Krisha@Patel']
Watch video for more understanding:
Data Structure Stack questions
The first topic we are going to cover is Data Structure Stack. Here we go!
1 mark objective types questions data structure stack class 12 computer science
[1] Kunj wants to remove an element from empty stack. Which of the following term is related to this?
a) Empty Stack
b) Overflow
c) Underflow
d) Clear Stack
Ans. c) Underflow
[2] ____________ is an effective and reliable way to represent, store, organize and manage data in systematic way.
Ans. Data Structure
[3] Which of the following is elementary representation of data in computers?
a) Information
b) Data
c) Data Structure
d) Abstract Data
Ans. b) Data
[4] ____________ represents single unit of certain type.
a) Data item
b) Data Structure
c) Raw Data
d) None of these
Ans. : a) Data Item
[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) Only Statement A is True
b) Only Statement B is True
c) Both are True
d) Both are False
Ans. c) Both are True
[6] Which of the following python built in type is mostly suitable to implement stack?
a) dictionary
b) set
c) tuple
d) list
Ans.: d) list
[7] The Data Structures can be classified into which of the following two types?
a) Stack and Queue
b) List and Dictionary
c) Simple and Compund Data Structure
d) Easy and Comoplex Data Structure
Ans. b) Page Style
[8] Identify Data Structure from the given facts:
- I am single level data strcuture.
- My elements are formed from a sequence.
a) Linear Data Structure
b) Non-Linear Data Structure
c) Dynamic Data Structure
d) Static Data Structure
Ans. : a) Linear Data Structure
[9] Which of the following is an example of non-linear data structure?
a) Stack
b) Queue
c) Linked List
d) Tree
Ans.: 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
Ans. 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
Ans. : a) Stack
[12] Which of the following is an example of stack?
a) Students standing in Assembly
b) People standing railway ticket window
c) Chairs arranged in a vertical pile
d) Cars standing on the road on traffic signal
Ans. c) Chairs arranged in a vertical pile
[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
Ans. a) push
[14] Which of the folloiwng operation is considered as deletion of element from stack?
a) push
b) pop
c) underflow
d) overflow
Ans. b) pop
[15] Which of the following pointer is very essential in stack operations?
a) front
b) top
c) middle
d) bottom
Ans. b) top
[16] The fixed length data structure is known as _____________
a) dynamic data stcuture
b) fixed length data structure
c) static data stucture
d) intact data structure
Ans. c) static data structure
[17] __________ refers to insepecting an element of stack without removing it.
a) push
b) pop
c) peek
d) underflow
Ans. c) peek
[18] Consider the following data:
[11,20,45,67,23]
The following operations performed on these:
push(19)
pop()
push(24)
pus(42)
pop()
push(3)
What will be the contents of the list evelntually?
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]
[19] The LIFO structure can be also same as ______________
a) FILO
b) FIFO
c) FOFI
d) LOFI
Ans.: a) FILO
[20] Consider the folloiwing data structure implemented a list as stack:
11
22
23
34
91
Which of the following is function is executed thrice to get this result:
34
91
a) delete()
b) pop()
c) remove()
d) clear()
Ans. b) pop()
Most expected 2 marks questions Stack Computer Science Class 12
[1] What is Stack? Write any one application of Stack?
Ans.: Stack is a linear data strcuture that allows to add or remove an element from top. It follows LIFO (Last In First Out) principle. The applications of stack are as follows:
1. Pile of clothes in almirah
2. Multiple chairs in a verticale pile
3. Bangles on girl’s wrist
4. Phone call logs
5. Web browsing history
6. Undo & Redo commands in text editors
7. Tubewell boring machine
[2] List out any two real-life examples of Stack.
Ans.:
1. Pile of dinner plates
2. Pile of chairs
3. Tennis balls in their container
4. CD and DVD holder
5. The forward and backword button in media player
[3] Define stack. What is the significance of TOP in stack?
Ans.: The definition of stack is given in question 1.
The TOP is the pointer in stack which allows to add and remove element from one side.
[4] Give any two characteristics of stacks.
Ans.:
1. Stack is a linear data structure.
2. The tasks performed on stack are : push, pop, peep, and change
3. The insertion and deletion performed on stack from one end only i.e top
4. Stack is implemented in python through lists
5. It follows LIFO principle
6. When the stack is having limited elements and all elements are filled this conidtion is known as stack overflow
7. When there is no element or elments are removed gradually and the stack becomes empty is known as stack underflow.
[5] What do you mean by push and pop operations on stack?
Ans.
1. Push operation refers to inserting element in the stack.
2. Pop operation refers to deleting element from the stack.
[6] What is LIFO data structure? Give any two applications of a stack?
Ans.:
LIFO stands for Last In First Out. It is a principle of data structure where the way of insertion and deletion is defined by orrucence of each element.
Refer Question 1 for applications of a stack.
[7] Name any two linear Data Structures? What do you understand by the term LIFO?
Ans.: Linear data structure refers to a data structure in which elements are organised in a sequence.
The term LIFO is explained in the above question.
[8] Name four basic operations performed on stack.
Ans.: Some basic operations perform on stack are:
1. push: Inserting element in stack
2. pop: Deleting element from stack
3. peep: Accessing the top element
4. change: Changing the value of top element
[9] Why stack is called LIFO data structure?
Ans. Stack is called LIFO structure because it allows to insert and delete an element from top where the last element is always on top. While removing this top element is removed first.
[10] What do you mean by underflow in the context of stack?
Ans. Underflow refers to condition in data structure operations while deleting elements. While deleting elements gradually elements are deleted and the list becomes empty. This situation is know as underflow.
[11] Consider STACK=[23,45,67,89,51]. Write the STACK content after each operations:
- STACK.pop( )
- STACK.append(99)
- STACK.append(87)
- STACK.pop( )
Ans.
1. STACK = [23,45,67,89]
2. STACK = [23,45,67,89,99]
3. STACK = [23,45,67,89,99,87]
4. STACK = [23,45,67,89,99]
[12] Differentiate between list and stack.
Ans.
Stack:
1. A stack is a data structure.
2. Stacks uses LIFO principle
3. In stack element only be inserted or deleted from top potision
4. Stack has dynamic size
5. It allows to use only linear search
List:
1. A list is a collection of items or data values
2. List uses index position
3. In lists elements can be inserted or deleted any indexes
4. List has fixed size
5. List allows linear and binary search
[13] Differentiate between push and pop in stacks.
Ans.
Push:
1. Inserting an element into the stack is known as Push
2. Stack is dynamic in size but when fixed size stack are used, overflow condition will occur
3. The top pointer increases when element is pushed
Pop:
1. Deleting an element into the stack is known as Pop
2. Underflow condition will occur when stack becomes empty while removing an elements
3. The top pointer decreases when element is popped
[14] Write an algorithm for pop operation in stack.
Ans.:
Step 1: Start
Step 2: If top=-1 go to step 3 else go to step 4
Step 3: Print “Stack is underflow” and go to step 7
Step 4: Delete item = Stack[top]
Step 5: Decrement top by 1
Step 6: Print “Item Popped”
Step 7: Stop
[15] Write an algorithm for push operation in stack.
Ans.
Step 1: Start
Step 2: top=-1
Step 3: Input new element
Step 4: Increment top by 1
Step 5: stack[top] = new element
Step 6: Print “Item Pushed”
Step 7: Stop
Watch this video for more understanding:
If you are looking for notes on stack data structure, click on this link:
Follow this link for more questions:
Most expected 3 marks Stack Programming questions computer science
- Write a function push (student) and pop (student) to add a new student name and remove a student name from a list student, considering them to act as PUSH and POP operations of stack Data Structure in Python.
Ans.:
def push(student):
name=input("Enter student name:")
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.
For example: If the sample content of the dictionary is as follows:
R={“OM”:35,”JAI”:40,”BOB”:53,”ALI”:66,”ANU”:19}
The output from the program should be:
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.
- Traverse the content of the list and push the odd numbers into a stack.
- Pop and display the content of the stack.
For Example:
If the sample Content of the list is as follows:
N=[79,98,22,35,38]
Sample Output of the code should be:
35,79
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
6. Write a function in Python POP_OUT(Stk), where Stk is a stack implemented by a list of numbers. The function returns the value which is deleted/popped from the stack.
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:
- Push the keys (name of the student) of the dictionary into a stack, where the corresponding value (marks) is greater than 75.
- Pop and display the content of the stack.
For example:
If the sample content of the dictionary is as follows:
R={“OM”:76, “JAI”:45, “BOB”:89, “ALI”:65, “ANU”:90, “TOM”:82}
The output from the program should be: TOM ANU BOB OM
R={"OM":76, "JAI":45, "BOB":89, "ALI":65, "ANU":90, "TOM":82}
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:
- Push the keys (employee name) of the dictionary into a stack, where the corresponding value (salary) is less than 85000.
- Pop and display the content of the stack.
For example:
If the sample content of the dictionary is as follows:
Emp={“Ajay”:76000, “Jyothi”:150000, “David”:89000, “Remya”:65000, “Karthika”:90000, “Vijay”:82000}
The output from the program should be:
Vijay Remya Ajay
Emp={"Ajay":76000, "Jyothi":150000, "David":89000, "Remya":65000, "Karthika":90000, "Vijay":82000}
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.
- Traverse the content of the list and push the negative temperatures into a stack.
- Pop and display the content of the stack.
For Example:
If the sample Content of the list is as follows:
T=[-9, 3, 31, -6, 12, 19, -2, 15, -5, 38]
Sample Output of the code should be: -5 -2 -6 -9
T= [-9, 3, 31, -6, 12, 19, -2, 15, -5, 38]
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!=[]:
print(Pop(s),end = " ")
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.
- DoPush(elt) to insert only prime numbers onto the stack.
- DoPop() to pop and display content of the stack.
For eg:if L=[2.5,6,11,18,24,32,37,42,47] then stack content will be 2 5 11 37 47
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.
- Push the keys (IDs) of the dictionary into the stack, if the corresponding marks is >50
- Pop and display the content of the stack
For eg:if D={2000:58,2001:45,2002:55,2003:40} Then output will be: 2000,2002
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):
name=input("Enter Name of 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:
- 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.
- Pop and display the content of the stack.
For example
If the sample content of the dictionary is as follows:
RO={“AJMER”:185, “Panchkula”:95, “Delhi”:207, “Guwahati”:87, “Bubaneshwar”:189}
The output from the program should be:
AJMER DELHI BHUBANESHWAR
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.
For example: If Reva has created the dictionary is as follows:
Product={“TV”:10000, “MOBILE”:4500, “PC”:12500, “FURNITURE”:5500}
The output from the program should be: [ ‘FURNITURE’, ‘MOBILE’]
Do Yourself…
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:
- Input the Book No, BookName and BookPrice from the user and Push into the stack.
- Display the status of stack after each insertion.
def Push():
books=[]
stk=[]
bno=int(input("Enter Book Number:"))
bname=input("Enter Book Name:")
bprice=input("Enter Book Price:")
books=[bno,bname,bprice]
stk.append(books)
print(stk)
18. Write a function in Python PUSH(mydict),where mydict is a dictionary of phonebook(name and mobile numbers), from this dictionary push only phone numbers having last digit is greater than or equal to 5 to a stack implemented by using list. Write function POP() to pop and DISPLAY() to display the contents.
if it has at least one element, otherwise display “stack empty” message.
>>> mydict={9446789123:”Ram”,8889912345:”Sam”,7789012367:”Sree”}
>>> push(mydict)
Phone number: 9446789123 last digit is less than five which can’t be pushed
Stack elements after push operation : [7789012367, 8889912345]
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.
For example: L = [‘Satish’,’Manish’,’Sagar’,’Vipul’]
Output will be: Satish Sagar
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…
Watch this video for practical understanding.
In the next section of Most expected questions Computer Science, I am going to discuss questions from unit 2 computer networks.
Most expected questions Unit II Computer Networks Computer Science Class 12
So let us discuss the most expected questions from Unit II Computer Networks for Computer Science Class 12. From this unit 1, 2, 3, 4, and 5 marks are going to be asked in your board exams. So here we go!
1 mark Unit 2 Computer Networks most expected questions computer science class 12
- ……………………………. is a network of physical objects embedded with electronics, software, sensors and network connectivity.
- ……………….. is a device that forwards data packets along networks.
- ———————- describes the maximum data transfer rate of a network or Internet connection.
- It is an internet service for sending written messages electronically from one computer to another. Write the service name.
- As a citizen of india , What advise you should give to others for e-waste disposal?
- Name the protocol that is used to send emails.
- Your friend Ranjana complaints that somebody has created a fake profile on Facebook and defaming her character with abusive comments and pictures. Identify the type of cybercrime for these situations.
- Name The transmission media best suitable for connecting to hilly areas.
- Write the expanded form of Wi-Fi.
- Rearrange the following terms in increasing order of data transfer rates. Gbps, Mbps, Tbps, Kbps, bps
- ______is a communication methodology designed to deliver both voice and multimedia communications over Internet protocol.
- Out of the following, which is the fastest wired and wireless medium of transmission? Infrared, coaxial cable, optical fibre, microwave, Ethernet cable
Answers:
- IoT
- router
- Network bandwidth
- People can take e-waste to recycling centres
- SMTP
- Cyber Stalking
- Radiowave or Microwave
- Wireless Fidelity
- bps -> Kbps -> Mbps -> Gbps -> Tbps
- VoIP
- Wired – Optical Fibre, Wireless – Microwave
Most expected 2 mark questions Unit 2 Computer networks
[1] Mr. Pradeep is working as a network admin in Durga Pvt. Ltd. He needs to connect 40 stand-alone computers in one unit using a server. How it is beneficial for the company? List out any two points.
Ans.:
1. Easy and Faster resource sharing
2. Cost factor
3. Higher connectivity
4. Reliability
[2] Differentiate between LAN, MAN, WAN.
Ans.:
LAN:
1. It stands for Local Area Network.
2. It limited upto small area like building, campus, or within 1 KM range.
3. LAN is a private network.
4. It offers faster data transfer.
MAN:
1. It stands for Metropolitan Area Nerwork.
2. It covers metropolitan area such has different cities of of country.
3. MAN can be private or public network.
4. It offers an average speed of data transfer.
WAN:
1. It stands for Wide Area Network.
2. It coverd wide range of areas over the countries.
3. It can be owned by government or large organization.
4. It offers slow speed of data transfer compared to MAN and LAN.
[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.
Ans.:
Dhara can use Modem to connect her telephone network with internet.
Functions of Modem:
1. Data compression
2. Error Correction
3. Flow control
4. Modulation and Demodulation
[4] What is an IP address? Write one example of IP Address.
Ans.:
IP stands for Internet Protocol. IP address is unique address of computer that identifies the computer in the network of local network. It is the set of rules governing the format of data sent via the internet or local network.
Example: 192.168.0.1
[5] Bharti wants to know the term used for the process of converting a domain name into IP address. How it works?
Ans. :
The process of onverting a domain name into IP address is known as Domain Name Resolution. After registering a domain name with a domain registrar that the wesbite content displayed. It is completed by a dedicated domain name resolution server.
[6] Illustrate the layout for connecting 5 computers in a Bus and a Star topology of Networks.


[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
Ans.:
a) POP3
b) VoIP
[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?
Ans.:
a) VoIP
b) Telnet
[9] Write short note on packet switching, message switching and circuit switching.
Ans.:
Packet Switching:
The information is trasnferred in form of data packets. These packets are fowarded one by one from sender to receiver. Each pakacket has a header and then it reassembles to the original message.
Message Switching:
The entire message is transmitted without break from node to node. It first stores then forward information that requires more time. There is no direct link eixsts between sender and receiver.
Circuit switching:
In this technique network resources are divided into pieces and bit delay is constant during a connection. It generates a dedicated path between sender and reveiver. Telephone system network is an example of circuit switching.
[10] Out of the following wired and wireless mediums of communication, which is the fastest:
Infrared, Coaxial Cable, Ethernet Cable, Microwave, Optical Fiber
Ans.:
Fastest wired medium: Optical Fiber
Fastest wireless medium: Microwave
[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?
- Coaxial cable
- Optical Fibre
- Ethernet Cable
(b) Also name the type of network out of (LAN/WAN/MAN) formed between various departments of the college.
Ans.:
a) Ethernet Cable
b) LAN
[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.
Ans.:
a) Repeater
b) Switch
[13]
(a) Which of the following is/are not communication media?
(i) Microwaves
(ii) Optical Fiber cable
(iii) Node
(iv) Radio waves
(b) Which of the following is/are not a topology?
(i) Star
(ii) Bus
(iii) Ring
(iv) Ethernet
Ans.:
a) (iii) Node
b) (iv) Server
[14] Identify the following media out of guided and unguided media?
Ethernet, Infrared, Bluetooth, Fibre Optic, Coaxial, Satellite, Radiowave, Microwave
Ans.:
Guided Media: Etherent, Fibre Optic, Coaxial
Ungudided Media: Infrared, Bluetooth, Satellite, Radiowave, Microwave
[15] Name the devices :
- This device links two networks together and is not a broadcast device, as it filters traffic depending upon the receiver’s MAC address.
- This device offers a dedicated bandwidth.
Ans.:
1. Bridge
2. Switch
[16] Expand TCP/IP. Write the purpose of TCP/IP in the communication of data on a network.
Ans. :
TCP/IP stands for Transmission Control Protocol/Internet Protocol. The purpose of TCP/IP is to deliver data packets between the source application of device and the destination using methods and structures that tags such as address information, within data packets.
[17] Write the expanded names for the following abbreviated terms used in Networking:
(i) MBPS
(ii) WAN
(iii) CDMA
(iv) WLL
Ans.:
(i) MBPS – Mega Bits Per Second
(ii) WAN – Wide Area Network
(iii) CDMA – Code Division Multiple Access
(iv) WLL – Wireless Local Loop
[18] Give two advantages and two disadvantages of tree topology.
Ans.:
Advantages:
1) Detection of errors
2) Easy expansion
Disadvantages:
1) Cost
2) Security
[19] Define the following terms: website , web browser
Ans.:
Website:
A website is collection of related page which is identified by a common domain and published on one web server.
Web browser:
A web browser is a computer software that allows to access the web site.
[20] Expand the following: ARPANET, NSFNet
Ans.:
ARPANET : Advance Research Project Agency Network
NSFNet: National Science Foundation Network
[21] Identify the transmission medium used in the following:
- TV Remotes
- Cellular Networks
Ans.:
1. Infrared
2. Radiowave
[22] Define: Web Server, Web Hosting
Ans.:
Web Server:
A web server is a special computer system, running on HTTP through web pages. It is used to store and deliver the contents of a website to clients such as a browser that request it.
Web Hosting:
Web hosting is a service that allows us to put a website or a web page onto the Internet, and make it a part of the World Wide Web so that users across the globe can access.
[23] Differentiate between IP address and MAC address.
Ans.:
IP Address:
1. IP address is logical address
2. It identifies the connection of a device on the internet or local network.
3. It can be changed by the network administrator or by the system itself.
4. It is numerical address separated by dots.
MAC Address:
1. It is a physical address of a Network Interface Card
2. It identifies the machine on the network
3. It is fixed and assigned by the manufacturer of the device
4. It is combination of numbes and symbols separated by colons
[24] (i) Name the connector used to connect ethernet cable to computer and hub or switch.
(ii) Name the cables used in TV networks.
Ans.:
(i) RJ45
(ii) Coaxial Cable
[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.
Ans.:
(i) Star
(ii) Message Switching
[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.
Ans.:
(i) High Level Bandwidth
(ii) Fastest Speed
(iii) Capable to cover large distance
(iv) Thinner and Light Weight
(v) Better Security
[27] What is the difference between hub and switch? Which is preferable in a large network of computers and why?
Ans.:
Hub forwards the message to every node connected and create a huge traffic in the network hence reduces efficiency whereas a Switch is also called intelligent hub since it redirects the received information/ packet to the intended node(s).
In a large network a switch is preferred to reduce the unwanted traffic in the network which may also reduce the bandwidth and cause network congestion.
[28] Give two advantages and two disadvantages of Bus topology.
Ans.:
Advantages:
1. Easy installation and connection
2. Very efficient for small networks
3. Less cable length
4. Cost effective
5. Easy to expand
Disadvantages:
1. Not good for large networks
2. Difficult to diagnose a fault
3. Individual device troubleshooting is very difficult
4. If network cable damages entire network fails
5. Packet loss is high
[29] Prakash wishes to install a wireless network in his office. Explain him the differences between guided and unguided media.
Ans.:
Guided Media:
1. Data travels through cables in guided media.
2. Uses point to point communication.
3. It forms discrete network topologies.
4. Examples : Twisted Pair, Coaxial Cables, Optical Fibre Cables
Unguided Media:
1. Data travels in the air in unguided media.
2. It uses radio braodcasting for communication.
3. It forms continuous network topologies
4. Examples: Radiowave, Micorwave, Infrared
[30] Which media is best for the following:
(i) Hilly Area
(ii) Large Industries
(iii) Point to point communication between two individuals
(iv) 4G
Ans.:
(i) Micfrowave or Radiowave
(ii) Optical Fibre Cable
(iii) Infrared
(iv) Microwave
Most expected 4 Marks questions Unit II Computer Networks Computer Science Class 12
Watch this video for 4 marks questions from Unit II Computer networks class 12 Computer Science.
Most expected questions Unit III Database Management Computer Science Class 12
In the next section of Most expected questions Computer Science Class 12 we are going to cover questions from Unit III Database Management System Computer Science Class 12. From this unit 1, 2, 3 and 4 marks will be asked. Here we go!
Most expected MCQ questions Unit III Database Management System Computer Science Class 12
[1] Vishal is giving an online test on the computer. The question he got on screen is which of the following is a valid SQL statement?
a) DELETE ALL ROWS FROM TABLE STUDENT;
b) DELETE * from student;
c) DROP all rows from student;
d) DELETE FROM student;
Select an appropriate option to help him.
Ans.: d) delete from student;
Explanation:
a,b and c options have incorrect syntax.
[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
Ans. b) alter
Explanation: Update command is DML command, modify and change are part of alter command.
[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
Ans. c) alter
Explanation: update is DML comamnd, drop is used to remove database and tables and remove is not an SQL command.
[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
Ans.: c) distinct
Explanation: Distinct keyword is used to fetch unique records from column hence it is not a part of DDL
[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
Ans. d) alter
Explanation: modify, drop and add are parts of alter table command. Drop itself a DDL comamnd used to remove table and database.
[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
Ans.: a) delete command
Explanation: Alter and drop commands are DDL command, remove is not a command of SQL.
[7] State true or false – “Drop command will remove the entire database from MySQL.”
Ans.:True
Explanation: Yes, drop command remove the database from Mysql.
Example – drop database database_name;
[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
Ans.: Master Key
Explanation: Primary key, Foreign key and Unique key are constraints of database.
[9 ]Which of the following statements is True?
a) There can be only one Foreign Key in a table
b) There can be only one Unique key is a table
c) There can be only one Primary Key in a Table
d) A table must have a Primary Key
Ans. : c) There can be only one primary key in a table
Explanaton: A table can have only one primary key, multiple primary keys on table are known as composite primary 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
Ans. b)Foregin Key
Explanation: Candidate Key and Alternate key are associated with Primary key but their values cannot derived from primary ket.
[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
Ans. b) distinct
Explanation:
Describe command is used to view the table structure, Unique is constraint and null values is used insert an unkonwn value into the table
[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
Ans. b) distinct
Explanation: Unique is a constraint, Set is used with update and having is used with group by
[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(*)
Ans. c) count(*)
Explanation: rest all are invalid options for MySQL.
[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
Ans.: a) AND, OR, NOT
Explanation: Rest are invalid symbols in mysql for opearators.
Watch this video for more understanding:
[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
Ans. b) count(column_name)
Explanation:
Most expected 2/3 marks questions Unit III Database Management Computer Science Class 12
[1] What is MySQL? List some popular versions of MySQL.
Ans. :
MySQL is one of the most pupular RDBMS software that allows to create a database to store, retrieve and manipulate data on that databases through queries.
MySQL 5.0 and MySQL 8.0 are popular versions of MySQL.
[2] Hetal is inserting “Rathod” in the “LastName” column of the “Emp” table but an error is being displayed. Write the correct SQL statement.
INSERT INTO Emp(‘Rathod’)VALUES(LastName) ;
Ans.:
The syntax to insert data is – insert into tablename (columns) values (values). Here she has written value frist then the columnname. So it is displaying error. The correct statement is:
insert into emp(LasName) values(‘Rathod’).
[3] Darsh created the following table with the name ‘Friends’ :
Table : Friends
| Freind_Code | Name | Hobbies |
| F001 | Anurag | Traveling |
| F002 | Manish | Watching Movies |
Now, Darsh wants to delete the ‘Hobbies’ column. Write the MySQL statement.
Ans.:
alter table friends drop column hobbies;
[4] Mr. Nikunj entered the following SQL statement to display all Salespersons of the cities “Chennai” and ‘Mumbai’ from the table ‘Sales’.
Table: Sales
| Scode | Name | City |
| S0001 | Krishanan Iyer | Chennai |
| S0002 | Atmaram Bhide | Mumbai |
| S0003 | Jethalal Gada | Bhachau |
| S0004 | Venugopal Srinavasana | Chennai |
| S0005 | Mandar Mumbaikar | Mumbai |
SELECT * FROM Sales WHERE City=‘Chennai’ AND City=‘Mumbai’;
He is getting the Empty Set as output. Explain the problem with the statement and rewrite the correct statement.
Ans.:
As he wants to display records from Chennai and Mumbai City, he must use OR operator in place of AND operator. The correct statement is as follows:
select * from sales where city=’Chennai’ or city=’Mumbai’;
He can also use IN operator, the correct statment is:
select * from sales where city in (‘Chennai’,’Mumbai’)
[5] Is NULL value the same as 0 (zero) ? Write the reason for your answer.
Ans.:
MySQL treats NULL as special values. It means missing or unknown or not applicable value. It is not a zero, not a space, it is just an empty cell. Zero refers a numeric value where is NULL is treated as special value in the table.
[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.
Ans. :
update company set comm=500 where sales>200000;
[7] While using SQL pattern matching, what is the difference between ‘_’ (underscore) and ‘%’ wildcard symbols?
Ans.:
While using SQL pattern matching,
% represent zero, one or multiple characters
_ is used to represent exactly a single character position
[8] What is the meaning of open source and open source database management system?
Ans.:
Open Source refers to any program whose source code is made available for use or modification as users or developers see fit.
An open source database is any database application with a codebase that is free to view, download, modify, distribute, and reuse. Open source licenses give developers the freedom to build new applications using existing database technologies.
[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.
Ans.:
Distinct keyword is used to get a list of only different values.
Example: select distinct occupation from employee;
[10] How is alter table statement different from UPDATE statement?
Ans.:
Alter table is different than update in the following ways:
1. Alter is DDL command, Update is DML command
2. Alter is used to modify the structure of table where as update is used to modify the table content
3. Alter allows to add column or constraints, modify column and delete column or constraints, update allows to change the data of table.
[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.
Delete from firstname from emp;
Ans.:
delete from emp where firstname = ‘Rama’;
[12] What is the relationship between SQL and MySQL?
Ans.:
SQL is a langauge that provides command to work upon databases where as MySQL is a software that runs SQL commands. SQL provides commands for query and operates the database systems. MySQL allows to handle, store, modify and delete and store data in an organized way.
[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;
Ans.:
alter table student add column hobbies varchar(50);
[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).
Ans.:
select * from employee where firstname like ‘___n’;
[15] Identify aggregat functions of MySQL amongst the following :
TRIM(), MAX(), COUNT(*), ROUND()
Ans.:
MAX(), COUNT(*)
[16] Write the following statement using ‘OR’ logical operator :
SELECT first_name, last_name, subject FROM studentdetails WHERE subject IN (‘Maths’, ‘Science’);
Ans.:
select first_name,last_name, subject from studentdetails where subject =’Maths’ or Subject=’Science’;
[17] What is MySQL used for? Ajay wants to start learning MySQL. From where can he obtain the MySQL software?
Ans.:
MySQL is used to store, add, retrieve and process data from the database.
Ajay can download the MySQL software from https://www.mysql.com/downloads/
[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 :
SELECT Marks+5 FROM Student WHERE Marks <33;
Rewrite the correct statement.
Ans.:
update student set marks=marks+5 where marks<33;
[19] Consider a table Accounts and answer the following:
(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.
Ans.:
(i) Char or Varchar
(ii) Char or Varchar, Date
[20] Given the table ‘Player’ with the following columns :
Table – Player
| Pcode | Points |
| P001 | 95 |
| P002 | 82 |
| P003 | 74 |
| P004 | 93 |
| P005 | 77 |
Write the output of the following queries:
- SELECT AVG(POINTS) FROM Player;
- Select COUNT(POINTS) FROM Player;
Ans. :
1. avg(points)
————–
84.2
2. count(POINTS)
—————-
5
Watch this video for more understanding:
[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?
Ans.:
Char is a fix length data type which stores number of characters as same as specified while creating a table. Varchar is variable length data type which stores data as long as the values provided to the rows.
In Priya’s table (10) indicates the size of the values, it means that user can enter 10 characters into those column values.
[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’.
Ans.:
select * from employee where city not in (‘Delhi’,’Mumbai’,’Chnadigarh’)
OR
select * from employee where city<>’Delhi’ or city<>’Mumbai’ or city<>’Chandigarh’
OR
select * from employee where city!=’Delhi’ or city!=’Mumbai’ or city!=’Chandigarh’
[23] Ajay has applied a Constraint on a column (field) such that
(i) Ajay will certainly have to insert a value in this field when he inserts a new row in the table.
(ii) If a column is left blank then it will accept 0 by itself.
Which constraints has Ajay used?
Ans.:
(i) Not null
(ii) Default
[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”.
Ans.:
select * from student where remark!=’PASS’
OR
select * from student where remark<>’PASS’
[25] Consider the table : Company
| SID | Sales |
| S001 | 250 |
| S002 | 100 |
| S002 | 200 |
What output will be displayed by the following SQL statements?
(i) select avg(sales) from company where sales>200;
(ii) select sum(sales)/2 from company where SID=’S002′;
Ans.:
(i) avg(sales)
—————–
250
(ii) sum(sales)
———————-
150
[26] Consider the table ‘Hotel’ given below:
Table : Hotel
| EMPID | Category | Salary |
| 1001 | Permanent | 25000 |
| 1002 | Contract | 18000 |
| 1003 | Adhoc | 10000 |
| 1004 | Contract | 12000 |
| 1005 | Permanent | 20000 |
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.
SELECT Category, Salary FROM Hotel GROUP BY Category;
Write one more query to display maximum salary category wise.
Ans.:
select category, avg(salary) from hotel group by category;
select category,max(salary) from hotel group by category;
[27] Namrata has created the following table with the name ‘Order’.
| Field | Constraint |
| OrderID | Primary Key |
| OrderDate | Not Null |
| OrderAmount | |
| StoreID |
Answer the following:
- What is the data type of columns OrderId and OrderDate in the table Order?
- Namrata is now trying to insert the following row : O102, NULL, 59000, S105
Ans.:
1. OrderId – char(4), Orderdate – Date
2. insert into order (orderid,orderamount,storeid) values(‘O102′,59000,’S105’)
[28] Write SQL query to create a table ‘Event’ with the following structure :
| Field | Data Type | Size | Constraint |
| eventid | varchar | 5 | Primary Key |
| event | varchar | 30 | not null |
| location | varchar | 50 | Ahmedabad should be by default |
| clientid | integer | Foreign Key Parent table (Client) | |
| eventdate | date |
Ans.:
create table event
(eventid varchar(5) primary key,
event varchar(30) not null,
location varchar(50) default ‘Ahmedabad’,
clientid int references client,
eventdate date);
[29] How is a Primary key constraint different from a Unique key constraint?
Ans.:
Primary Key:
1. Identifies rows uniquely
2. Cannot be null
3. One primary key present in a table
4. Used to create relationships between two tables
Unique Key:
1. Identifies rows uniquely
2. Can be null at once
3. Multiple uniques keys can be used in a table
4. Cannot be used to create relationships
[30] Write two similarities between CHAR and VARCHAR data types.
Ans.:
1. Represents text values
2. Values must be enclosed with single or double quotes
[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.
Ans.:
If one enters data for a row with no value for the source column, it will save null value will be saved in the column.
select * from travelpackage where source is null;
[32] Define: Field/Attribute, Tuple/Record
Ans.:
Field/Attribute: A field/attribute is vertical data set of a table derives its values from pool of data.
Tuple/Record: A tuple/recods is horizotal data set of a table stores one complete data of one entity.
[33] Define: Degree and Cardinality
Ans.:
Degree refers to the number of columns or attributes of a table. It changes with addition or deletion of columns.
Cardinality refers to the number rows or tuple of a table. It gets changes with addition or deletion of columns.
[34] Define: Candidate Key, Alternate Key
Ans.:
Candidate Key: The columns which can serve as primary key of a table is known as candidate keys.
Alternate Key: The candidates keys wich are not primary keys are known as alternate keys.
[35] A NULL value can be inserted into a foreign key? Justify your answer.
Ans.:
Yes, NULL value can be inserted into a foreign key. Foreign key represents a linked records from primary key table, if there something which value is not moatched or unknown can be set as null.
[36] Ravindra is confused about what is a domain? Clear his confusion with an example.
Ans.:
Domain refers to the pool of values from which a field of a table derives its values.
Example rollno field derives its values from set of integers, marks derives from the range of marks in the examiantion.
[37] Consider the following table – Student
| AdmNo | RollNo | Name | Class | Marks |
| 1001 | 1 | Shailesh | X | 76 |
| 1002 | 2 | Kamalaa | XII | 89 |
| 1003 | 3 | Dinesh | XI | 85 |
Identify the candidate keys and alternate keys.
Ans.:
The attributes admno and rollno both contains unique records so they can be a primary key for the table. Hence both can be candidate keys. Where as Name, Class and Marks are alternate keys.
[38] Enlist any four popular RBMDS software.
Ans.:
1. MySQL
2. Oracle
3. MS SQL
4. DB2
[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?
Ans.:
Initially, 4 degree and 6 cardinality.
After adding 2 rows and deleting 1 column the degree will be 3 and cardinality 8.
[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:
show * from patient;
She is not getting the output. Rewrite the correct statement.
Ans.:
(i) MySQL store date in this format: YYYY-MM-DD
(ii) select * from patient;
[41] What is sorting? Which keyword is used to sort data from the table in SQL?
Ans.
Sorting refers to rearrnaging the data in increasing (Ascending) or decreasing (Descending) order. SQL provides order by keyword to sort data.
[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.
Ans.:
Order by clause is used in select comand. The order by clause is final clause of select statement. You must specify the column name after order by. By default order by display the records in ascending order. If you want to dispay the result in descending order, you have to provide the keyword desc after columns in order by clause.
Example: Sortig records of emplpoyees according to their salary.
Ascending Order: select * from emp order by sal;
Descending Order: select * from emp order by sal desc;
[43] Consider the given table states and write the output of queries given below:
| Code | Sname | Capital | Districts | Flower | FDate |
| I001 | Gujarat | Gandhinagar | 33 | Marigold | 1960-05-01 |
| I002 | Rajasthan | Jaipur | 50 | Rohida | 1949-03-30 |
| I003 | Goa | Panaji | 2 | Jasmine | 1987-05-30 |
| I004 | Punjab | Chandigarh | 23 | Gladiolus | 1950-01-26 |
| I005 | Kerala | Thiruvananthapuram | 14 | Golden Shower | 1956-01-11 |
| I006 | Karnataka | Bangalore | 31 | Lotus | 1956-01-11 |
| I007 | Uttar Pradesh | Lucknow | 75 | Palash | 1950-01-24 |
- select min(fdate) from states;
- select count(districts) from states where districts>30;
- select avg(districts) from states where sname like ‘%u%’;
- select count(distinct fdate) from states;
Ans.:
[1]
| min(fdate) |
| 1949-03-30 |
[2]
| count(districts) |
| 4 |
[3]
| avg(districts) |
| 43.67 |
[4]
| count(distinct fdate) |
| 6 |
[44] Write output of queries given below based on table chips:
| brand_name | flavour | price | qty |
| Lays | Onion | 25 | 7 |
| Bingo | Pudina | 42 | 10 |
| Pringles | Salty | 37 | 8 |
| Uncle Chips | Spicy | 20 | 15 |
| Doritos | Pudina | 48 | 8 |
| Cornitos | Spicy | 28 | 18 |
- Select BRAND_NAME, FLAVOUR from CHIPS where QTY like ‘%8’;
- Select * from CHIPS where FLAVOUR=”SPICY” and PRICE > 20;
- Select BRAND_NAME from CHIPS where price between 30 and 48 or QTY < 15;
- Select count( distinct (flavour)) from CHIPS;
- Select price *1.5 “New Price” from CHIPS where FLAVOUR = “PUDINA”;
- Select distinct (BRAND_NAME) from CHIPS where brand_name like ‘%o%’order by BRAND_NAME desc;
Ans.:
[1]
| brand_name | flavour |
| pringles | salty |
| doritos | pudina |
| cornitos | spicy |
[2]
| brand_name | flavour | price | qty |
| cornitos | spicy | 28 | 18 |
[3]
| brand_name |
| pringles |
| doritos |
[4]
| count( distinct (flavour)) |
| 4 |
[5]
| New Price |
| 63 |
| 72 |
[6]
| Distinct (brand_name) |
| Bingo |
| Cornitos |
| Doritos |
Most expected 4 marks questions computer science class 12 Unit 3 Database Management
[1] Consider the following tables participant and activity and answer the questions :
Table – Participant
| ADMNO | NAME | HOUSE | ACTIVITYOCDE |
| A001 | Sagar Patel | Red | AC001 |
| A002 | Kaushik Maheta | Blue | AC002 |
| A003 | Noor Joshi | Green | AC003 |
| A004 | Mahesh Joshi | Yellow | AC004 |
| A005 | Nutan Chauhan | Blue | AC001 |
| A006 | Mahek Patel | Yellow | AC004 |
| A007 | Sidhdharth Patel | Blue | AC003 |
| A008 | Gaurang Vyas | Green | AC004 |
Table – activity fields: activitycode, activityname, points
| ACTIVITYCODE | ACTIVITYNAME | POINTS |
| AC001 | Poem Recitation | 120 |
| AC002 | Maths Quiz | 150 |
| AC003 | Science Quiz | 180 |
| AC004 | Sports | 200 |
- 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.
- Identify data type and size to be used for column ACTIVITYCODE in table ACTIVITY.
- Write a query to display Activity Code along with the number of participants participating in each activity (Activity Code wise) from the table Participant.
- How many rows will be there in the Cartesian product of the two tables in consideration here?
- To display Names of Participants, Activity Code, and Activity Name in alphabetic ascending order of names of participants.
- 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.
Ans.:
1. NAME can be repeated sometimes, so ADMNO which is unique for each participant. Hence it is set up as primary key.
2. It can be char or varchar with size 5.
3. select activitycode, count(*) from participant group by activity;
4. There are 32 rows in cartesian product of the two tables.
5. select name, activitycode, activityname from participant p, activity a where p.activitycode=a.activitycode order by name;
6. select name, activitycode,activityname from activity a, participant p where p.activitycode=a.activitycode and a.activityname like ‘quiz’ and a.points>150;
[2] Consider the following tables SUPPLIER and ITEM and answer the questions
Table – Supplier
| SNO | SNAME | AREA | |
| 1 | A to Z Suppliers | Narol | a2zsupp@gmail.com |
| 2 | Rathi Brothers Company Pvt. Ltd. | Naroda | rathibrothers@gmail.com |
| 3 | Rushan Communications | Danilimda | rushan786@gmail.com |
| 4 | Apex Entreprise Pvt. Ltd. | Maninagar | apexmaninagar@gmail.com |
| 5 | Mahi Transport Co. Ltd. | Maninagar | mahimaninagar@gmail.com |
| 6 | Dhareja Travels | Naroda | dharejatravelsnaroda@gmail.com |
| 7 | Sameer Suppliers | Narol | sameersuppliers@gmail.com |
Table – Item
| INO | INAME | PRICE | SNO |
| I001 | Cargo | 28000 | 1 |
| I002 | Cartoon | 500 | 2 |
| I003 | LG Mobiles | 2600 | 3 |
| I004 | Truck on Rent | 55000 | 1 |
| I005 | Reliance SIM | 700 | 3 |
| I006 | Packing Material | 8000 | 1 |
| I007 | Moterbikes | 70000 | 4 |
- Which column should be set as the Primary key for SUPPLIER table ?
- 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.
- Write the data type and size of INo column of ‘ITEM’ table.
- To display names of Items, SNo and Names of Suppliers supplying those items for those suppliers who have stores located in Naroda.
- To display Names of Items, SNo, Price and Corresponding names of their suppliers of all the items in ascending order of their Price.
- 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.)
- What will be the number of rows in the Cartesian product of the above two tables?
Ans.:
1. SNO can be set as primary key for supplier table as it has unique numbers for each supplier details.
2. Emails are unique but it contains more characters in it. Primary key should be such a column that contains very less number of chartacters or digits in it.
3. INO – char(4)
4. select iname,sno,sname from item i, supplier s where i.sno=s.sno and area=’Naroda’;
5. select iname,sno,price,sname from item i, supplier s where i.sno=s.sno order by price;
6. select iname, min(price), max(price) from item group by iname;
7. There are 49 rows in the cartesian product of the above two tables.
[3] Consider the table given below:
Table – Faculty
| TEACHERID | NAME | ADDRESS | STATE | PHONENUMBER |
| T001 | Avinash | Ahmedabad | Gujarat | 9825741256 |
| T002 | Akhilesh | Jaipur | Rajasthan | 9824456321 |
| T003 | Shivansh | Mumbai | Maharashtra | 9327045896 |
| T004 | Minaxi | New Delhi | Delhi | 9012547863 |
Table – Course, Fields: coruseid, subject, teacherid, fee
| COURSEID | SUBJECT | TEACHERID | FEE |
| 1001 | Computer Science | T001 | 6750 |
| 1002 | Informatics Practices | T004 | 4550 |
- Which column is used to relate the two tables?
- Is it possible to have a primary key and a foreign key both in one table? Justify your answer with the help of table given above.
- With reference to the above given tables, write commands in SQL for (i) and (ii) and output for (iii) :
- (i) To display CourseId, TeacherId, Name of Teacher, Phone Number of Teachers living in Delhi.
- (ii) To display TeacherID, Names of Teachers, Subjects of all teachers with names of Teachers starting with ‘S’.
- (iii) SELECT CourseId, Subject,TeacherId,Name,PhoneNumber FROM Faculty,Course WHERE Faculty.TeacherId = Course.TeacherId AND Fee>=5000;
Ans.:
1. Teacherid column is used to related the two tables
2. Yes, Teacherid will be a primary key and foreign key in both table
3. (i) select courseid, teacherid, name, phonenumber from course c, faculty f where c.teacherid=f.teacherid and address like ‘%Delhi%’;
(ii) select teacherid, name, subject from course c, faculty f where c.teacherid=f.teacherid and name like ‘S%’;
(iii) courseid subject teacherid name phonenumber
———————————————————————————————————
1001 Computer Science T001 Avinash 9825741256
[4] Write commands in SQL for (1) to (4) and output for (5) and (6).
Table : Store
| STOREID | NAME | LOCATION | CITY | NOOFEMPLOYEES | DATEOPENED | SALESAMOUNT |
| S01 | BHAGYA LAXMI | SATELLITE | AHMEDABAD | 7 | 2018-04-01 | 25000 |
| S02 | PARTH FASHION | AKOTA | BARODA | 2 | 2010-07-15 | 45000 |
| S03 | KRISHNA SAREES | UMARWADA | SURAT | 8 | 2020-08-13 | 85000 |
| S04 | SAMEER CLOTHES | RELIEF ROAD | AHMEDABAD | 2 | 2012-06-02 | 78000 |
- To display name, location, city, SalesAmount of stores in descending order of SalesAmount.
- To display names of stores along with SalesAmount of those stores that have ‘fashion’ anywhere in their store names.
- To display Stores names, Location and Date Opened of stores that were opened before 1st March, 2015.
- To display total SalesAmount of each city along with city name.
- SELECT distinct city FROM store;
Ans. :
1. select name,location,city,salesamount from fstore order by salesamount dessc;
2. select name,salesamount from store where name like ‘%fashion%’;
3. select name, location, dateopened from store where dateopened<'2015/03/01'; 4. select city,sum(salesamount) from store group by city; 5. distinict city ---------------- AHMEDABAD BARODA SURAT [/showhide]
[5] Consider the following table named ‘‘SOFTDRINK’’. Write commands of SQL for (1) to (4) and output for (5) to (7).
Table: Softdrink, Fields: drinkcode, dname, price, calories
| drinkcode | dname | price | ml |
| D1011 | Thums Up | 45 | 200 |
| D1012 | Cocacola | 42 | 150 |
| D1013 | Pepsi | 28 | 100 |
- To display names and drink codes of those drinks that have more than 100 ml.
- To display drink codes, names and calories of all drinks, in descending order of ml.
- To display names and price of drinks that have price in the range 41 to 45 (both 41 and 45 included).
- Increase the price of all drinks in the given table by 10%.
- SELECT COUNT(DISTINCT(PRICE)) FROM SOFTDRINK;
- SELECT MAX (ML) FROM SOFTDRINK;
- SELECT DNAME FROM SOFTDRINK WHERE DNAME LIKE “%cola%”;
- What is the degree and cardinality of ‘SOFTDRINK’ TABLE ?
Do yourself
[6] In a Database Company, there are two tables given below :
Table Sales
| SALESMANID | NAME | SALES | LOCATIONID |
| S0001 | SAMYAK SHAH | 1500 | 1 |
| S0002 | PRASHANT GARG | 2000 | 1 |
| S0003 | SHAURYA SAXENA | 2500 | 2 |
| S0004 | SAUMITYA PARIKH | 3000 | 2 |
| S0005 | AYUSH SINGH | 2000 | 3 |
| S0006 | HARSHVERDHAN SINGH | 1800 | 3 |
Table Location
| LOCATIONID | LOCATIONNAME |
| 1 | MANINAGAR |
| 2 | ISANPUR |
| 3 | RAM BAG |
Write SQL queries for the following :
- To display SalesmanID, names of salesmen, LocationID with corresponding location names.
- To display names of salesmen, sales and corresponding location names who have achieved Sales more than 2000.
- To display names of those salesmen who have ‘SINGH’ in their names.
- Identify Primary key in the table SALES. Give reason for your choice.
- Write SQL command to change the LocationID to 3 of the Salesman with ID as S0003 in the table ‘SALES’.
Ans. :
1. select salemanid, name, locationid, locationname from sales, location where sales.locationid=location.locationid;
2. select name, sales, locationname from sales, location where sales.locationid=location.locationid and sales>2000;
3. select name from sales where name like ‘%SINGH%’;
4. Salesmanid is the primary key for sales because it hs unique records
5. update sales set locationid=3 where salesmanid=’S0003′
[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
| DCODE | DEPARTMENT | LOCATION |
| 10 | AGRICULTURE | ANAND |
| 20 | MINES | NADIAD |
| 30 | TPP | KHEDA |
| 40 | MECHANICAL | AHMEDABAD |
Table:EMP
| ENO | NAME | DOJ | DOB | GENDER | DCODE |
| 1111 | MISKA | 2020/03/01 | 1997/11/15 | F | 10 |
| 1112 | AKSHAY | 2018/06/05 | 1998/12/04 | M | 20 |
| 1113 | NEEL | 2021/07/01 | 2000/10/20 | M | 10 |
| 1114 | ANKITA | 2016/04/25 | 2001/10/27 | F | 30 |
| 1115 | MOHIT | 2016/12/22 | 2003/11/02 | M | 40 |
- To display Eno, Name, Gender from the table EMPLOYEE in ascending order of Eno.
- To display the Name of all the MALE employees from the table EMPLOYEE.
- To display the Eno and Name of those employees from the table EMPLOYEE who are born between ‘1997-01-01’ and ‘1999-12-01’.
- To count and display FEMALE employees who have joined after ‘1999-01-01’.
- SELECT COUNT(*),DCODE FROM EMPLOYEE GROUP BY DCODE HAVING COUNT(*)>1;
- SELECT DISTINCT DEPARTMENT FROM DEPT;
- SELECT NAME,DEPARTMENT FROM EMPLOYEE E,DEPT D WHERE E.DCODE=D.DCODE AND ENO<1113
- SELECT MAX(DOJ), MIN(DOB) FROM EMPLOYEE;
Ans.:
1. SELECT ENO, NAME, GENDER FROM EMP ORDER BY ENO;
2. SELECT NAME FROM EMP WHERE GENDER =’M’;
3. SELECT ENO, NAME FROM EMP WHERE DOB BETWEEN ‘1997-01-01’ AND ‘1999-12-01’;
4. SELECT COUNT(*) FROM EMP WHERE GENDER=’F’ AND DOJ>’1999-01-01′;
5. COUNT(*) DCODE
—————————–
2 10
1 20
1 30
1 40
6. DISTINCT DEPARTMENT
—————————————
AGRICULTURE
MINES
TPP
MECHANICAL
7. NAME DEPARTMENT
——————————-
MISKA AGRICULTURE
AKSHAY MINES
8. MAX(DOJ) MIN(DOB)
——————————
2021/07/01 1997/11/15
Watch the following video for more understanding:
Most expected Questions interface of python with MySQL
In this section of Most expected questions in Computer Science class 12, we are going to discuss questions from the interface of python with MySQL. Here we go!
Most important MCQs Interface of Python with MySQL
Let us begin with MCQs. here we go!
[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
Ans. : b) pymysql
[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()
Ans. a) connect()
[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()
Ans. : a) Mycur.fetch()
[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()
Ans. a) cursor.rowcount()
[5] Rearrange the steps for connecting MySQL database with python in the appropriate order.
i) create a cursor object
ii) open connection to a database
iii) execute the query and commit or fetch records
iv) import MySQL Connector
v) close the connection
a) i – ii – iii – iv – v
b) iv – ii – i – iii – v
c) v – i – iii – ii- iv
d) i – iii – v – ii – iv
Ans. b) iv – ii – i – iii – v
[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
Ans.: a) host
[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
Ans.: d) cursor object
[8] Which of the following is the correct statement:
a) import connector.mysql as cn
b) import MySQL.Connector as cn
c) import mysql.connector as cn
d) Import mysql.connectot AS cn
Ans.: c) import mysql.connector as cn
[9] The mysql.connector.connect() method returns
a) int object
b) connection object
c) list object
d) str object
Ans.: b) connection 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)
Ans.: a) cn.cursor()
[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()
Ans.: 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()
Ans.:a) execute()
[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()
Ans.: c) close()
[14] The fetchall() function will return all the records as
a) Only lists
b) Tuple of list
c) List of lists
d) List of tuples
Ans.: d) List of tuples
[15] What will be returned by fetchone() method?
a) All values in str
b) All values in list or tuple
c) All values in dictionary
d) None of these
Ans.: b) All values in list or tuple
[16] State True or False: “The fetechone() method returns None if there are no more records in database.”
Ans.: False
[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
Ans.: b) %s
[18] The fetchmany(n) returns any n no. of rows from database.
a) Yes, any n rows randomly
b) no, sorts first then top n rows
c) no, only top n rows from table as its present in table
d) None of these
Ans.: c) no, only top n rows from table as its present in table
[19] When fetchone() method is used, the cursor moves to ____________ record immediately after getting the specified row.
a) next record
b) last record in the table (end of table)
c) first record
d) previous record
Ans.: a) next record
[20] A string template refers to
i) MySQL Command
ii) MySQL Function
iii) string containing a mixture of one or more format codes
iv) a string consists of text with the f % v
a) i) and ii)
b) i and iii)
c) iii) and iv)
d) ii) and iv)
Ans.: c) iii) and iv)
[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()
Ans.: a) commit()
Most important 2/3 Marks Questions Interface of Python with MySQL
[1] Nisha is trying to create a project on python. Where she wants to store the records in a database. She learnt about front-end and back-end, But forget what it means right now. Help her by giving definition of front-end and backend.
Ans.:
Front-end: While creating a project on python user needs to take input using python program. This python interface is known as front-end.
Back-end: The python project usually stores data from python interface to a particular database. This database is known as back-end.
[2] What is DB-API?
Ans.:
Usually python standard libray doesn’t provide any RDBMS interface for database programming. To do this user needs to install a module named DB-API (DataBase Application Programming Interface). It is a set of tools used by an application program to communicate with the operating system or RDBMS software.
[3] What does DB-API include?
Ans.:
1. Import the module
2. Establishing connection
3. Passing and triggering SQL statements
4. Closing connection
[4] Man wants to install the mysql connector. Suggest steps to install the same.
Ans. :
1. Press window + R and open Run command.
2. Type cmd.
3. Type command – pip install mysql-coonector
4. After installation you will get the message Successfully installed mysql-connector, close the cmd window.
[5] Prakash has installed mysql connector. Now he wants to check whether its properly installed or not. Suggest python command to do this task.
Ans.:
import mysql.connector
[6] Name any two python mysql connector modules.
Ans.:
1. mysql.conector
2.pymysql
[7] What are the main components of mysql.connector module?
Ans.:
1. connect method
2. cursor object
[8] What do you mean by a connection?
Ans.:
After importing the mysql.connector module user need to establish a connection between database and python script. It is done through the connect method.
[9] What do you mean by cursor object?
Ans.:
Cusror object provides control structure to execute the queries of RDBMS through the connector. It executes the sql commands and send the result set to over the connection at a time.
[10] What are the parameters of mysql.connector.connect method?
Ans.:
1. host : The host name of mysql database, usually localhost
2. user : username for MySQL Serever, ussually root
3. password or passwd: Password the user, usuallu root
4. database: Database name to save the records
[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.______()
Ans.:
Line 1 – mysql.connector
Line 2 – connect
Line 3 – cursor
Line 4 – close
[12] Fill the proper words in the following code snippet:
cn=mysql.connector.connect(_______=localhost,________='root',________='root',______='school')
Ans.:
1 – host
2 – user
3 – passwd/password
4 – database
[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.
Ans.:
1 – cursor.execute()
2 – connector.commit()
[14] What are the methods used to read data from SQL tables?
Ans.:
1. fetchone()
2. fetchall()
3. fetchmany()
4. rowcount
[15] Differentiate between fetchone() and fetchmany().
Ans.:
fetchone(): It fetches next row ofa query result set. It returns the value in object. The object stores multiple values from database table.
fetchmany(): It fetches number of rows from database as a result set. It returns the result set as list of tuples. The default size 1, if no rows returned as result set it will return emty list.
[16] Is rowcount method? Explain in short.
Ans.:
rowcount is not a method but it is a property of cursor object. It returns the numbers of rows/records/tuples inserted in the table.
[17] Consider the following table: IPL2022
| Rank | Batter | Runs | Team |
| 1 | Jos Buttler | 863 | RR |
| 2 | KL Rahul | 616 | LSG |
| 3 | Quinton de Kock | 508 | LSG |
| 4 | Hardik Pandya | 487 | GT |
| 5 | Shubman Gill | 483 | GT |
Observe the following given code and write the output:
import mysql.connector as ms
cn=ms.connect(host='localhost',user='root',passwd='root',database='IPL')
cr=cn.cursor()
cr.execute("seleect * from IPL2022")
r=cr.fetchone()
r=cr.fetchone()
r=cr.fetchone()
data=int(r[2])
print(data*2)
Ans. :
Output : 1016
[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()
cr.execute("seleect * from IPL2022")
r=cr.fetchone()
print("No. of records fetched:",cr.rowcount)
r=cr.fetchmany(2)
print("No. of records fetched:",cr.rowcount)
Ans.:
No. of records fecthed: 1
No. of recrods fetched:3
[19] Consider the tabe given in question no. 17 and write python code to display the top 3 run-scorer.
Ans.:
import mysql.connector as ms
cn=ms.connect(host=’localhost’,user=’root’,passwd=’root’,database=’IPL’)
cr=cn.cursor()
cr.execute(“seleect * from IPL2022”)
r=cr.fetchmany(3)
for i in r:
print(i,end=”\n”)
[20] Consider the table given in question 17 and write python code to display details for those batsmen who score less than 500 runs.
Ans.:
import mysql.connector as ms
cn=ms.connect(host=’localhost’,user=’root’,passwd=’root’,database=’IPL’)
cr=cn.cursor()
cr.execute(“seleect * from IPL2022 where runs<500”)
r=cr.fetchall()
for i in r:
print(i,end=”\n”)
[21] Write python code to insert this record: (6,’David Miller’,481,’GT’)
Ans.:
import mysql.connector as ms
cn=ms.connect(host=’localhost’,user=’root’,passwd=’root’,database=’IPL’)
cr=cn.cursor()
cr.execute(“insert into ipl2022 values(6,’David Miller’,481,’GT’)”)
cn.commit()
cn.close()
[22] Write python code to update short team name GT to full team name Gujarat Titans.
Ans.:
import mysql.connector as ms
cn=ms.connect(host=’localhost’,user=’root’,passwd=’root’,database=’IPL’)
cr=cn.cursor()
cr.execute(“update ipl2022 set team=’Gujarat Titans’ where team=’GT'”)
cn.commit()
cn.close()
[23] Write code to delete record of David Miller.
Ans.:
import mysql.connector as ms
cn=ms.connect(host=’localhost’,user=’root’,passwd=’root’,database=’IPL’)
cr=cn.cursor()
cr.execute(“delete from ipl2022 where batsman=’David Miller'”)
cn.commit()
cn.close()
Watch this video for practical understanding:
[24] The partial code is given to check whether the connection between the interface of python with MySQL is established or not. Fill in the blanks with appropriate functions/statements for given statements:
Note the following to establish connectivity between Python and MYSQL:
- Username is root
- Password is root
- Database name – Transport
| V_ID | Name | Model | Price |
| integer | varchar | integer | integer |
import ____________ as msql #Statement 1
cn=msql.___________(_______,________,________,_______) #Statement 2
if cn.__________: # Statement 3
print("Successfully Connected...")
else:
print("Something went wrong...")
Write the missing statements as per the given instructions:
- Write the module name required in #Statement 1
- Complete the code with the name of a function and parameters in #Statement 2
- Write a function to check whether the connection is established or not in #Statement 3
Ans.
1. mysql.connector
2. connect(host=”localhost”,user=’root’,password=’root’,database=’transport’)
3. is_connected():
[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.
import mysql.connector as mysql
con1=mysql.connect(host="localhost",
user="root",
password="root",
database="Transport")
_______________ #Statement 1
print("Models after 2010 : ")
q="Select * from vehicle where model>2010"
_______________________ #Statement 2
data= _________________ #Statement 3
for rec in data:
print(rec)
Write the following missing statements to complete the code:
- Statement 1 – to create the cursor object
- Statement 2 – to execute the query that extracts records of those vehicles whose model is greater than 2010.
- Statement 3 – to read the complete result of the query into the object named data.
Answer:
Ans.
1. cr=con1.cursor()
2. cr.execute(q)
3. cr.fetchall()
Watch this video to understand with practical explanation:
[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:
The table structure of student is as follows:
| RollNo | Name | Standard | Marks |
| integer | varchar | integer | float |
Note the following to establish connectivity between Python and MySQL:
- 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()
rno=int(input("Enter Roll Number :: "))
name=input("Enter name :: ")
std=int(input("Enter class :: "))
marks=int(input("Enter Marks :: "))
querry=________________________________ #Statement 1
______________________ #Statement 2
______________________ # Statement 3
con1.close()
print("Data Added successfully")
Write the following missing statements to complete the code:
Statement 1 – query insert records with all the variables
Statement 2 – to execute the command that inserts the record in the table Student.
Statement 3 – to add the record permanently to the database
Answer:
Ans.:
1. “inset into student values({},'{}’,{},{})”.format(rno,name,std,marks)
OR
“insert into student23 values(%s,%s,%s,%s)”,(rno,name,std,marks))
2. mycursor.execute(querry)
3. con1.commit()
Follow this link to access sample papers for board exam 2023:
Thats’ all from Most expected questions Computer Science Class 12. I hope this article will help you to prepare well for your board exam. Thank you for visit.
Q1. What are the most expected questions in Class 12 Computer Science board exam?
The most expected questions usually come from Python programming, File Handling, DBMS, and Computer Networks.
Q2. Are these questions based on CBSE pattern?
Yes, these questions follow the latest CBSE syllabus and board exam pattern.
Q3. How to score 90+ in Class 12 Computer Science?
Practice most expected questions, solve previous year papers, and revise important concepts regularly.
Q4. Are most expected questions enough to pass Class 12 Computer Science?
Yes, practicing Class 12 Computer Science most expected questions helps you cover important concepts and frequently asked topics. However, students should also revise theory, solve previous year question papers, and practice sample papers for better scores.
Q5. From which chapters do most expected questions usually come in Class 12 Computer Science?
Most expected questions are generally asked from Python Programming, File Handling, Data Structures (Stack), DBMS, and Computer Networks. These chapters carry high weightage in the CBSE board exam.
Feel free to give your feedback in the following feedback form and help us to improve: