I'm using the Python Tutorial visualize webpage to try and understand the flow of this function that reverses a string:
text = "hello"
def reverse(text):
if len(text) <= 1:
return text
else:
return reverse(text[1:]) + text[0]
print reverse(text)
I understand what this function does, but even with the visualizer, I'm still not quite grasping how the last line operates in the function in terms of the flow of the function as it loops through the characters in the string:
return reverse(text[1:]) + text[0]
I get that by itself reverse(text[1:]) returns o and that text[0] returns h
But again, not quite experienced enough to understand how the function is set up to loop through the string using [1:] and [0] — any explanation would be greatly appreciated in terms of how the final string retuned from the function is 'olleh'
reverse(text[1:])(eventually) returns'olle', not just'o'! Think about the caselen(text) == 2and work out from there.text[1:]on its own? Do you know what that does?