Our Features

Our Features
.

Monday, 6 June 2016

Python Questions and Answers – While and For Loops – 3

This set of Tough Python Questions & Answers focuses on “While and For Loops”.
1. What is the output of the following?
x = 'abcd'
for i in x:
    print(i)
    x.upper()
a) a B C D
b) a b c d
c) A B C D
d) error
View Answer
Answer: b
Explanation: Changes do not happen in-place, rather a new instance of the string is returned.
2. What is the output of the following?
x = 'abcd'
for i in x:
    print(i.upper())
a) a b c d
b) A B C D
c) a B C D
d) error
View Answer
Answer: b
Explanation: The instance of the string returned by upper() is being printed.
3. What is the output of the following?
x = 'abcd'
for i in range(x):
    print(i)
a) a b c d
b) 0 1 2 3
c) error
d) none of the mentioned
View Answer
Answer: c
Explanation: range(str) is not allowed.
4. What is the output of the following?
x = 'abcd'
for i in range(len(x)):
    print(i)
a) a b c d
b) 0 1 2 3
c) error
d) none of the mentioned
View Answer
Answer: b
Explanation: i takes values 0, 1, 2 and 3.
5. What is the output of the following?
x = 'abcd'
for i in range(len(x)):
    print(i.upper())
a) a b c d
b) 0 1 2 3
c) error
d) none of the mentioned
View Answer
Answer: c
Explanation: Objects of type int have no attribute upper().
6. What is the output of the following?
x = 'abcd'
for i in range(len(x)):
    i.upper()
print (x)
a) a b c d
b) 0 1 2 3
c) error
d) none of the mentioned
View Answer
Answer: c
Explanation: Objects of type int have no attribute upper().
7. What is the output of the following?
x = 'abcd'
for i in range(len(x)):
    x[i].upper()
print (x)
a) abcd
b) ABCD
c) error
d) none of the mentioned
View Answer
Answer: a
Explanation: Changes do not happen in-place, rather a new instance of the string is returned.
8. What is the output of the following?
x = 'abcd'
for i in range(len(x)):
    i[x].upper()
print (x)
a) abcd
b) ABCD
c) error
d) none of the mentioned
View Answer
Answer: c
Explanation: Objects of type int aren’t subscriptable.
9. What is the output of the following?
x = 'abcd'
for i in range(len(x)):
    x = 'a'
    print(x)
a) a
b) abcd abcd abcd
c) a a a a
d) none of the mentioned
View Answer
Answer: c
Explanation: range() is computed only at the time of entering the loop.
10. What is the output of the following?
x = 'abcd'
for i in range(len(x)):
    print(x)
    x = 'a'
a) a
b) abcd abcd abcd abcd
c) a a a a
d) none of the mentioned
View Answer
Answer: d
Explanation: abcd a a a is the output as x is modified only after ‘abcd’ has been printed once.

No comments:

Post a Comment