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
Ashish Ahuja
  • 4,913
  • 10
  • 51
  • 65
bugsyb
  • 4,977
  • 7
  • 28
  • 39

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
  • 963,270
  • 265
  • 3,804
  • 3,187
  • 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