You can easily see what's happening by adding print() statements.
def reverse_string4(arr, start=0):
print('-> arr %s, start=%i' % (arr, start))
while start < len(arr):
print('start %i < len(arr) %i' % (start, len(arr)))
arr.insert(start, arr.pop())
print('call reverse_string()')
reverse_string4(arr, start + 1)
print('back from call')
Run it with reverse_string4(['h', 'e', 'l', 'l', 'o']):
-> arr ['h', 'e', 'l', 'l', 'o'], start=0
start 0 < len(arr) 5
call reverse_string()
-> arr ['o', 'h', 'e', 'l', 'l'], start=1
start 1 < len(arr) 5
call reverse_string()
-> arr ['o', 'l', 'h', 'e', 'l'], start=2
start 2 < len(arr) 5
call reverse_string()
-> arr ['o', 'l', 'l', 'h', 'e'], start=3
start 3 < len(arr) 5
call reverse_string()
-> arr ['o', 'l', 'l', 'e', 'h'], start=4
start 4 < len(arr) 5
call reverse_string()
-> arr ['o', 'l', 'l', 'e', 'h'], start=5
back from call
start 4 < len(arr) 5
call reverse_string()
-> arr ['o', 'l', 'l', 'e', 'h'], start=5
back from call
start 4 < len(arr) 5
call reverse_string()
-> arr ['o', 'l', 'l', 'e', 'h'], start=5
back from call
start 4 < len(arr) 5
call reverse_string()
-> arr ['o', 'l', 'l', 'e', 'h'], start=5
back from call
start 4 < len(arr) 5
call reverse_string()
-> arr ['o', 'l', 'l', 'e', 'h'], start=5
back from call
start 4 < len(arr) 5
call reverse_string()
See? The while condition is still true, so it stays in the while loop.
The proper fix is to use either a while loop or recursion (and then, probably return the value called by the recursive call).
whileis an infinite loop. There's nothing in the body of the loop that would make the while condition false. Why do you think you need a while loop and recursion?ifinstead ofwhileloop because there is no need ofwhilelooping in recursion.if start < len(arr):will also work.startdoes not become 5. When you recursively callreverse_string2you create a new run of the function with its own variables and its ownstart. But in the original run, thestartvariable that the while-loop is looking at still has the same value, so it still loops.