Search code examples
pythonfunctionreturnbooleanlocal-variables

Why does this function return "None" if the number isn't even? How can I make it return "False" without using an else condition?


def my_function(n):
    if(n % 2 == 0):
        return True

print(my_function(2))
print(my_function(5))

Output:

True
None

I understand that 'False' has to be explicitly specified to be returned by the function but don't exactly understand why.Can this function be made to return false without an else loop incorporated?


Solution

  • def my_function(n):
        if(n % 2 == 0):
            return True
        return False
    

    Since it is only one return indication, otherwise it returns none, 'nothing'. Here we have forced it to return False otherwise.