Chapter 2 – Python Revision Tour II
Type B: Application-Based Questions – Python Revision Tour II
Question 1: What will be the output produced by following code fragments?
1 (a)
y = str(123)
x = “hello” * 3
print(x, y)
x = “hello” + “world”
y = len(x)
print(y, x)
Answer:
hellohellohello 123
10 helloworld
1 (b)
x = “hello”+ \
“to python”+\
“world”
for char in x:
Answer:
h : e : l : l : o : t : o : : P : y : t : h : o : n : w : o : r : l : d :
Question – 1 (c) : Output
Answer:
he hellowor ld
o ll
llowo or
Question – 2: Python code to Print Average length of Words
Answer:
#Type - B Que 2
words = ["This", "is", "a", "Python", "Program"]
addlength = 0
for w in words:
addlength = addlength + len(w)
avg_length = addlength / len(words)
print(avg_length)
Question – 3: Predict Output
Answer: [4, 3, 2]
Question – 4 (a) : Predict Output
Answer: 2 3 4 5 6 6
Question – 4 (b) : Predict Output
Answer:
1 #
1 # 2 #
1 # 2 # 3 #
Question – 5(a) : Find the errors. State reasons.
Answer: t[0] = 6 raise an error message. Becuase t is a tuple, tuple is immutable.
Question – 5(b) : Find the errors. State reasons.
Answer: No Error
Question – 5(c) : Find the errors. State reasons.
Answer: t[4] = 6, raise an error IndexError – list index out of range
Question – 5(d) : Find the errors. State reasons.
Answer: t[0] = “H” raise a TypeError: ‘str’ object does not support item assignment
Question – 5(e) : Find the errors. State reasons.
Answer: This code has the following errors –
Line 1 – Undefined Symbol – Amar, Shveta, and Parag
Line 2 – Undefined Symbol IF, Invalid operator =, it should be ==
Question – 6:
Answer: for i in range(len(words), 0, -1) : print(words[i], end=”)
Error 1: when i is len(words), words[i] raise an IndexError, because last element index value is len(words)-1.
Error 2: for i in range(len(words), 0, -1) – does not assign 0 to i, so that it does not print the first element of the word. This is a logical error.
Question – 7: Output of the following code
Answer:
a is Hello
b is Nita
c is How’s
d is life ?
Hi Nita
Question – 8: Output of the following code – (refer to book)
Answer: print(tuple_a == tuple_b) => print True
Question – 9: Output of the following code- (refer to book)
Answer: (b) False
Reason: Both id1 and id2 refer to a different memory.
Question – 10: Output of the following code(refer to book)
Answer: 30
{(1,2,4) : 8, (4,2,1) : 10, (1,2) : 12}
Question – 11: Write a method to display the elements of the list thrice if it is a number and display the element terminated with ‘#’ if it is not a number.
Answer: Python Method
def printList():
List = ['41', 'DROND', 'GIRIRAJ', '13', 'ZARA']
for val in List:
if val.isdigit():
print(val*3)
else:
print(val,'#', sep='')
printList()
Output:
414141
DROND#
GIRIRAJ#
131313
ZARA#
Question – 12: Name the function/method required to
Answer: (i) Check if a string contains only uppercase letters – isupper()
(ii) gives the total length of the list – len()