Home > Backend Development > Python Tutorial > Why Does My Recursive Code Continuously Return None?

Why Does My Recursive Code Continuously Return None?

Barbara Streisand
Release: 2024-10-27 01:11:30
Original
732 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template