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