pythonpython-3.xstringindexing

Solution to Python for Everybody exercise 6.1


I'm currently following the free PY4E course and going through the exercises one by one to get a good understanding of the basics. I got stuck understanding the outcome of the following exercise:

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

My program:

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

The program prints 'apple' backwards as expected but ends with a traceback: string index out of range.

Why is this and how would one prevent the traceback from happening for this particular exercise?

I've tried adjusting the index, and index > len(fruit) but in the latter case there is no result printed.

Thanks for any help!


Solution

  • index will always be less than the length of fruit. So once your script reaches an index of -6 it is throwing the error because it exceeds the length of the string apple. Another way to accomplish your task would be:

    fruit = "apple"
    
    for letter in fruit[::-1]:
        print(letter)
    

    In Python you can slice strings like an array. string[start:stop:step]. In this example, [::-1] is saying from start to end in -1 steps aka from the end to the start.

    If you want to keep what you have you can fix it by:

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

    Each iteration of the loop is doing:

    fruit[-1] = e
    fruit[-2] = l
    fruit[-3] = p
    fruit[-4] = p
    fruit[-5] = a