Don't understand the Reverse code


#1

Struggled with this code so I opted for the ‘Get Code’ after a few unsuccessful attempts. I’m looking for some clarity on what some of the lines in the function does. Thanks!



def reverse(text):
    word = ""
    l = len(text) - 1 #this variable takes the length of 'text' and subtracts 1?  Is this the same argument in the function?  
    while l >= 0:
        word = word + text[l] # do not understand this, please help
        l -= 1
    return word
print reverse("text")



#2
l = len(text) - 1

strings are zero indexed based (counting start at zero) while len(gth) start counting at 1, so we need to subtract one to compensate for the difference, otherwise we get an index error

the best way to understand is by adding print statements to see what code does:

print l, text[l]
word = word + text[l]

so l will contain integers which we can use as indexes to retrieve letters from word we want to reverse


#3

Thank you. I didn’t know that about len() and adding the print statements really helped visualize what is going on.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.