user3716774 - 7 months ago 38

Python Question

For example I have a function like this:

`def a (x):`

f(x)

if f(x) < 0:

a(x) # If a(x) is called over 30 times, then stop calling a(x) and return certain value.

else: return f(x)

I want to count the number of function calling under the if statement. Once the calling number is over certain number, then I can stop running a(x) and return certain values, and the calling number can be restored.

How can I do this? The regular counting wrapper is for the whole function, which is not suitable in this case I guess?

------------ Update -------------

Thanks to @Yevhen Kuzmovych now I have an example function like this:

`def a (x, depth = 0):`

b = x - 1

print(depth, b)

if b < 0:

if depth < 10:

a(b, depth + 1)

else:

return b

else:

return b

c = a(0) # this doesn't have a value

so with this function, c doesn't have a value. I don't understand. It seems the value is not returned.

Answer

You need to count depth of recursion:

```
def a(x, depth = 0):
f(x)
if f(x) < 0:
if depth < certain_number:
return a(x, depth + 1)
else:
return certain_value
else:
return f(x)
```

Source (Stackoverflow)