12 TH Computer Science Python Unit-1 Notes
12 TH Computer Science Python Unit-1 Notes
[1] State True or False – ‘Tuple is one of the datatypes of python having data in key-value
pair.”
”Hide_Answer”
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.
a) %
b) in
c) #
d) **
”Hide_Answer”
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.
print(2**3**2)
a) 64
b) 256
c) 512
d) 32
”Hide_Answer”
Ans.: c) 512
Explanation: As per execution from the statement 3**2 – 9 and 2**9 is 512
a) eval
b) nonlocal
c) assert
d) pass
”Hide_Answer”
Ans. : a) eval
Explanation: eval is a function rest all three are keywords.
d_std={“Roll_No”:53,”Name”:’Ajay Patel’}
d_marks={“Physics”:84,”Chemistry”:85}
a) d_std + d_marks
b) d_std.merge(d_marks)
c) d_std.add(d_marks)
d) d_std.update(d_marks)
”Hide_Answer”
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?
print(data)
a) {‘A’:2000, ‘B’:2500, ‘C’:3000, ‘A’:4000}
”Hide_Answer”
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.
a) True
b) False
c) None
d) Null
”Hide_Answer”
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
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
”Hide_Answer”
Ans. b) True
Explanation:
True or not True and False
True or False and False
True or False
True
s=’CSTutorial@TutorialAICSIP’
o=s.partition(‘Tutorial’)
print(o[0]+o[2])
a) CSTutorial
b) CSTutorialAICSIP
c) CS@TutorialAICSIP
d)Tutorial@TutorialAICSIP
”Hide_Answer”
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
t = str.split(“program”)
print(t)
c) [‘My’,’ is’]
d) [‘My’]
”Hide_Answer”
a) “PYTHON”*2
b) “PYTHON” + “10”
c) “PYTHON” + 10
d) “PYTHON” + “PYTHON”
”Hide_Answer”
Ans.: c) “Python” + 10
Explanation: For string concatenation both operands should be string only. A string and number
is invalid combination.
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
”Hide_Answer”
Ans.: c) S3
Explanation: The tuple is assigned as value for the key salary which is immutable.
a) 30.0
b) 30.5
c) 30.6
d) 30.1
”Hide_Answer”
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
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
”Hide_Answer”
Ans.: (A) Both A and R are true and R is the correct explanaton for A
Watch this video for more understanding:
a) Conversion
b) Declaration
c) Calling of Function
d) Function Header
”Hide_Answer”
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.
a) Boolean
b) integers
c) strings
d) Class
”Hide_Answer”
Ans.: d) Class
Explanation: Core data types in python are boolean, integers and string.
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
”Hide_Answer”
4+3%5
a) 2
b) 6
c) 0
d) 7
”Hide_Answer”
Ans.: d) 7
Explanation: In this expression 3%5 will execute first. So the value is 3 only then 4 + 3=7.
”Hide_Answer”
[21] Which of the following statement(s) would give an error after executing the following
code?
a) Statement 3
b) Statement 4
c) Statement 5
d) Statement 4 and 5
”Hide_Answer”
Ans. b) Statement 4
Explanation: String is immutable object of python, Hence it does not allow this operation. Rest
all statements are correct.
”Hide_Answer”
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.
a) int
b) tuple
c) list
d) set
”Hide_Answer”
Ans.: a) int
Explanation: p stores only single number in paranthesis. Parantehsis with comma becomes tuple,
but only single number represents int in python.
a) else_if
b) for
c) pass
d) 2count
”Hide_Answer”
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.
Which of the following will be the correct output if the given expression is evaluated?
a) True
b) False
c)’5’
d)’bye’
”Hide_Answer”
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’
for i in "CS12":
print([i.lower()], end="#")
a) ‘c’#’s’#’1’#’2’#
b) [“cs12#’]
c) [‘c’]#[‘s’]#[‘1’]#[‘2’]#
(d) [‘cs12’]#
”Hide_Answer”
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?
a) Statement 2
b) Statement 4
c) Statement 1
d) Statement 3
”Hide_Answer”
Ans. b) Statement 4
print(25//4 +3**1**2*2)
a) 24
b)18
c) 6
d) 12
”Hide_Answer”
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.
a) (1,3,4)
b) (0,3,4)
c) (1,12,Error)
d) (1,3,#error)
”Hide_Answer”
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
(b) 144
(c) 121
(d) 1936
”Hide_Answer”
Ans. b) 144
Explanation:
Bracket off – 11**2 = 121
Now 23+121 =144
2marks
1. a) Given is a Python string declaration:
message='FirstPreBoardExam@2022-23'
d1={'rno':21, 'name':'Rajveer'}
d2={'name':'Sujal', 'age':17,'class':'XII-A'}
d2.update(d1)
print(d2.keys())
Ans.:
Steps:
a)
F i r s t P r e B o a r d E x a m@2 0 2 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:
a) 322ADORSF
b) dict_keys(['name', 'age', 'class', 'rno'])
dt=["P",10,"Q",30,"R",50]
t=0
a=""
ad=0
for i in range(1,6,2):
t = t + i
a = a + dt [i-1] + "@"
ad = ad + dt[i]
print (t, ad, a)
Ans.:
Steps:
Iteration Values
i=1
t=t+i
1 t=0+1=1
a=””+”P”+”@”=P@
ad=0+10=10
i=3
t=1+3=4
2
a=’P@’+’Q’+’@’=P@Q@
ad=10+30=40
i=5
t=4+5=9
3
a=’P@Q@’+’R’+’@’
ad=40+50=90
4 For Loop Ends
9 90 P@Q@R@
L=[11,22,33,44,55]
Lst=[]
for i in range(len(L)):
if i%2==1:
t=(L[i],L[i]*2)
Lst.append(t)
print(Lst)
Ans.:
Steps:
Iteration Values
0 Condition False
i=1
1 t=(22,44)
Lst=[(22,44)]
2 Condition False
3 i=3
t=(44,88)
Lst=[(22,44),(44,88)]
4 Condition False
5 For loop Ends
[(22, 44), (44, 88)]
str="PYTHON@LANGUAGE"
print(str[2:12:2])
data = [11,int(ord('a')),12,int(ord('b'))]
for x in data:
x = x + 10
print(x,end=' ')
Ans.:
Steps:
a)
PYTHON@LANG U A G E
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
T O @ A G
b)
Iteration Values
x=11
1
x=x+10=21
x=97
2
x=x+10=97+10=107
x=12
3
x=x+10=12+10=22
X=98
4
X=X+10=98+10=108
a) TO@AG
b) 21 107 22 108
5. Write the output of the following code and the difference between a*3 and (a,a,a)?
a=(1,2,3)
print(a*3)
print(a,a,a)
Ans.:
(1, 2, 3, 1, 2, 3, 1, 2, 3)
((1, 2, 3) (1, 2, 3) (1, 2, 3))
Difference:
a*3 will repeate the tuple 3 times where as (a,a,a) will repeat tuple 3 times into a separate tuple.
s="ComputerScience23"
n = len(s)
m=""
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:
Co m p ut e r Sc ie nc e 23
if: a-n M E CIE CE
elif: n-z C mpu e e
elif-upper c s
else ##
cCMmpuEesCIEeCE##
lst1=[39,45,23,15,25,60]
x=["rahul",5, "B",20,30]
x.insert(1,3)
x.insert(3, "akon")
print(x[2])
Ans.:
Steps:
a)
39 45 23 15 25 60
Index 0 1 2 3 4 5
Index(15) 3+2=5
b)
‘rahul’ 5 ‘B’ 20 30
index 0 123 4 5 6
insert 1 3
insert 2 akon
x[2] 5
a) 5
b) 5
Ans.:
p ython programmin g
if False
elif p yth True
else 4+1=5
pyth
5
9. Predict the output:
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.:
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))
def printMe(q,r=2):
p=r+q**3
print(p)
#main-code
a=10
b=5
printMe(a,b)
printMe(r=4,q=2)
Ans.:
a=10
b=5
printMe(10,5)
q=10
r=5
p=r+q**3
=5+10**3
=5+1000
=1005
printMe(4,2)
q=2
r=4
p=r+q**3
=4+2**3
=4+8
=12
Output:
1005
12
def foo(s1,s2):
l1=[]
l2=[]
for x in s1:
l1.append(x)
for x in s2:
l2.append(x)
return l1,l2
a,b=foo("FUN",'DAY')
print(a,b)
Ans:
a,b=foo("FUN","DAY")
foo('FUN','DAY')
l1=[]
l2=[]
for x in 'FUN':
l1.append(x)
So l1=['F','U','N']
for x im 'DAY':
l2.append(x)
So l2=['D','A','Y']
[6] Preety has written a code to add two numbers . Her code is having errors. Rewrite the
correct code and underline the corrections made.
def sum(arg1,arg2):
total=arg1+arg2;
print(”Total:”,total)
return total;
sum(10,20)
print(”Total:”,total)
Ans.:
def sum(arg1,arg2):
total=arg1+arg2 #Semicolon not required
print(”Total:”,total)
return total #Any one statement is enough either return or print
[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.:
[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:
But this code is not working, Can you help Ravi to identify the error in the above function
and what is the solution?
[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')
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
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:
Ans.:
def ThreeLetters(L):
l3=[]
for i in range(len(L)):
if len(L[i])==3:
l3.append(L[i])
l3.append(i)
return l3
[2] Write a function modifySal(lst) that accepts a list of numbers as an argument and
increases the value of the elements (basic) by 3% if the elements are divisible by 10. The
new basic must be integer values.
For example:
Ans.:
def modifySal(lst):
for i in range(len(lst)):
if lst[i]%10==0:
lst[i]=int(lst[i]+(lst[i]*0.03))
return lst
basic_li=[25000,15130,10135,12146,15030]
print(modifySal(basic_li))
[3] Write a function not1digit(li), where li is the list of elements passed as an argument to
the function. The function returns another list that stores the indices of all numbers except
1-digit elements of li.
For example:
If L contains [22,3,2,19,1,69]
Ans.:
def not1digit(li):
l=[]
for i in range(len(li)):
if li[i]>9:
l.append(li[i])
return l
li=[22,3,2,19,1,69]
print(not1digit(li))
[4] Write a function shiftLeft(li, n) in Python, which accepts a list li of numbers, and n is a
numeric value by which all elements of the list are shifted to the left.
def LeftShift(li,n):
li[:]=li[n:]+li[:n]
return li
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]
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:
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:
Ans.:
def reverseList(li):
rev_li=[]
for i in range(-1,-len(li)-1,-1):
rev_li.append(li[i])
return rev_li
l=[79,56,23,28,98,99]
print(reverseList(l))
[8] Write a function in python named Swap50_50(lst), which accepts a list of numbers and
swaps the elements of 1st Half of the list with the 2nd Half of the list, ONLY if the sum of
1st Half is greater than 2nd Half of the list.
l= [8, 9, 7,1,2,3]
Output = [1,2,3,8,9,7]
ddef Swap50_50(lst):
s1=s2=0
L=len(lst)
for i in range(0,L//2):
s1+=lst[i]
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.
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))
Find answer below for data file handling in python class 12.
Answers:
1. File
2. File Handling
3. I/O Operations
4. Data file
5. Text File
6. open(“data.txt”,”r”)
7. open(“data.txt”,”w”)
8. File handle or File Object
9. close
10. read(15)
11. readline()
12. readlines()
13. write()
14. writelines()
15. append
16. flush()
17. ASCII, UNICODE
18. CSV
19. open()
20. +
1 Every file has its own identity associated with it. Which is known as –
a. icon
b. extension
c. format
d. file type
a. .pdf
b. jpg
c. mp3
d. txp
a. File handle
b. File object
c. File Mode
d Buffer
a. End Of Line
b. End Of List
c. End of Lines
d. End Of Location
5. Which of the following file types allows to store large data files in the computer memory?
a. Text Files
b. Binary Files
c. CSV Files
6. Which of the following file types can be opened with notepad as well as ms excel?
a. Text Files
b. Binary Files
c. CSV Files
d. None of these
a. close
b. read
c. write
d. append
8. To read 4th line from text file, which of the following statement is true?
a. dt = f.readlines();print(dt[3])
b. dt=f.read(4) ;print(dt[3])
c. dt=f.readline(4);print(dt[3])
d. All of these
a. flush()
b. close()
c. open()
d. fflush()
10. Which of the following functions flushes the data before closing the file?
a. flush()
b. close()
c. open()
d. fflush()
Please refer notes section for the answers on Data file handling in python class 12.
The following section contains few case study based questions for Data file handling in python
class 12.
1. Write a python program to create and read the city.txt file in one go and print the contents on
the output screen.
Answer:
2. Consider following lines for the file friends.txt and predict the output:
Output:
Explanation:
In line no. 2, f.readline() function reads first line and stores the output string in l but not printed
in the code, then it moves the pointer to next line in the file. In next statement we have
f.readline(18) which reads next 18 characters and place the cursor at the next position i.e. comma
(,) , in next statement f.read(10) reads next 10 characters and stores in ch3 variable and then
cursor moves to the next position and at last f.readline() function print() the entire line.
3. Write a function count_lines() to count and display the total number of lines from the
file. Consider above file – friends.txt.
def count_lines():
f = open("friends.txt")
cnt =0
for lines in f:
cnt+=1
print("no. of lines:",cnt)
f.close()
4. Write a function display_oddLines() to display odd number lines from the text file.
Consider above file – friends.txt.
def display_oddLines():
f = open("friends.txt")
cnt =0
for lines in f:
cnt+=1
if cnt%2!=0:
print(lines)
f.close()
5. Write a function cust_data() to ask user to enter their names and age to store data in
customer.txt file.
def cust_data():
name = input("Enter customer name:")
age=int(input("Enter customer age:"))
data = str([name,age])
f = open("customer.txt","w")
f.write(data)
f.close()
[1] The _________ files are used to store large data such as images, video files, audio files etc.
–> Binary
[2] The process of converting the structure to a byte stream before writing to the file is known as
_________.
–> Pickling
[3] The process of converting byte stream back to the original structure is known as _______.
–> Unpickling
[4]A ______ module is used to store data into an python objects with their structure.
–> pickle
[5]A _______ function of pickle module is used to write data into binary as well as a
____________ function of pickle module is used to read data from binary file.
[6]The _____ file mode is used to handle binary file for reading.
–> rb
[7] The _____ file mode is used when user want to write data into binary file.
–> wb
–> appending
The next section of Important QnA binary files CS Class 12 will provides MCQ type questions.
MCQs
[1] Which of the following is not a correct statement for binary files?
[2] Which of the following file mode open a file for reading and writing both in the binary file?
a) r
b) rb
c) rb+
d) rwb
[3] Which of the following file mode opens a file for reading and writing both as well as
overwrite the existing file if the file exists otherwise creates a new file?
a) w
b) wb+
c) wb
d) rwb
[4] Which of the following file mode opens a file for append or read a binary file and moves the
files pointer at the end of the file if the file already exist otherwise create a new file?
a) a
b) ab
c) ab+
d) a+
[5] Ms. Suman is working on a binary file and wants to write data from a list to a binary file.
Consider list object as l1, binary file suman_list.dat, and file object as f. Which of the following
can be the correct statement for her?
a) f = open(‘sum_list’,’wb’); pickle.dump(l1,f)
b) f = open(‘sum_list’,’rb’); l1=pickle.dump(f)
c) f = open(‘sum_list’,’wb’); pickle.load(l1,f)
d) f = open(‘sum_list’,’rb’); l1=pickle.load(f)
[6] Which option will be correct for reading file for suman from q-5?
[7] In which of the file mode existing data will be intact in binary file?
a) ab
b) a
c) w
d) wb
a) import – pickle
b) pickle import
c) import pickle
[5] Compare how binary files are better than text files?
[6] Explain various file modes can be used with binary file operations.
[7] What is pickle module? How to import pickle module in python program?
[1] Ms. Sejal is working on the sports.dat file but she is confused about how to read data from
the binary file. Suggest a suitable line for her to fulfill her wish.
import pickle
def sports_read():
f1 = open("sports.dat","rb")
_________________
print(data)
f1.close()
sports_read()
[3] Improve above code and write the correct code to display all records from the file.
f1 = open("sports.dat","rb")
try:
while True:
dt = pickle.load(f1)
print(dt)
except Exception:
f1.close()
[2] Develop python code to insert records in g_meet.dat binary file until user press ‘n’. The
information is Google meeting id, google meeting time, and class.
f1 = open("g_meet.dat","ab")
while True:
gmeet_id=input("Enter id:")
gmeet_time=input("Enter time:")
gmeet_class =int(input("Enter google meet class:"))
rec={"Google Meeting id":gmeet_id,"Gogole Meet
Time":gmeet_time,"Google Meet Class":gmeet_class}
pickle.dump(rec,f1)
ch = input("Want more records:")
ch=ch.lower()
if ch=='n':
break
f1.close()
.CSV
[2] One row of CSV file can be considered as _______ in terms of database.
record
[3] The CSV files can be operated by __________ and ____________ software.
[5] A _____ function allows to write a single record into each row in CSV file.
writerow()
[6] The _________ parameter of csv.reader() function is used to set a specific delimiter like a
single quote or double quote or space or any other character.
dialect
[7] A ________ is a parameter of csv.reader() function that accpets the keyword arguments.
**fmtparams
[8] When you read csv file using csv.reader() function it returns the values in _______ object.
nested list
quoting
[10] You can specify a quote character using _______ through writer function.
quotechar
[11] The ____________ parameter instructs writer objects to only quote those fields which
contain special characters such as delimiter, quotechar or any of the characters in lineterminator.
csv.QUOTE_MINIMAL
csv.QUOTE_NONE
[13] If you want to change a default delimiter of csv file, you can specify ________ parameter.
delimiter
[14] CSV module allows to write multiple rows using ____________ function.
writerrows()
[1] Each row read from the csv file is returned as a list of strings.
True
True
False
[4] When csv.QUOTE_NONE is used with writer objects you have to specify the escapechar
option parameter to writerow() function.
True
False
[6] The quotechar function must be given any type of character to separate values.
True
True
[8] The write row function creates header row in csv file by default.
False
[9] You cannot insert multiple rows in csv file using python csv module.
False
[10] In csv file, user can insert text values and date values with single quote like MySQL.
True
MCQs/One word Answer Questions – CSV in Python class 12
1. Expand: CSV
o Comma Separated Value
2. Which of the following module is required to import to work with CSV file?
a. File
b. CSV
c. pandas
d. numpy
3. Which of the following is not a function of csv module?
0. readline()
1. writerow()
2. reader()
3. writer()
4. The writer() function has how many mandatory parameters?
0. 1
1. 2
2. 3
3. 4
5. Name the function which used to write a row at a time into CSV file.
o writerow()
6. Which of the following parameter needs to be added with open function to avoid blank row
followed file each row in CSV file?
0. qoutechar
1. quoting
2. newline
3. skiprow
7. Anshuman wants to separate the values by a $ sign. Suggest to him a pair of function and
parameter to use it.
0. open,quotechar
1. writer,quotechar
2. open,delimiter
3. writer, delimiter
8. Which of the following is tasks cannot be done or difficult with CSV module?
0. Data in tabular form
1. Uniqueness of data
2. Saving data permanently
3. All of these
9. Which of the following is by default quoting parameter value?
0. csv.QUOTE_MINIMAL
1. csv.QUOTE_ALL
2. csv.QUOTE_NONNUMERIC
3. csv.QUOTE_NONE
10. Which of the following is must be needed when csv.QUOTE_NONE parameter is used?
0. escapechar
1. quotechar
2. quoting
3. None of these
Descriptive Questions CSV in python class 12
1. Open()
2. reader()
3. writer()
4. writerow()
5. close()
1. import csv
2. from csv import *
1. reader()
2. writer()
3. writerow()
[4] Write python code to create a header row for CSV file “students.csv”. The column names are
: Adm.No, StudentName, City, Remarks
Creating a header row is one of the most important aspects of CSV in python class 12. Use the
following code to do so.
[5] Observe the following code and fill in the given blanks:
import csv
with _________ as f:
#1
r = csv.______(f)
#2
for row in ______:
#3
print(_____) #4
1. open(“data.csv”)
2. reader
3. r
4. row
[6 Write steps to print data from csv file in list object and support your answer with example.
[6] How to print following data for cust.csv in tabular form usig python code?
[7] Write code to insert multiple rows in the above csv file.
import csv
record = list()
custname= input("Please enter a customer name to delete:")
with open('cust.csv', 'r') as f:
data = csv.reader(f)
for row in data:
record.append(row)
for field in row:
if field == custname:
record.remove(row)
with open('cust.csv', 'w') as f:
writer = csv.writer(f)
writer.writerows(record)
[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:
He wants to be perfect.
The output after executing displayword() will be:
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:
INDIA is my country.
Ans.:
def displaywords():
f = open('data.txt','r')
s = f.read()
lst = s.split()
for x in lst:
if len(x)>3:
print(x, end=" ")
f.close()
[4] Write a function COUNT_AND( ) in Python to read the text file “STORY.TXT” and count
the number of times “AND” occurs in the file. (include AND/and/And in the counting)
Ans.:
def COUNT_AND( ):
c=0
f=open(‘STORY.TXT','r')
dt = f.read()
w = dt.split()
for i in w:
if i.lower()=='and':
c=c+1
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)
[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:
Read the questions given below and fill in the gaps accordingly: 1 + 1 + 2
”Hide_Answer”
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:
”Show_Answer”
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:
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.
1. He now has to update a record based on the employee id entered by the user and update
the salary. The updated record is then to be written in the file temp.dat.
2. The records which are not to be updated also have to be written to the file temp.dat.
3. If the employee id is not found, an appropriate message should to be displayed.
As a Python expert, help him to complete the following code based on the requirement given
above:
import_______ #Statement 1
def update_data():
rec={}
fin=open("emprecords.dat","rb")
fout=open("_____________") #Statement2
found=False
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()
”Show_Answer”
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.
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.
”Hide_Answer”
Ans.:
1. csv
2. csvwriter.writerows(dt)
3. next(csvreader)
4. csvreader
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.:
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()
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.:
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()
def search():
f=open("emp.csv",'r')
ro=csv.reader(f)
for i in ro:
if float(i[2])>40000:
print(i)
f.close()
Function Calling:
add()
search()
[3] What is delimiter in CSV file? Write a program in python that defines and calls the following
user defined function:
i) Add() – To accept data and add data of employee to a CSV file ‘record.csv’. Each record
consists of a list with field elements as empid, name and mobile to store employee id, employee
name and employee salary.
ii) CountR():To count number of records present in CSV file named ‘record.csv’.
Ans.:
Delimiter refers to a character used to separate the values or lines in CSV file. By default
delimiter for CSV file values is a comma and the new line is ‘\n’. Users can change it anytime.
[4] Give any one point of difference between a text file and csv file. Write a python program
which defines and calls the following functions:
i) add() – To accept and add data of a furniture to a csv file ‘furdata.csv’. Each record consists of
a list with field elements such as fid, name and fprice to store furniture id, furniture name and
furniture price respectively.
ii) search() – To display records of sofa whose price is more than 12000.
Ans.:
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()
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.
1. What module should be imported in #Line1 for successful execution of the program?
2. In which mode file should be opened to work with user.csv file in#Line2
3. Fill in the blank in #Line3 to read data from csv file
4. Fill in the blank in #Line4 to close the file
5. Write the output he will obtain while executing Line5
Ans.:
1. csv
2. ‘a’
3. reader
4. close
5. Output:
['Aditya'.'987@555']
['Archi','arc@maj']
['Krish','Krisha@Patel']
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
”Hide_Answer”
Ans. c) Underflow
[2] ____________ is an effective and reliable way to represent, store, organize and manage data
in systematic way.
”Hide_Answer”
a) Information
b) Data
c) Data Structure
d) Abstract Data
”Hide_Answer”
Ans. b) Data
[4] ____________ represents single unit of certain type.
a) Data item
b) Data Structure
c) Raw Data
d) None of these
”Hide_Answer”
[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.
”Hide_Answer”
[6] Which of the following python built in type is mostly suitable to implement stack?
a) dictionary
b) set
c) tuple
d) list
”Hide_Answer”
Ans.: d) list
[7] The Data Structures can be classified into which of the following two types?
”Hide_Answer”
”Hide_Answer”
a) Stack
b) Queue
c) Linked List
d) Tree
”Hide_Answer”
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
”Hide_Answer”
[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
”Hide_Answer”
Ans. : a) Stack
[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
”Hide_Answer”
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
”Hide_Answer”
Ans. b) pop
a) front
b) top
c) middle
d) bottom
”Hide_Answer”
Ans. b) top
”Hide_Answer”
a) push
b) pop
c) peek
d) underflow
”Hide_Answer”
Ans. c) peek
[11,20,45,67,23]
push(19)
pop()
push(24)
pus(42)
pop()
push(3)
a) [11,20,45,67,23]
b) [3,24,11,20,67,23]
c) [42,24,11,20,67,23]
d) [24,11,20,67,23]
a) FILO
b) FIFO
c) FOFI
d) LOFI
”Hide_Answer”
Ans.: a) FILO
11
22
23
34
91
34
91
a) delete()
b) pop()
c) remove()
d) clear()
”Hide_Answer”
Ans. b) pop()
Most expected 2 marks Most expected questions Stack Computer Science Class
12
”Hide_Answer”
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
”Hide_Answer”
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?
”Hide_Answer”
”Hide_Answer”
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.
”Hide_Answer”
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?
”Hide_Answer”
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.
”Hide_Answer”
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.
”Hide_Answer”
”Hide_Answer”
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.
”Hide_Answer”
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:
1. STACK.pop( )
2. STACK.append(99)
3. STACK.append(87)
4. STACK.pop( )
”Hide_Answer”
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]
”Hide_Answer”
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
”Hide_Answer”
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
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
”Hide_Answer”
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
1. 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.
R={“OM”:35,”JAI”:40,”BOB”:53,”ALI”:66,”ANU”:19}
ANU OM
R={"OM":35,"JAI":40,"BOB":53,"ALI":66,"ANU":19}
def Push(stk,n):
stk.append(n)
def Pop(stk):
if stk!=[]:
return stk.pop()
else:
return None
s=[]
for i in R:
if R[i]<40:
Push(s,i)
while True:
if s!=[]:
print(Pop(s),end=" ")
else:
break
4. SHEELA has a list containing 5 integers. You need to help Her create a program with
separate user defined functions to perform the following operations based on this list.
1. Traverse the content of the list and push the odd numbers into a stack.
2. Pop and display the content of the stack.
For Example:
If the sample Content of the list is as follows:
N=[79,98,22,35,38]
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:
1. Push the keys (name of the student) of the dictionary into a stack, where the
corresponding value (marks) is greater than 75.
2. Pop and display the content of the stack.
For example:
The output from the program should be: TOM ANU BOB OM
def Pop(stk):
if stk!=[]:
return stk.pop()
else:
return None
s=[]
for i in R:
if R[i]>75:
Push(s,i)
while True:
if s!=[]:
print(Pop(s),end=" ")
else:
break
8. Raju has created a dictionary containing employee names and their salaries as key value
pairs of 6 employees. Write a program, with separate user defined functions to perform the
following operations:
1. Push the keys (employee name) of the dictionary into a stack, where the
corresponding value (salary) is less than 85000.
2. Pop and display the content of the stack.
For example:
def Push(stk,sal):
stk.append(sal)
def Pop(stk):
if stk==[]:
return None
else:
return stk.pop()
stk=[]
for i in Emp:
if Emp[i]<85000:
Push(stk,i)
while True:
if stk!=[]:
print(Pop(),end=" ")
else:
break
9. Anjali has a list containing temperatures of 10 cities. You need to help her create a program
with separate user-defined functions to perform the following operations based on this list.
1. Traverse the content of the list and push the negative temperatures into a stack.
2. Pop and display the content of the stack.
For Example:
def Push(s,n):
s.append(n)
def Pop(s):
if s!=[]:
return s.pop()
else:
return None
s=[]
for i in T:
if i<0:
Push(s,i)
while True:
if s!=[]:
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.
def DoPush(elt):
L= [2,5,6,11,18,24,32,37,42,47]
for i in L:
for j in range(2,i):
if i % j ==0:
break
else:
elt.append(i)
def DoPop(s):
if s!=[]:
return s.pop()
else:
return None
s=[]
DoPush(s)
while True:
if s!=[]:
print(DoPop(s),end=" ")
else:
break
11. Mr. Ramesh has created a dictionary containing Student IDs and Marks as key value
pairs of students. Write a program to perform the following operations Using separate user
defined functions.
1. Push the keys (IDs) of the dictionary into the stack, if the corresponding marks is
>50
2. Pop and display the content of the stack
Do Yourself…
12. Write AddNew (Book) and Remove(Book) methods in Python to add a new Book and
Remove a Book from a List of Books Considering them to act as PUSH and POP
operations of the data structure Stack?
def AddNew(Book):
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:
1. Push the keys (Name of Region Office) of the dictionary into a stack, where the
corresponding value (Number of Nodal Centre Schools) is more than 100.
2. Pop and display the content of the stack.
For example
Do yourself…
14. Write a function in Python PUSH (Lst), where Lst is a list of numbers. From this list
push all numbers not divisible by 7 into a stack implemented by using a list. Display the
stack if it has at least one element, otherwise display appropriate error message.
def PUSH(Lst):
stk=[]
for i in range(len(Lst)):
if Lst[i]%7==0:
stk.append(Lst[i])
if len(stk)==0:
print("Stack is underflow")
else:
print(stk)
15. Write a function in Python POP(Lst), where Lst is a stack implemented by a list of
numbers. The function returns the value deleted from the stack.
def POP(Lst):
if len(stk)==0:
return None
else:
return Lst.pop()
16. Reva has created a dictionary containing Product names and prices as key value pairs
of 4 products. Write a user defined function for the following:
PRODPUSH() which takes a list as stack and the above dictionary as the parameters. Push the
keys (Pname of the product) of the dictionary into a stack, where the corresponding price of the
products is less than 6000. Also write the statement to call the above function.
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:
1. Input the Book No, BookName and BookPrice from the user and Push into the
stack.
2. Display the status of stack after each insertion.
def Push():
books=[]
stk=[]
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)
>>> mydict={9446789123:”Ram”,8889912345:”Sam”,7789012367:”Sree”}
>>> push(mydict)
Phone number: 9446789123 last digit is less than five which can’t be pushed
mydict={9446789123:"Ram",8889912345:"Sam",7789012367:"Sree"}
def Push(mydict):
stk=[]
for i in mydict:
if i%10>=5:
stk.append(i)
print(stk)
Push(mydict)
19. Write a function to push an element in a stack which adds the name of passengers on a
train, which starts with capital ‘S’. Display the list of passengers using stack.
L = ['Satish','Manish','Sagar','Vipul']
def Push(L,name):
L.append(name)
stk=[]
for i in L:
if i[0]=='S':
Push(stk,i)
print(stk)
20. In a school a sports club maintains a list of its activities. When a new activity is added
details are entered in a dictionary and a list implemented as a stack. Write a push() and
pop() function that adds and removes the record of activity. Ask user to entre details like
Activity, Type of activity, no. of players required and charges for the same.
Do Yourself…