0

I want to check in a string from the last character to the first one using while loop in python.

Linux - Ubuntu - I am using Atom text editor.

fruit = 'banana'
letter = fruit[5]
length = len(fruit)
index = 5

    while index > len(fruit):
            letter = fruit[index]
            print(letter)
            index = index - 1

the terminal lists the characters right but does that twice and at the end displays out of range error. check:

a
n
a
n
a
b
a
n
a
n
a
b
Traceback (most recent call last):
  File "youtube.py", line 5, in <module>
    letter = fruit[index]
IndexError: string index out of range
  • 1
    Possible duplicate of [Loop backwards using indices in Python?](https://stackoverflow.com/questions/869885/loop-backwards-using-indices-in-python) – hugo Aug 10 '19 at 23:36
  • 1
    Cannot reproduce. This code as posted doesn't enter the loop. – Carcigenicate Aug 10 '19 at 23:37
  • 2
    I flagged as possible dupe, but if you *need* to use a while-loop, just write `while index >= 0` instead -- edit: and start with `length = len(fruit) - 1` – hugo Aug 10 '19 at 23:37
  • Uh yeah, as @Carcigenicate mentioned, your code surely doesn't produce the output you documented – hugo Aug 10 '19 at 23:39
  • Another possible duplicate: https://stackoverflow.com/questions/10957812/how-to-for-loop-in-reverse – wwii Aug 10 '19 at 23:46
  • @wwii Just like my flag, yours ignores the fact that OA asked for a solution using a while-loop – hugo Aug 10 '19 at 23:47

4 Answers4

0

Since your index is starting at 5 and heading down, change your test to index >= 0

fruit = 'banana'
letter = fruit[5]
index = 5

while index >= 0:
    letter = fruit[index]
    print(letter)
    index = index - 1
dwmorrin
  • 2,704
  • 8
  • 17
  • Hmm, sure, but also set `length` to `len(fruit) - 1` if you want it to work – hugo Aug 10 '19 at 23:40
  • @hugo `length` isn't used. It can be deleted. – dwmorrin Aug 10 '19 at 23:42
  • You're right, my bad. Still writing `index = len(fruit) - 1` would be better? *(but I understand your goal was not to alter the original code too much)* – hugo Aug 10 '19 at 23:46
0

Thank you guys, I tried the below and it worked. I used the break functionality.

fruit = 'banana'
index = 0
while index < len(fruit) :
    letter = fruit[index - 1]
    print(letter)
    index = index - 1
    if index == -6 :
        break
0

Here are some methods

  • reverse slicing

    fruit = 'banana'
    for f in fruits[::-1]:
       print(f)
    
  • reversed in-build

    fruit = 'banana'
    for f in reversed(fruits):
       print(f)   
    
  • while loop

    fruit = 'banana'
    fruit_len = len(fruit)
    while fruit_len:
        fruit_len -=1
        print(fruit[fruit_len])
    
Tobey
  • 1,400
  • 1
  • 10
  • 25
0

I tried this and it works:

index = 0
fruit = "apple"
    while index < len(fruit):
    index = index - 1
        if index < -(len(fruit)):
            break
    letter = fruit[index]
    print(letter)
    
Nhung Vu
  • 1
  • 1