Home >Backend Development >Python Tutorial >Why Does My Recursive Code Continuously Return None?
Recursive Code Continuously Returns None
Given the following recursive code snippet:
<code class="python">def isIn(char, aStr): ms = len(aStr)/2 if aStr[ms] == char: print('i am here now') return True elif char > aStr[ms] and not ms == len(aStr)-1: aStr = aStr[ms+1:] elif char < aStr[ms] and not ms == 0: aStr = aStr[0:ms] else: return False isIn(char, aStr) print(isIn('a', 'ab'))</code>
One may encounter unexpected behavior where the code returns None instead of the expected True value. This issue arises because the final recursive call within the else block lacks an explicit return statement.
The corrected code should include the following addition:
<code class="python">else: return isIn(char, aStr)</code>
In this scenario, when the function recurses, it assigns the return value of the recursive call to the function itself. If the recursive call fails to find the character, it returns False, which the function then returns as its own value.
Without the explicit return statement on the final recursive call, the function would reach the end without a specified return value. As a result, it would implicitly return None, which is why the original code kept returning None.
The above is the detailed content of Why Does My Recursive Code Continuously Return None?. For more information, please follow other related articles on the PHP Chinese website!