How to fix "IndexError: string index out of range" error in python

Prashant Gonga

I recently started learning Python from a MOOC on Coursera. I'm trying to write a while loop that starts at the last character in the string and works its way backwards to the first character in the string, printing each letter on a separate line, except backwards.

I have written the code which is giving me the desired output but it's also giving me an error

"IndexError: string index out of range"

index = 0
fruit = "potato"
while index <= len(fruit) :
    index = index - 1
    letter = fruit[index] 
    print(letter)
 Traceback (most recent call last):
      File "strings_01.py", line 8, in <module>
        letter = fruit[index]
    IndexError: string index out of range
U10-Forward

Try using a different while loop condition:

index = 0
fruit = "potato"
while abs(index) < len(fruit):
    index = index - 1
    letter = fruit[index] 
    print(letter)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How I can fix this error IndexError: string index out of range

How to fix IndexError: String index out of range - Python

How to solve the following error in python: "IndexError: string index out of range"

How to resolve "IndexError: string index out of range" error in python?

Python error:“IndexError: string index out of range”

How can I handle the error "IndexError: string index out of range"

How to debug "IndexError: string index out of range" in Python?

How di I fix this Error? self.category_id.set(row[1]), IndexError: string index out of range

Python 3 - IndexError: string index out of range

Getting IndexError: string index out of range in python

IndexError: string index out of range python problem

"IndexError: string index out of range" with a Python Program

PYTHON IndexError : string index out of range

Python - IndexError: string index out of range

"IndexError: string index out of range" error, despite no flaws in code

Python regex: 'exceptions.IndexError: string index out of range'

Reverse the string using for loop in python IndexError: string index out of range

I can't deal with "IndexError: string index out of range" in Python

Getting IndexError: string index out of range for a python problem

Python returns IndexError: string index out of range on this funtion why

How can I get rid of "IndexError: string index out of range"

Reading level script sends error "IndexError: string index out of range" on certain sites

why getting IndexError: string index out of range when i get no error when i print the list?

Python IndexError: string index out of range - What am I doing wrong?

How can I get rid of IndexError: string index out of range in loops?

IndexError string index out of range

IndexError: string index out of range:

IndexError: string index out of range - Treeview

IndexError: String Index out of range for recursive function