Why does my code work strange?


#1



Reverse


If you replace the 0 in range with 1, it reverses the string except for the first letter, and if you leave it like that, this error comes out:

File "python", line 7, in
File "python", line 5, in reverse
IndexError: string index out of range


def reverse(text):
    newtext=''
    for n in range(0,len(text)):       
        k = len(text)-n
        newtext += str(text[k])
    return newtext
reverse('text')

Replace this line with your code.


#2

the problem is in that len() is one indexed based (the counting starts from one) making the length 4. well the string is zero indexed based, so the indexes of the string are 0,1,2,3.

so then here:

k = len(text)-n

for the first run of the loop, k becomes 4, which is not a valid index for text. you could simply solve this problem by subtracting one:

k = len(text)-n - 1

#3

Ohhh, I get it now. Thank you so much :slight_smile:


#4