"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does My Recursive Function Return `None` in Python?

Why Does My Recursive Function Return `None` in Python?

Posted on 2025-03-23
Browse:385

Why Does My Recursive Function Return `None` in Python?

Recursive Function Returns None in Python Resolved

When attempting to return a path in a recursive function, an issue can arise where "None" is returned instead. This can be resolved by ensuring that the recursive result is returned. Here's an explanation of why and how to fix it:

In the provided code:

def get_path(dictionary, rqfile, prefix=[]):
    for filename in dictionary.keys():
        path = prefix   [filename]
        if not isinstance(dictionary[filename], dict):
            if rqfile in str(os.path.join(*path)):
                return str(os.path.join(*path))
        else:
            get_path(directory[filename], rqfile, path)

The recursive call ends with get_path(directory[filename], rqfile, path) without a return. This means that if rqfile is not in str(os.path.join(*path)), the function ends without explicitly returning anything, resulting in a default return value of None.

To fix this, the recursive result should be returned like so:

else:
    return get_path(directory[filename], rqfile, path)

By always returning at the end of the function, whether or not it's a recursive call, we ensure that a return is explicitly given, preventing "None" from being returned.

Note that the else after the if not isinstance(dictionary[filename], dict): branch can be removed, as the function should return in both cases: when rqfile is in the path and when it's not, and there's no need for an else branch to simply end the function.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3