Function is returning NoneType in Python instead of integer
Question:
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.
Answers:
def function(n):
if n%4==1:
return(n**2)
else:
n += 1
return function(n)
if function(6)%2==0:
print(function(6))
else:
print("Hey!")
in your else statement you return nothing. Put the return statement in there for your recursive function.
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.
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.
def function(n):
if n%4==1:
return(n**2)
else:
n += 1
return function(n)
if function(6)%2==0:
print(function(6))
else:
print("Hey!")
in your else statement you return nothing. Put the return statement in there for your recursive function.
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.