Recursive function returning none in Python
You need to return the recursive result:
else:
return get_path(directory[filename], rqfile, path)
otherwise the function simply ends after executing that statement, resulting in None
being returned.
You probably want to drop the else:
and always return at the end:
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))
return get_path(directory[filename], rqfile, path)
because if rqfile in str(os.path.join(*path))
is False
then you end your function without a return
as well. If recursing in that case is not the right option, but returning None
is not, you need to handle that edgecase too.
Recursive function returning none?
You are ignoring the return values of recursive calls. You need to explicitly return those too:
elif input[mid] > target:
return bisect(input[:mid], target)
elif input[mid] <= target:
return bisect(input[mid:], target)
Recursive calls are just like any other function call; they return a result to the caller. If you ignore the return value and the calling function then ends, you end up with that calling function then returning None
instead.
Why is my recursive function returning a None value
As you go down the call stack, you need to be returning values back up the stack once you hit the base case.
def detectNumber(stringVal, lp, makeNumber=""):
try:
if stringVal[lp] == " ":
print("Space detected")
print(f"At start makeNumber was {makeNumber}")
return makeNumber
else:
makeNumber += stringVal[lp]
lp += 1
# Here
return detectNumber(stringVal, lp, makeNumber=makeNumber)
except:
print(f"Error {lp}")
>>> detectNumber('123 ', 0)
Space detected
At start makeNumber was 123
'123'
You were getting None
, because the value was only returned to the last recursive caller, rather than all the way back up the stack
recursive function returning 'None'
Change it please to
def fib(n):
nums.append(nums[-1] + nums[-2])
if len(nums) - 1 != n:
return fib(n)
elif len(nums) - 1 == n:
return nums
Recursive function return None even though print() works
You need to return count_lowercase(s, low + 1, high)
, otherwise the function simply ends after executing that statement, resulting in None
being returned.
count = 0
def count_lowercase(s, low, high):
global count
if low > high:
return count
else:
if s[low] == s[low].lower():
count += 1
return count_lowercase(s, low + 1, high)
Why Recursive function return None
The return statement is missing!
Do this:
def good(num,sum):
if num == 0:
return sum
sum = sum + num
num = num - 1
return good(num, sum)
This is because the function is called but is not returning the new values recursively.
One of the best website that explains this in depth and clearly is realpython.com, have a look especially at: maintaining-state but I suggest you to have a look at the whole article.
For sake of completeness I quote a section where I think is related to the issue you encountered:
Behind the scenes, each recursive call adds a stack frame (containing its execution context) to the call stack until we reach the base case. Then, the stack begins to unwind as each call returns its results.
- unwind: Basically it returns it backward.
When dealing with recursive functions, keep in mind that each recursive call has its own execution context.
Other Stack Overflow Related questions
- recursive-function-returning-none-in-python
- python-recursion-with-list-returns-none
- i-expect-true-but-get-none
Why does my recursive function return None?
It is returning None
because when you recursively call it:
if my_var != "a" and my_var != "b":
print('You didn\'t type "a" or "b". Try again.')
get_input()
..you don't return the value.
So while the recursion does happen, the return value gets discarded, and then you fall off the end of the function. Falling off the end of the function means that python implicitly returns None
, just like this:
>>> def f(x):
... pass
>>> print(f(20))
None
So, instead of just calling get_input()
in your if
statement, you need to return
it:
if my_var != "a" and my_var != "b":
print('You didn\'t type "a" or "b". Try again.')
return get_input()
Related Topics
How to Use 'Subprocess' Command With Pipes
Packaging a Python Script on Linux into a Windows Executable
Simulating Key Press Event Using Python For Linux
Hex/Binary String Conversion in Swift
Unboundlocalerror on Local Variable When Reassigned After First Use
Input() Error - Nameerror: Name '...' Is Not Defined
How to Read a Single Character from the User
Why Are Multiple Instances of Tk Discouraged
Sorting List Based on Values from Another List
Imagemagick Not Authorized to Convert Pdf to an Image
Find Size and Free Space of the Filesystem Containing a Given File
Understanding Python Subprocess.Check_Output'S First Argument and Shell=True
How to Make Good Reproducible Pandas Examples
How to Avoid Having Class Data Shared Among Instances
Pygame Mouse Clicking Detection
Accessing Class Variables from a List Comprehension in the Class Definition