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

Function is returning NoneType in Python instead of integer

def function(n):
    if n%4==1:
      return(n**2)
    else:
      n += 1
      function(n)

# Here for example n=6:

if function(6)%2==0:
    print(function(6))
else:
    print("Hey!")

This is showing the error unsupported operand type(s) for %: ‘NoneType’ and ‘int’. I have tried to convert NoneType with int() but that is telling me to give "str" or other data types as an argument.

When I am telling function(n) to return in both ‘if’ and ‘else’ conditions, only then it does not show the error.

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

>Solution :

To elaborate on comments from Nin17 and molbdnilo:

Your function function(n) is supposed to return an integer value.
Like you did in if branch with return(n**2), do return in the else branch:

def function(n):
    if n % 4 == 1:
      return n**2
    else:      
      return function(n + 1)  # inlined the increased n and do return 

I would recommend to give the function a meaningful name.

A function like yours that calls itself is a recursive function. One of it’s key-mechanisms is that it returns a value.

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