Which of the following statements is FALSE about traversing a string using loops in Python? 

a. We can use a for loop with the in operator to iterate over each character in a string.

b. We can use a while loop with the len() function and indexing to access each character in a string. 

c. We can use slicing with a negative step to iterate over the characters in a string in reverse order. 

d. We can use the range() function with the len() function to generate the indices of the characters in a string.

Answer:

Answer by student

c. We can use slicing with a negative step to iterate over the characters in a string in reverse order.

Detailed answer by teachoo

-lock-

Let’s go through each of the options and see why they are correct or incorrect.

  • Option a. We can use a for loop with the in operator to iterate over each character in a string.

This is TRUE . We can use a for loop with the in operator to iterate over each character in a string, as shown in the following example:

s = "Hello"

for c in s:

  print(c)

The output of this code is:

H

e

l

l

o

  • Option b. We can use a while loop with the len() function and indexing to access each character in a string.

This is TRUE . We can use a while loop with the len() function and indexing to access each character in a string, as shown in the following example:

s = "Hello"

i = 0

while i < len(s):

  print(s[i])

  i = i + 1

The output of this code is:

H

e

l

l

o

  • Option c. We can use slicing with a negative step to iterate over the characters in a string in reverse order.

This is FALSE . We cannot use slicing with a negative step to iterate over the characters in a string in reverse order using a loop, because slicing returns a new string object, not an iterable. For example, if we try to run the following code:

s = "Hello"

for c in s[::-1]:

  print(c)

We will get an error message like this:

TypeError: 'str' object is not reversible

  • Option d. We can use the range() function with the len() function to generate the indices of the characters in a string.

This is TRUE . We can use the range() function with the len() function to generate the indices of the characters in a string, as shown in the following example:

s = "Hello"

for i in range(len(s)):

  print(s[i])

The output of this code is:

H

e

l

l

o

So, the only false statement among the options is option c.

So, the correct answer is option c. We can use slicing with a negative step to iterate over the characters in a string in reverse order.

-endlock-

Remove Ads
Teachoo · Class 11 Explore Class 11
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh is an IIT Kanpur graduate and has been teaching for 16+ years. At Teachoo, he breaks down Maths, Science and Computer Science into simple steps so students understand concepts deeply and score with confidence.

Many students prefer Teachoo Black for a smooth, ad-free learning experience.