my function looks like this:
JavaScript
x
8
1
def func(x):
2
for i in range(x+1 to x+10):
3
if (condition):
4
return True
5
else:
6
func(i)
7
return False
8
here, when we return True or False, the return value of the previous recursive call is not affected.
What I want to do is: if a recursive function returns True, the “base case function” should also return True immediately
A workaround I’ve found is using a nonlocal variable:
JavaScript
1
10
10
1
var = False
2
def func(x):
3
nonlocal var
4
for i in range(x+1 to x+10):
5
if (condition):
6
var = True
7
else:
8
func(i)
9
return var
10
but I was wondering if there was a nicer way to do the same
Advertisement
Answer
It’s just this.
JavaScript
1
8
1
def func(x):
2
for i in range(x+1 to x+10):
3
if (condition):
4
return True
5
elif func(i):
6
return True
7
return False
8
Do use the return value of func(i)
as a boolean value.