The following code iterates and output banana, how can i change it to reverse the output?

I have tried to modify the code to print the reverse of banana but I still can’t find a solution. thanks in advance.

index = 0
fruit = "banana"
while index < len(fruit):
    letter = fruit[index]
    print (letter)
    index = index + 1

Answer

Try this approach. In Python -1 means last position, so the len of the word (negative) is the first position of your slice.

Because Python range is not inclusive, you have to add a -1 to this scenario. Otherwise it it will print “anana”.

Finally, we want to go from -1 to -6, so the increment must be -1.

word = "banana"
start = -1
end = (len(word) * -1) - 1
increment = -1

print(word[start:end:increment])