250+ TOP MCQs on Python While and For Loops and Answers

Tough Python Questions & Answers on “While and For Loops”.

1. What will be the output of the following Python code?

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
Answer: b
Clarification: Changes do not happen in-place, rather a new instance of the string is returned.

2. What will be the output of the following Python code?

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
Answer: b
Clarification: The instance of the string returned by upper() is being printed.

3. What will be the output of the following Python code?

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
Answer: c
Clarification: range(str) is not allowed.

4. What will be the output of the following Python code?

x = 'abcd'
for i in range(len(x)):
    print(i)

a) a b c d
b) 0 1 2 3
c) error
d) 1 2 3 4
Answer: b
Clarification: i takes values 0, 1, 2 and 3.

5. What will be the output of the following Python code?

x = 'abcd'
for i in range(len(x)):
    print(i.upper())

a) a b c d
b) 0 1 2 3
c) error
d) 1 2 3 4
Answer: c
Clarification: Objects of type int have no attribute upper().

6. What will be the output of the following Python code snippet?

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
Answer: c
Clarification: Objects of type int have no attribute upper().

7. What will be the output of the following Python code snippet?

x = 'abcd'
for i in range(len(x)):
    x[i].upper()
print (x)

a) abcd
b) ABCD
c) error
d) none of the mentioned

Answer: a
Clarification: Changes do not happen in-place, rather a new instance of the string is returned.

8. What will be the output of the following Python code snippet?

x = 'abcd'
for i in range(len(x)):
    i[x].upper()
print (x)

a) abcd
b) ABCD
c) error
d) none of the mentioned
Answer: c
Clarification: Objects of type int aren’t subscriptable. However, if the statement was x[i], an error would not have been thrown.

9. What will be the output of the following Python code snippet?

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
Answer: c
Clarification: range() is computed only at the time of entering the loop.

10. What will be the output of the following Python code snippet?

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
Answer: d
Clarification: abcd a a a is the output as x is modified only after ‘abcd’ has been printed once.

tough questions on Python,

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top