i = 1
input_number = int(input("Input a digit you wish to count: "))
def count(n):
global i
n = int(n/10)
if n > 0:
i = i+1
count(n)
else:
j = i
print(f"j={j}")
return j
j = count(input_number)
print(f"i={i}")
print(j)
I’m trying to use a recursive way to print the digits of a number. I used a global counter to count, and can print the global counter as result. However, my question is – why can’t I make the function to return the counter and print the function result directly? It returns None somehow.
>Solution :
The count function does not always return a value, so in those cases, it returns None.
If n is greater than 0, no return is encountered.
if n > 0: i = i+1 count(n)
You were likely wanting:
if n > 0:
i = i+1
return count(n)
Please also note that if you want integer division, you can use //. E.g. n = int(n/10) can be n = n // 10 or just n //= 10.