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.
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!