Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – Why does it prints "none"?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading