0% found this document useful (0 votes)
120 views

Python Revision Material - CH.1,2.3.5.9

The document contains questions about Python programming concepts like functions, variables, operators, errors etc. The questions are about identifying errors, correcting code snippets, evaluating expressions, expanding acronyms and more. Answers are also provided for some questions.

Uploaded by

Hemnathpalani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
120 views

Python Revision Material - CH.1,2.3.5.9

The document contains questions about Python programming concepts like functions, variables, operators, errors etc. The questions are about identifying errors, correcting code snippets, evaluating expressions, expanding acronyms and more. Answers are also provided for some questions.

Uploaded by

Hemnathpalani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

1.

QUESTIONS - GENERAL THEORY


1. Differentiate between the round( ) and floor( ) functions with the help of suitable example.
2. Which string method is used to implement the following:
a. To count the number of characters in the string
b. To change the first character of the string in capital letter
c. To change lowercase to uppercase letter
d. To check whether the given character is letter or a number
3. What are default arguments?
4. What is the difference between actual and formal parameters?
6. What is the difference between built-in functions and modules?
7. What is the difference between local variable and global variable?
8. What are the advantages of writing functions with keyword arguments?
9. What do you mean by scope of variables?
10. Which of the following is valid arithmetic operator in Python:
(i)// (ii)? (iii)< (iv)and
11. Write the type of tokens from the following:
(i) if (ii) roll_no
12. Which of the following are valid operators in Python:
(i) ** (ii) */ (iii) like (iv) ||
(v) is (vi) ^ (vii) between (viii) in
13. Which of the following can be used as valid variable identifier(s) in Python?
(i) 4thSum (ii) Total
(iii) Number# (iv) _Data
14. Rearrange the following operators in Highest to Lowest Priority.
% , or, ==, not, =
15. Find the invalid identifier from the followings:
a) File_name, b) sl1, c) False, d) num34
16. Which of the following is not a valid identifier name in Python? Justify reason for it not being
a valid name.
a) 5Total b) _Radius c) pie d)While
17. Which of the following is not a valid identifier in Python?
a) KV2 b) _main c) Hello_Dear1 d) 7 Sisters
18. Which of the following are valid operators in Python:
(i) * (ii) between (iii) like (iv) ||
19. Which of the following are valid operator in Python:
(i) */ (ii) is (iii) ^ (iv) like
20. How would you write x -4x in python
y 9

21. Name the Python Library modules which need to be imported to invoke the following
functions: (i) ceil( ) (ii) randrange( )
22. What will be the output of the following expression: print(24//6%3, 24//4//2, 20%3%2)
23. Evaluate following expressions:
a) 18 % 4 ** 3 // 7 + 9
b) 2 > 5 or 5 == 5 and not 12 <= 9
c) 16%15//16
d) 51+4-3**3//19-3
e) 17<19 or 30>18 and not 19==0
24. Expand the following terms:
a. HTML b. ITA c. SIP d. GSM
e. PPP f. PAN g. POP3 h. FTP

84
SOLUTIONS: GENERAL THEORY
Ans1. The round( ) function is used to convert a fractional number into whole as the nearest next
whereas the floor( ) is used to convert to the nearest lower whole number.
E.g. round(5.8) = 6 and floor(5.8)= 5

Ans2. a. len(str) b. str.capitalize( ) c. str.upper( ) d. ch.isalnum( )

Ans3. Default arguments are used in function definition, if the function is called without the argument,
the default argument gets its default value.

Ans 4. Actual parameters are those parameters which are used in function call statement and formal
parameters are those parameters which are used in function header (definition).
e.g. def sum(a,b): # a and b are formal parameters
return a+b
x, y = 5, 10
res = sum(x,y) # x and y are actual parameters

Ans 6: Built in functions can be used directly in a program in python, but in order to use modules, we have
to use import statement to use them.
Ans 7.
Sno. LOCAL VARIABLE GLOBAL VARIABLE
1 It is a variable which is declared within a It is a variable which is declared outside
function or within a block. all the functions.
2 It is accessible only within a function/ block in It is accessible throughtout the
which it is declared. program.
For example,
def change():
n=10 # n is a local variable
x=5 # x is a global variable
print( x)
Ans 8. i) using the function is easier as we do not need to remember the order of the arguments.
ii) we can specify values of only those parameters which we want to give, as other parameters
have default argument values
Ans9. Scope of variables refers to the part of the program where it is visible, i.e, the area where you can
use it
Ans10. (i)

Ans 11. i) Keyword ii) identifier


Ans 12. i) iv) vi) viii)
Ans 13. ii) and iv)
Ans 14. %, ==, not, or, =
Ans 15. c)False
Ans 16. a) 5Total Reason: An identifier cannot start with a digit
Ans 17. d) 7 Sisters
Ans 18. (iv) ||
Ans 19. Valid operators are : (ii) is (iii) ^
Ans 20. Math.pow(x,y) – 4 * math.pow(x,9)
Ans 21. i) math (ii) random
Ans 22. (1,3,0)
Ans. 23. a) 11 b) True c) 0 d) 51 e) True
Ans 24. a. PHP-Hypertext Text markup Language
b. ITA-Information Technology Act
c. SIP- Session Initiation Protocol
d. GSM-Global system for mobile communication
e. PPP: Point to Point Protocol
f. PAN; Personal Area Network
g. POP3: Post Office Protocol version 3
h. FTP: File Transfer Protocol

85
2. QUESTIONS - ERROR FINDING
Q1. Find error in the following code(if any) and correct code by rewriting code and
underline the correction;-
x= int(“Enter value of x:”)
for y in range [0,10]:
if x=y
print( x + y)
else:
print( x-y)

Q2. Rewrite the following program after finding and correcting syntactical errors and
underlining it.
a, b = 0
if (a = b)
a +b = c
print(c)

Q3. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
250 = Number
WHILE Number<=1000:
if Number=>750
print (Number)
Number=Number+100
else
print( Number*2)
Number=Number+50
Q4. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
Val = int(rawinput("Value:"))
Adder = 0
for C in range(1,Val,3)
Adder+=C
if C%2=0:
Print (C*10)
Else:
print (C*)
print (Adder)

Q5. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
25=Val
for I in the range(0,Val)
if I%2==0:
print( I+1):
Else:
print [I-1]

Q6. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
STRING=""WELCOME
NOTE""
for S in range[0,8]:
print (STRING(S))

86
Q7. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
a=int{input("ENTER FIRST NUMBER")}
b=int(input("ENTER SECOND NUMBER"))
c=int(input("ENTER THIRD NUMBER"))
if a>b and a>c
print("A IS GREATER")
if b>a and b>c:
Print(" B IS GREATER")
if c>a and c>b:
print(C IS GREATER)

Q8. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
i==1
a=int(input("ENTER FIRST NUMBER"))
FOR i in range[1, 11];
print(a,"*=", i ,"=",a * i)

Q9. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
a=”1”
while a>=10:
print("Value of a=",a)
a=+1

Q10. 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)

Q11. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
weather='raining'
if weather='sunny':
print("wear sunblock")
elif weather='snow':
print("going skiing")
else:
print(weather)

Q12. Write the modules that will be required to be imported to execute the following
code in Python.
def main( ):
for i in range (len(string)) ):
if string [i] = = ‘’ “
print
else:
c=string[i].upper()
print( “string is:”,c)
print (“String length=”,len(math.floor()))
87
Q13. Observe the following Python code very carefully and rewrite it after removing all
syntactical errors with each correction underlined.

DEF execmain():
x = input("Enter a number:")
if (abs(x)=x):
print ("You entered a positive number")
else:
x=*-1
print "Number made positive:"x
execmain()

Q14. Rewrite the following code in python after removing all syntax error(s).Underline
each correction done in the code
x=integer(input('Enter 1 or 10'))
if x==1:
for x in range(1,11)
Print(x)
Else:
for x in range(10,0,-1):
print(x)

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

30=To
for K in range(0,To)
IF k%4==0:
print (K*4)
else
print (K+3)

SOLUTIONS : ERROR FINDING


Ans 1. Correct code:-
x= int(input(“Enter value of x:”))
for y in range (0,10):
if x==y:
print( x+y)
else:
print (x-y)

Ans 2. a,b = 0,0


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

Ans 3. Number = 250


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

88
Ans 4. Val = int(raw_input("Value:")) # Error 1
Adder = 0
for C in range(1,Val,3) : # Error 2
Adder+=C
if C%2==0 : # Error 3
print( C*10 ) # Error 4
else: # Error 5
print (C ) # Error 6
print(Adder)

Ans 5. Val = 25 #Error 1


for I in range(0,Val): #Error 2 and Error 3
if I%2==0:
print (I+1)
else: #Error 4
print (I-1)

Ans 6. CORRECTED CODE:-


STRING= "WELCOME"
NOTE=" "
for S in range (0, 7) :
print (STRING [S])

Also range(0,8) will give a runtime error as the index is out of range. It shouldbe range(0,7)

Ans 7. a=int(input("ENTER FIRST NUMBER"))


b=int(input("ENTER SECOND NUMBER"))
c=int(input("ENTER THIRD NUMBER"))
if a>b and a>c:
print("A IS GREATER")
if b>a and b>c:
print(" B IS GREATER")
if c>a and c>b:
print(" C IS GREATER ")

Ans 8. CORRECTED CODE

i=1
a=int(input("ENTER FIRST NUMBER"))
for i in range(1,11):
print(a,"*=",i,"=",a*i)

Ans 9. CORRECTED CODE

a=1
while a<=10:
print("Value of a=",a)
a+=1

Ans 10. CORRECTED CODE


Num=int(input("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)
89
Ans. 11 Corrected Code
weather='raining'
if weather=='sunny':
print("wear sunblock")
elif weather=='snow':
print("going skiing")
else:
print(weather)

Ans.12. Math module and String module

Ans 13. Corrected code:


def execmain():
x= input("Enter a number:") (indentation)
if(abs(x)== x):
print("You entered a positive number")
else:
x *= -1(indentaion)
print("Number made positive:" , x)
execmain()

Ans-14. x=int(input('Enter 1 or 10'))


if x==1:
for x in range(1,11):
print(x)
else:
for x in range(10,0,-1):
print(x)(indentation)

Ans 15. To=30


for K in range(0,To) :
if k%4==0:
print (K*4)
else:
print (K+3)

QUESTIONS - FIND THE OUTPUT


Q1. Find output generated by the following code:
p=10
q=20
p*=q//3
q+=p=q**2
print(p, q)

Q2. Find output generated by the following code:


Str=”Computer”
Str=Str[-4:]
print(Str*2)

Q3. Find out the output of the Following –


x=20
x=x+5
x=x-10
print (x)
x, y=x-1,50
print (x, y)

90
Q4. Find out the output of the Following –
for a in range(3,10,3):
for b in range(1,a,2):
print(b, end=’ ‘)
print( )

Q5. FIND OUTPUT OF FOLLOWING


x=10
y=5
for i in range(x-y*2):
print("%",i)

Q6. Find output generated by the following code:


x="one"
y="two"
c=0
while c<len(x):
print(x[c],y[c])
c=c+1

Q7. Find output generated by the following code:


for i in range(-1,7,2):
for j in range(3):
print(i,j)

Q8. Find output generated by the following code:


string=”aabbcc”
count=3
while True:
if string[0]=='a':
string=string[2:]
elif string[-1]=='b':
string=string[:2]
else:
count+=1
break
print(string)
print(count)

Q9. Find output generated by the following code:


x="hello world"
print(x[:2],x[:-2],x[-2:])
print(x[6],x[2:4])
print(x[2:-3],x[-4:-2])

Q10. Find and write the output of the following python code:
Msg1="WeLcOME"
Msg2="GUeSTs"
Msg3=""
for I in range(0,len(Msg2)+1):
if Msg1[I]>="A" and Msg1[I]<="M":
Msg3=Msg3+Msg1[I]
elif Msg1[I]>="N" and Msg1[I]<="Z":
Msg3=Msg3+Msg2[I]
else:
Msg3=Msg3+"*"
print (Msg3)
91
Q11. Find and write the output of the following python code :
def Changer(P,Q=10):
P=P/Q
Q=P%Q
print (P,"#",Q)
return P
A=200
B=20
A=Changer(A,B)
print (A,"$",B)
B=Changer(B)
print (A,"$",B)
A=Changer(A)
print (A,"$",B)

Q12. Find and write the output of the following python code:
Data = ["P",20,"R",10,"S",30]
Times = 0
Alpha = ""
Add = 0
for C in range(1,6,2):
Times= Times + C
Alpha= Alpha + Data[C-1]+"$"
Add = Add + Data[C]
print (Times,Add,Alpha)

Q13. Find and write the output of the following python code:
Text1="AISSCE 2018"
Text2=""
I=0
while I<len(Text1):
if Text1[I]>="0" and Text1[I]<="9":
Val = int(Text1[I])
Val = Val + 1
Text2=Text2 + str(Val)
elif Text1[I]>="A" and Text1[I] <="Z":
Text2=Text2 + (Text1[I+1])
else:
Text2=Text2 + "*"
I=I+1
print (Text2)

Q14. Find and write the output of the following python code:
TXT = ["20","50","30","40"]
CNT = 3
TOTAL = 0
for C in [7,5,4,6]:
T = TXT[CNT]
TOTAL = float (T) + C
print(TOTAL)
CNT-=1

92
Q15. Find output generated by the following code:
line = "I'll come by then."
eline = ""
for i in line:
eline += chr(ord(i)+3)
print(eline)

Q16. Find output generated by the following code:


line = "What will have so will"
L = line.split('a')
for i in L:
print(i, end=' ')

Q17. Find output generated by the following code:


p=5/2
q=p*4
r=p+q
p+=p+q+r
q-=p+q*r
print(p,q,r)

Q18. Find output generated by the following code:


a=(2 + 3) ** 3 – 6 / 2
b=(2 + 3) * 5// 4 + (4 + 6) / 2
c=12 + ( 3 * 4 – 6 ) / 3
d=12 % 5 * 3 + (2 * 6) // 4
print(a, b, c, d)

Q19. Find the output of the following:


def main( ) :
Moves=[11, 22, 33, 44]
Queen=Moves
Moves[2]+=22
L=len(Moves)
for i in range (L):
print ("Now@", Queen[L-i-1], "#", Moves [i])
main()
Q20. Find the output of the following
L1 = [100,900,300,400,500]
START = 1
SUM = 0
for C in range(START,4):
SUM = SUM + L1[C]
print(C, ":", SUM)
SUM = SUM + L1[0]*10
print(SUM)
Q21. Find and write the output of the following python code:
def fun(s):
k=len(s)
m=" "
for i in range(0,k):
if(s[i].isupper()):
m=m+s[i].lower()
elif s[i].isalpha():
m=m+s[i].upper()
else:
93
m=m+'bb'
print(m)
fun('school2@com')
Q22. Find the output of the give program :
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)

Q23. Find the output of the give program :


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

SOLUTION : FIND THE OUTPUT


1. Output:- 60, 480 2. ANS uteruter
‘ComputerComputer’
3. ANS: 15 ANS 4: 1
14, 50 1 4
1 4 7
ANS 5:- NO OUTPUT Ans 6.: ot
nw
eo

ANS 7: -1 0 Ans. 8 bbcc


-1 1 4
-1 2
10
11
12
30
31
32
50
51
52

Ans 9: he hello wor ld ANS 10. G*L*TME


w ll
llo wo or

Ans 11. 10 # 10 Ans 12- 1 20 P$


10 $ 20 4 30 P$R$
2 # 2 9 60 P$R$S$
10 $ 2
1 # 1
1 $ 2

Ans 13.- ISSCE*3129 ANS 14. 47.0


94
35.0
54.0
26.0
ANS 15. L*oo#frph#e|#wkhq1 ANS 16. Wh t will h ve so will
Ans 17. (27.5 - 142.5 12.5) Ans 18. (122.0 11.0 14.0 9)
Ans 19. Now @ 44 # 11 Ans 20. 1:900
Now @ 55 # 22 1900
Now @ 22 # 55 3200
Now @ 11 # 44 3:3600
4600
Ans 21. SCHOOLbbbbCOM Ans 22. 250 #150
250 #100
130 #100

Ans 23. -- aaaaaa OR infiniteloop

QUESTIONS: BASED ON TUPLE


Q1: Find the output of following codes

1. t1=("sun","mon","tue","wed")
print(t1[-1])

2. t2=("sun","mon","tue","wed","thru","fri")
for i in range (-6,2):
print(t2[i])

3. t3=("sun","mon","tue","wed","thru","fri")
if "sun" in t3:
for i in range (0,3):
print(t2[i])
else:
for i in range (3,6):
print(t2[i])

4. t4=("sun", "mon", "tue", "wed", "thru", "fri")


if "sun" not in t4:
for i in range (0,3):
print(t4[i])
else:
for i in range (3,6):
print(t4[i])

5. t5=("sun",2,"tue",4,"thru",5)
if "sun" not in t4:
for i in range (0,3):
print(t5[i])
else:
for i in range (3,6):
print(t5[i])

6. t6=('a','b')

95
t7=('p','q')
t8=t6+t7
print(t8*2)
7. t9=('a','b')
t10=('p','q')
t11=t9+t10
print(len(t11*2))

8. t12=('a','e','i','o','u')
p, q, r, s, t=t12
print("p= ",p)
print("s= ",s)
print("s + p", s + p)

9. t13=(10,20,30,40,50,60,70,80)
t14=(90,100,110,120)
t15=t13+t14
print(t15[0:12:3])

Q2. Find the errors


1. t1=(10,20,30,40,50,60,70,80)
t2=(90,100,110,120)
t3=t1*t2
Print(t5[0:12:3])

2. t1=(10,20,30,40,50,60,70,80)
i=t1.len()
Print(T1,i)

3. t1=(10,20,30,40,50,60,70,80)
t1[5]=55
t1.append(90)
print(t1,i)

4. t1=(10,20,30,40,50,60,70,80)
t2=t1*2
t3=t2+4
print t2,t3

5. t1=(10,20,30,40,50,60,70,80)
str=””
str=index(t1(40))
print(“index of tuple is ”, str)
str=t1.max()
print(“max item is “, str)

SOLUTION: OUTPUTS TUPLES


1. wed 2. sun
mon
tue
wed
thru
fri
sun
mon
96
3. sun 4. wed
Mon thru
Tue fri

5. 4 6. (‘a’, ‘b’, ‘p’, ‘q’, ‘a’, ‘b’, ‘p’, ‘q’)


thru
5
7. 8 8. p= a
s= o
s + p oa
9. 10, 40, 70, 100

Q2. TUPLES : FIND THE ERRORS


Ans 1 a. ti*t2 cant multiply
b. P is in uppercase in print command
c. t5 is not defined
Ans 2 a. len() is used wrongly
b. P is in uppercase in print command
c. T1 is not defined
Ans 3 a. 'tuple' object does not support item assignment in line 2
b. Append() Method is not with tuple

Ans. 4 a) line 3 cannot concatenate with int


b) Parenthesis is missing in line 4

Ans 5 a. Syntax error in index function


b. Syntax error in max function

QUESTION: BASED ON LIST


Q1. Give the output of the following code:-
list=['p','r','o','b','l','e','m']
list[1:3]=[]
print(list)
list[2:5]=[]
print(list)
Q2. Give the output of the following code:-
l1=[13,18,11,16,13,18,13]
print(l1.index(18))
print(l1.count(18))
l1.append(l1.count(13))
print(l1)
Q3. Find the error in following code. State the reason of the error.
aLst = { ‘a’:1 ,’ b’:2, ‘c’:3 }
print (aLst[‘a’,’b’])
Q4. Find the error in following code. State the reason of the error.
list1 =[1998, 2002, 1997, 2000]
list2 =[2014, 2016, 1996, 2009]
print"list1 + list 2 = : ", list1 +list2 #statement 1
print"list1 * 2 = : ", list1 *2 #statement 2
Q5. What is the output of the following:?
list1 = [1, 2, 3, 4, 5]
list2 =list1
97
list2[0] =0;
print("list1= : ", list1)

Q6. What is the output of the following:


data =[2, 3, 9]
temp =[[x forx in[data]] forx inrange(3)]
print(temp)
a) [[[2, 3, 9]], [[2, 3, 9]], [[2, 3, 9]]] b) [[2, 3, 9], [2, 3, 9], [2, 3, 9]]
c) [[[2, 3, 9]], [[2, 3, 9]]] d) None of these
Q7. What is the output of the following:?
Temp =[‘Geeks’, ‘for’, ‘Geeks’]
arr =[i[0].upper() for i in temp]
print(arr)
a) [‘G’, ‘F’, ‘G’] b) [‘GEEKS’]
c) [‘GEEKS’, ‘FOR’, ‘GEEKS’] d) Compilation error
Q8. What will be the output?

1. d1 ={"john":40, "peter":45}
2. d2 ={"john":466, "peter":45}
3. d1 > d2
a) True b) False
c) ERROR d) None
Q9. What will be the error of the following code Snippet?
Lst =[1,2,3,4,5,6,7,8,9]
Lst[::2]=10,20,30,40,50,60
Print[Lst]

Q10. Find the error in following code. State the reason of the error
aLst={‘a’:1,’b’:2,’c’:3}
print(aLst[‘a’,’b’])

Q11. What will be the output of the following Code Snippet?


a =[1,2,3,4,5]
print(a[3:0:-1])
A. Syntax error B. [4, 3, 2]
C. [4, 3] D. [4, 3, 2, 1]

Q12. What will be the output of the following Code Snippet?


fruit_list1 = ['Apple', 'Berry', 'Cherry', 'Papaya']
fruit_list2 = fruit_list1
fruit_list3 = fruit_list1[:]
fruit_list2[0] = 'Guava'
fruit_list3[1] = 'Kiwi'
sum = 0
for ls in (fruit_list1, fruit_list2, fruit_list3):
if ls[0] == 'Guava':
sum += 1
if ls[1] == 'Kiwi': A. 22 B. 21
sum += 20 C. 0 D. 43
print (sum)

98
Q13. What will be the output of the following Code Snippet?
a = {(1,2):1,(2,3):2}
print(a[1,2])
A. Key Error B. 1 C. {(2,3):2} D. {(1,2):1}

Q14. What will be the output of the following Code Snippet?


my_dict = {}
my_dict[1] = 1
my_dict['1'] = 2
my_dict[1.0] = 4
sum = 0
for k in my_dict: A. 7 B. Syntax error
sum += my_dict[k]
C. 3 D. 6
print (sum)

Q15. What will be the output of the following Code Snippet?


my_dict = {}
my_dict[(1,2,4)] = 8 A. Syntax error
my_dict[(4,2,1)] = 10 B. 30
my_dict[(1,2)] = 12 {(1, 2): 12, (4, 2, 1): 10, (1, 2, 4): 8}
sum = 0 C. 47
for k in my_dict: {(1, 2): 12, (4, 2, 1): 10, (1, 2, 4): 8}
sum += my_dict[k] D. 30
print (sum) {[1, 2]: 12, [4, 2, 1]: 10, [1, 2, 4]: 8}
print(my_dict)

SOLUTIONS: BASED ON LIST

Ans.1 [‘p’,’b’,’l’,’e’,’m’] Ans. 2 1


[‘p’,’b’] 2
[13,18,11,16,13,18,13,3]
Ans 3: The above code will produce KeyError, the reason being that there is no key same as the list [‘a’,’b’]

Ans 4. list1 + list 2 = : [1998, 2002, 1997, 2000, 2014, 2016, 1996, 2009]
list1 * 2 = : [1998, 2002, 1997, 2000, 1998, 2002, 1997, 2000]

Ans 5. List1:[0,2,3,4,5] Ans 6. (a)


Explanation: [x for x in[data] returns a new list copying the values in the list data and the outer for
statement prints the newly created list 3 times.

Ans7. a Ans 8. Type Error

Ans 9. ValueError: attempt to assign sequence of size 6 to extended slice of size 5

Ans 10. The above code produce KeyError, the reason being that there is no key same as the
list[‘a’,’b’] in dictionary aLst

Ans 11. B Ans 12. A

Ans 13. B Ans 14. D

Ans 15. B

99
QUESTIONS : FUNCTIONS - OUTPUT AND ERROR

QA. Identify the errors, underline it and correct the errors


a) Def Sum(a=1,b)
return a+b
print (“The sum =” Sum(7, -1)

b) def main ( )
print ("hello")

c) def func2() :
print (2 + 3)
func2(5)

Q1. Find the output of the following numbers:


Num = 20
Sum = 0
for I in range (10, Num, 3):
Sum+=i
if i%2==0:
print (i*2)
else:
print (i*3)

Q2. Find the output of the following


Text=”gmail@com”
L=len(Text)
ntext=” “
for i in range (0,L):
if text[i].isupper():
ntext=ntext+text[i].lower()
elif text[i].isalpha():
ntext=ntext+text[i].upper()
else:
ntext=ntext+’bb’

Q3. Find the output of the following-


def power (b , p):
r = b ** P
return r

def calcSquare(a):
a = power (a, 2)
return a

n=5
result = calcSquare(n)
print (result)

100
Q4. Find the output of the following-
import math
print (math. floor(5.5))

Q5. Find the output


def gfg(x,l=[ ]) :
for I in range(x):
l.append(i*i)
print(l)
gfg(2)
gfg(3,[3,2,1])
gfg(3)

Q6. Find the output of the following-


count =1
def dothis():
global count
for I in (1,2,3):
count+=1
dothis( )
print (count)

Q7. Find the output of the following-


def addem(x,y,z):
print(x+y+z)
def prod(x,y,z):
return x*y*z
A=addem(6,16,26)
B=prod(2,3,6)
print(a,b)

Q8. def Func(message,num=1):


print(message*num)
Func(‘python’)
Func(‘easy’,3)

Q9. def Check(n1=1,n2=2):


n1=n1+n2
n2+=1
print(n1,n2)
Check( )
Check(2,1)
Check(3)

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

11. Write a user defined function GenNum(a, b) to generate odd numbers between a and b
(including b).

101
12. Write definition of a method/function AddOdd(VALUES) to display sum of odd values
from the list of VALUES.

13. Write definition of a Method MSEARCH(STATES) to display all the state names from a list of
STATES, which are starting with alphabet M.
For example:
If the list STATES contains [“MP’,”UP”,”MH”,”DL”,”MZ”,”WB”]
The following should get displayed
MP
MH
MZ
14. Write a python function generatefibo(n) where n is the limit, using a generator function
Fibonacci (max)( where max is the limit n) that produces Fibonacci series.

15. Write a definition of a method COUNTNOW(PLACES) to find and display those place names,
in which here are more than 7 characters.
For example:
If the list PLACES contains. ["MELBORN","TOKYO","PINKCITY","BEIZING","SUNCITY"]
The following should get displayed : PINKCITY

SOLUTION: FUNCTIONS - OUTPUT AND ERROR


Ans Aa: def sum(a=1,b) :__
return a+b (indentation)
print (“The sum =”, Sum(7,-1))

Ans Ab: def main ( ):


print ("hello")

Ans Ac: def func2() :


print (2 + 3)
func2() no parameter is to be passed

1. output: 20 2. Output: GMAILbbCOM


39
32
57

3. output: 25 4. output: 6
5. output: [0,1] 6. output: 4
[3,2,1,0,1,4]
[0,1,0,1,4]
7. output: 36 8. output: python
easyeasyaesy
9. Output: 33 10. 15
32
53

11. def getNum(a,b): 12.Ans def AddOdd(Values):


for i in range(a,b+1): n=len(NUMBERS)
if i%2==1: s=0
print(i) for i in range(n):
if (i%2!=0):
s=s+NUMBERS[i]
print(s)

102
13. Ans def MSEARCH(STATES):
for i in STATES:
if i[0]==’M’:
print(i)

14. def Fibonacci (max):


a, b = 0, 1
while a <=max:
yield a,
a, b = b, a+b
def generatefibo(n):
for i in Fibonacci (n):
print( i)

15. Ans. l =["MELBORN","TOKYO","PINKCITY","BEIZING","SUNCITY"]


def countno(m):
length=len(m)
for i in range(0,length):
if len(m[i])>7:
print(m[i])
countno(l)

QUESTIONS: PYTHON LIBRARY/PACKAGE

SECTION A (1 MARK QUESTION)

Q1. Which operator is used in the python to import all modules from packages?
(a) . operator
(b) * operator
(c) -> symbol
(d) , operator

Q2. Which file must be part of the folder containing python module file to make it importable
python package?
(a) init.py
(b) ____steup__.py
(c) __init ___.py
(d) (d) setup.py

Q3. In python which is the correct method to load a module math?


(a) include math
(b) import math
(c) #include<math.h>
(d) using math

Q4. Which is the correct command to load just the tempc method from a module called usable?
(a) import usable,tempc (b) Import tempc from usable
(c) from usable import tempc (d) import tempc

Q5. What is the extension of the python library module?


(a) .mod (b) .lib
(c) .code (d) .py

103
SECTION B (2 MARK QUESTION)

Q1. How can you locate environment variable for python to locate the module files imported into a
program?
Q2. What is the output of the following piece of code?
#mod1
def change (a):
b=[x*2 for x in a]
print (b)
#mod2
def change (a) :
b =[x*x for x in a]
print (b)
from mode 1 import change
from mode 2 import change
#main
S= [1,2,3]
Change (s)
Note: Both the modules mod1 and mod 2 are placed in the same program.
(a) [2,4,6] (b) [1,4,9]
(c) [2,4,6][1,4,9] (d) There is a name clash

Q3. What happens when python encounters an import statement in a program? What would happen, if
there is one more important statement for the same module, already imported in the same program?

Q4. What is the problem in the following piece of code?


from math import factorial
print (math.factorial (5))

Q5. What is the output of the following piece of code?


#mod1
def change (a):
b=[x*2 for x in a]
print (b)
#mod2
def change (a):
b=[x*x for x in a]
print (b)
from mod1 import change
from mod2 import change
#main
S=[1,2,3]
Changes(s)

Q6. What would be the output produced by the following code :


import math
import random
print ( math.ceil (random.random()))
Justify your answer.

SECTION C (3 MARK QUESTION)


Q1. Observe the following code and answer the question based on it.
# the math_operation module
def add (a,b):
return a+b
def subtract(a,b):
return a-b

104
Fill in the blanks for the following code:
1. Math _operation #get the name of the module.
2. print (_______) #output: math_operation
# Add 1and 2
3. print(_______(1,2) ) # output 3

Q2. Consinder the code given in above and on the basis of it, complete the code given below:
# import the subtract function
#from the math_operation module
1.________________________ #subtract 1from 2
2.print(_______(2,1) ) # output : 1
# Import everything from math____operations
3._______________________________
print (subtract (2,1) ) # output:1
print (add (1,1) ) # output:2

Q3. Consider a module ‘simple’ given below:


#module simple.py
“ “ “Greets or scold on call” “ “
def greet():
“ “ “ Greet anyone you like :-)” “ “
Print (“Helloz”)
def scold ():
“ “ “ Use me for scolding ,but scolding is not good:-( “ “ “
Print (“Get lost”)
Count =10
print (“greeting or scolding- is it simple?”)
Another program ‘test.py’ imports this module.The code inside test.py is :
#test.py
import simple
print(simple.count)
What would be the output produced ,if we run the program test.py? justify your answer.

Q4. Consider the following code:


import math
import random
print(str(int(math.pow( random.randint (2,4),2) )), end = ‘ ’)
print(str( int ( math.pow(random.randint(2,4), 2))) , end = ‘ ’)
print( str ( int (math.pow( random .randint (2,4),2))))

What would be possible outputs out of the given four choices?


(i) 234
(ii) 944
(iii) 16 16 16
(iv) 249
(v) 494
(vi) 444

SOLUTIONS : PYTHON LIBRARY/PACKAGE


SECTION A (1 MARK ANSWERS )
Ans 1. (b)
Ans 2. (c )
Ans 3. (b)
Ans 4. (C)
Ans 5. (d)

105
SECTION B (2 MARK ANSWERS )

Ans 1. Pythonpath command is used for the same. It has a role similar to path. This variable tells the
python interpreter where to locate the module files imported into a program.It should include the
python source library ,directory containing python source code.

Ans 2. (d)

Ans 3. When python encounters an important statement, it does the following:


 The code of imported module is interpreted and executed.
 Defined functions and variables created in the module are now available to the program that
imported module.
 For imported module, a new namespace is set up with the same name as that of the module.
Any duplicate import statement for the same module in the same program is ignored by python

Ans 4. In the “from–import” from of import, the imported identifiers (in this case factorial ()) become
part of the current local namespace and hence their module’s name aren’t specified along with the
module name. Thus, the statement should be:
print( factorial (5) )

Ans 5. There is a name clash. A name clash is a situation when two different entities with the same name
become part of the same scope. Since both the modules have the same function name, there is a
name clash, which is an error..

Ans6. The output Produced would be 1.0

SECTION C (3 MARK ANSWERS )


Ans 1 . 1. input
2. math_operation_name_
3. math.operation.add

Ans 2. 1. from__operation import subtract


2. subtract
3. from math___ operation import*

Ans 3. The output produced would be:


Greeting or scolding – is it simple ?
10
The reason being , import module’s main block is executed upon import, so its important
statement cause it to print:
Greting or scolding- is it simple?
And print (simple.count) statement causes output’s next line ,i.e., 10

Ans 4. The possible outputs could be (ii), (iii) (v) and (vi).
The reason being that randint( ) would generate an integer between range 2…4, which is then
raised to power 2.

QUESTIONS : FILE HANDLING


Ques write a program in python to write and read structure, dictionary to the binary file.
Ans import pickle
d1={'jan':31,'feb':28,'march':31,'april':30}
f=open('binfile.dat','wb+')
pickle.dump(d1,f)
d2=pickle.load(f)
print(d2)
f.close()

106
The above program saves a dictionary in binfile.dat and prints it on console after reading it from
the file binfile.dat

QUESTIONS (1 MARK)

Q1. What is the difference between 'w' and 'a' modes?


Q2. BINARY file is unreadable and open and close through a function only so what are the
advantages of using binary file

Q3. Write a statement to open a binary file name sample.dat in read mode and the file
sample.dat is placed in a folder ( name school) existing in c drive

Q4. Which of the following function returns a list datatype


A) d=f.read() B) d=f.read(10)
C) d=f.readline() D) d=f.readlines()

Q5. How many file objects would you need to manage the following situations :
(a) To process four files sequentially
(b) To process two sorted files into third file

Q6. When do you think text files should be preferred over binary files?

QUESTIONS (2 MARK)
Q1. Write a single loop to display all the contens of a text file file1.txt after removing leading
and trailing WHITESPACES
out=open('output.txt','w')
out.write('hello,world!\n')
out.write('how are you')
out.close( )
open('output.txt').read( )

Q2. Read the code given below and answer the questions
f1=open('main.txt','w')
f1.write('bye')
f1.close()
if the file contains 'GOOD' before execution, what will be the content of the file after
execution of the code

Q3. Observe the code and answer the following


f1=open("mydata","a")
______#blank1
f1.close()
(i)what type of file is mydata
(ii) Fill in the blank1 with statement to write "abc" in the file "mydata"

Q4. A given text file data.txt contains :


Line1\n
\n
line3
Line 4
\n
line6
What would be the output of following code?
f1=open('data.txt')
107
L=f1.readlines()
print(L[0])
print(L[2])
print(L[5])
print(L[1])
print(L[4])
print(L[3])
Q5. In which of the following file modes the existing data of the file will not be lost?
i) rb
ii) w
iii) a+b
iv) wb+
v) r+
vi) ab
vii) w+b
viii)wb
ix) w+
Q6. What would be the data types of variables Data in following statements?
i) Data=f.read( )
ii) Data=f.read(10)
iii) Data=f.readline()
iv)Data=f.readlines()
Q7. Suppose a file name test1.txt store alphabets in it then what is the output of the following
code
f1=open("test1.txt")
size=len(f1.read())
print(f1.read(5))
QUESTIONS (3 MARKS)

Q1. Write a user defined function in python that displays the number of lines starting with 'H'in
the file para.txt
Q2. Write a function countmy() in python to read the text file "DATA.TXT" and count the
number of times "my" occurs in the file. For example if the file DATA.TXT contains-"This is
my website. I have diaplayed my preference in the CHOICE section ".-the countmy()
function should display the output as:"my occurs 2 times".
Q3. Write a method in python to read lines from a text file DIARY.TXT and display those lines
which start with the alphabets P.
Q4 write a method in python to read lines from a text file MYNOTES.TXT and display those
lines which start with alphabets 'K'
Q5 write a program to display all the records in a file along with line/record number.
Q6. consider a binary file employee.dat containing details such as
empno:ename:salary(seperator ':') write a python function to display details of those
employees who are earning between 20000 and 30000(both values inclusive)
Q7. write a program that copies a text file "source.txt" onto "target.txt" barring the lines
starting with @ sign.

SOLUTONS : FILE HANDLING


(1 MARK QUESTIONS)

Ans1. w mode opens a file for writing only. it overwrites if file already exist but 'a mode appends the
existing file from end. It does not overwrites the file
Ans2 binary file are easier and faster than text file.binary files are also used to store binary data such as
images, video files, audio files.
Ans3 f1=open(“c:\school\sample.dat”,’r’)

108
Ans4 d) f.readlines()
Ans5 a)4 b)3
Ans6 Text file should be preferred when we have to save data in text format and security of file is not
important
(2 MARKS QUESTIONS)
Ans1 for line in open(“file1.txt”):
print(line.strip())

Ans2 The file would now contains “Bye”only because when an existing file is openend in write mode .it
truncates the existing data in file .
Ans3 i) Text file
ii) f1.write(“abc”)
Ans4 Line1
Line3
Line 6
Line 4
Ans5 ab and a+b mode

Ans6 a) string b)string c)string d)list

Ans7 No Output
Explanation: the f1.read() of line 2 will read entire content of file and place the file pointer at the
end of file. for f1.read(5) it will return nothing as there are no bytes to be read from EOF and,
thus,print statement prints nothing.

ANSWERS (3 MARKS QUESTION)

Ans.1 def count H( ):


f = open (“para.txt” , “r” )
lines =0
l=f. readlines ()
for i in L:
if i [0]== ‘H’:
lines +=1
print (“No. of lines are: “ , lines)
Ans.2 def countmy ():
f=open (“DATA.txt” ,”r”)
count=0
x= f.read()
word =x.split ()
for i in word:
if (i == “my”):
count =count + 1
print (“my occurs” ,count, “times”)
Ans.3 def display ():
file=open(‘DIARY.txt ‘ , ‘r’)
line= file.readline()
while line:
if line[0]== ‘p’ :
print(line)
line=file.readline ()
file.close()

Ans.4 def display ():


file=open(MYNOTES.TXT’ , ‘r’)
line=file.readlines()
while line:
if line[0]==’K’ :
print(line)
line=file.readline()
109
file.close()

Ans5. f = open(“result.dat” , “r”)


count=0
rec=””
while True:
rec=f.readline (0)
if rec == “ “ :
break
count=count+1
print (count,rec)
f.close()

Ans.6 def Readfile():


i=open( “Employee.dat” , “rb+”)
x=i .readline()
while(x):
I= x.split(‘:’)
if ( (float (I[2]) >=20000) and (float I[2])<=40000):
print(x)
x= i.readline()

Ans.7 def filter (oldfile, newfile):


fin =open (oldfile, “r”)
fout= open (newfile, “w”)
while True:
text =fin.readline ()
if len(text)==0:
break
if text[0]== “@”:
continue
fout.write(text)
fin.close()
fout.close()
filter(“source.txt” , “target.txt”)

QUESTIONS : CSV FILE

Q1. Sunita writing a program to create a csv file “a.csv” which contain user id and name of the
beneficiary. She has written the following code. As a programmer help her to successfully
execute the program.
import ______________ #Line 1
with open('d:\\a.csv','w') as newFile:
newFileWriter = csv.writer(newFile)
newFileWriter.writerow(['user_id','beneficiary'])
newFileWriter.________________([1,'xyz']) #Line2
newFile.close()
with open('d:\\a.csv','r') as newFile:
newFileReader = csv._______________(newFile) #Line 3
for row in newFileReader:
print (row) #Line 4
newFile.____________ #Line 5
a) Name the module he should import in Line 1
b) Fill in the blank in line 2 to write the row.
c) Fill in the blank in line 3 to read the data from csv file.
d) Write the output while line 4 is executed.
110
e) Fill in the blank in line 5 to close the file.

Q2. MOHIT is writing a program to search a name in a CSV file “MYFILE.csv”. He has written the
following code. As a programmer, help him to successfully execute the given task.
import _________ # Statement 1
f = open("MYFILE.csv", _______) # Statement 2
data = ____________ ( f ) # Statement 3
nm = input("Enter name to be searched: ")
for rec in data:
if rec[0] == nm:
print (rec)
f.________( ) # Statement 4

(a) Name the module he should import in Statement 1.


(b) In which mode, MOHIT should open the file to search the data in the file in statement 2?
(c) Fill in the blank in Statement 3 to read the data from the file.
(d) Fill in the blank in Statement 4 to close the file.
(e) Write the full form of CSV.
3. Anis of class 12 is writing a program to create a CSV file “mydata.csv” which will contain
user name and password for some entries. He has written the following code. As a
programmer, help him to successfully execute the given task
import _____________ # Line 1
def addCsvFile(UserName,PassWord): # to write / add data into the CSV file
f=open(' mydata.csv','________')# Line 2
newFileWriter = csv.writer(f)
newFileWriter.writerow([UserName,PassWord])
f.close() #csv file reading code
def readCsvFile(): # to read data from CSV file
with open('mydata.csv','r') as newFile:
newFileReader = csv._________(newFile) # Line 3
for row in newFileReader:
print (row[0],row[1])
newFile.______________ # Line 4
addCsvFile(“Aman”,”123@456”)
addCsvFile(“Anis”,”aru@nima”)
addCsvFile(“Raju”,”myname@FRD”)
readCsvFile() #Line 5

(a) Give Name of the module he should import in Line 1.


(b) In which mode, Aman should open the file to add data into the file
(c) Fill in the blank in Line 3 to read the data from a csv file.
(d) Fill in the blank in Line 4 to close the file.
(e) Write the output he will obtain while executing Line 5.

SOLUTIONS : CSV FILES


1. a) import csv
b) newFileWriter.writerow([1,'xyz'])
c) newFileReader = csv.reader(newFile)
d) User_Id Beneficiary
1 xyz
e) newFile.close()

2. (a) csv.
(b) “r”?

111
(c) data = csv.reader(f)
(d) f.close()
(e) Comma Separated Values

3. (a) Line 1 : csv


(b) Line 2 : a
(c) Line 3 : reader
(d) Line 4 : close()
(e) Line 5 : Aman 123@456
Anis aru@nima
Raju myname@FRD

QUESTION : DATA STRUCTURE (STACK IN PYTHON)

1. Write a program for linear search in a list.


2. Write PushOn(Book) and Pop(Book) methods/functions in Python to add a new Book
and delete a Book from a list of Book titles, considering them to act as push and pop
operations of the Stack data structure.
3. Write a function AddCustomer(Customer) in Python to add a new Customer
information NAME into the List of CStack and display the information.
4. Write a function DeleteCustomer() to delete a Customer information from a list of
CStack. The function delete the name of customer from the stack

SOLUTIONS : DATA STRUCTURE (STACK IN PYTHON)


Ans 1. Write a program for linear search in a list.

L= input("Enter the elements: ")


n=len(L)
item=input("Enter the element that you want to search : ")
for i in range(n):
if L[i]==item:
print("Element found at the position :", i+1)
break
else:
print("Element not Found")
Ans 2.
def PushOn(Book):
a=input(“enter book title :”)
Book.append(a)
def Pop(Book):
if (Book = =[ ]):
print(“Stack empty”)
else:
print(“Deleted element :”)
Book.pop()
OR
class Stack:
Book=[ ]
def PushOn(self):
a=input(“enter book title:”)
Stack.Book.append(a)
def Pop(self):
if (Stack.Book==[ ]):
112
print(“Stack empty”)
else:
print(“Deleted element :”,Stack.Book.pop( ))

3. def AddCustomer(Customer):
CStake.append(Customer)
if len(CStack)==0:
print (“Empty Stack”)
else:
print (CStack)

4. def DeleteCustomer():
if (CStack ==[]):
print(“There is no Customer!”)
else:
print(“Record deleted:”,CStack.pop())

QUESTIONS : COMPUTER NETWORK


1. What are the components required for networking?
2. What is spyware?
3. What is Ethernet?
4. Write two advantage and disadvantage of networks.
5. What is ARPAnet ?
6. What is communication channel?
7. Define baud, bps and Bps. How are these interlinked?
8. What do you understand by InterSpace?
09. Name two switching circuits and explain any one
10. What is communication channel? Name the basic types of communication channels available
11. What are the similarities and differences between bus and tree topologies?
12. What are the limitations of star topology?
13. When do you think, ring topology becomes the best choice for a network?
14. Write the two advantages and two disadvantages of Bus Topology in network.
15. Define the following:
(i)RJ-45 (ii)Ethernet
(iii) Ethernet card (iv)hub (v)Switch
16. What is protocol? Name some commonly used protocols.
17 Define GSM, CDMA, and WLL
18 Define the following: (i)3G (ii)EDGE (iii)SMS (iv)TDMA
19. Define web browser and web server.
20. INDIAN PUBLIC SCHOOL in Darjeeling is setting up the network between its different wings.
There are 4 wings named as SENIOR(S), JUNIOR (J), ADMIN (A) and HOSTEL (H).
Distance between various Wings
Wing A to Wing S 100 m
Wing A to Wing J 200 m
Wing A to Wing H 400 m
113

You might also like