I assume that this is an exercise / exploration in handling variables in recursive functions.
You can pass ctr
as an argument in the recursive calls, and you can initialize it with a default value so you don't need to supply ctr
in the original call.
def myfn(N, ctr=0):
if N == 0:
return ctr
elif N % 10 == 2:
ctr += 1
A = N/10
print A
return myfn(A, ctr)
else:
A = N/10
return myfn(A, ctr)
print myfn(1233252672)
output
123325267
123325
1233
1
4
(If you need to pass more complex objects around then you have to be careful. See “Least Astonishment” in Python: The Mutable Default Argument for details).
However, it's simpler to just use a while
loop for this task. Recursion is not efficient in Python, so you should only use it when it's appropriate to the problem domain, eg working with recursive data structures, like trees.
def myfn(n):
ctr = 0
while n:
a = n // 10
if n % 10 == 2:
ctr += 1
print a
n = a
return ctr