Home > Backend Development > Python Tutorial > Why Does My Recursive Function Return `None` in Python?

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

Barbara Streisand
Release: 2024-11-24 12:16:24
Original
206 people have browsed it

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

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

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.

The above is the detailed content of Why Does My Recursive Function Return `None` in Python?. 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