0

I know there are better ways to print things backwards. But for some reason I can't get this to work. Any ideas why?

fruit = 'banana'
index = 0
while index < len(fruit):
    print fruit[-(index)]
    index = index + 1
Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67
bugsyb
  • 5,662
  • 7
  • 31
  • 47

1 Answers1

7

You reversed everything but the b, because you started at 0, and -0 is still 0.

You end up with the indices 0, -1, -2, -3, -4, -5, and thus print b, then only anana in reverse. But anana is a palindrome, so you cannot tell what happened! Had you picked another word it would have been clearer:

>>> fruit = 'apple'
>>> index = 0
>>> while index < len(fruit):
...     print fruit[-index]
...     index = index + 1
... 
a
e
l
p
p

Note the a at the start, then pple correctly reversed.

Move the index = index + 1 up a line:

index = 0
while index < len(fruit):
    index = index + 1
    print fruit[-index]

Now you use the indices -1, -2, -3, -4, -5 and -6 instead:

>>> fruit = 'banana'
>>> index = 0
>>> while index < len(fruit):
...     index = index + 1
...     print fruit[-index]
... 
a
n
a
n
a
b
>>> fruit = 'apple'
>>> index = 0
>>> while index < len(fruit):
...     index = index + 1
...     print fruit[-index]
... 
e
l
p
p
a

I removed the (..) in the expression -(index) as it is redundant.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • One of those weird situations where the only reason it's hard to debug is the particular example used. Not many words are a letter followed by an palindrome. – Roger Fan Sep 27 '14 at 20:40