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
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
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.