Home > Net >  Why does this function return "None" if the number isn't even? How can I make it retu
Why does this function return "None" if the number isn't even? How can I make it retu

Time:12-18

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?

CodePudding user response:

1st question: If you did not specify any return in a Python function, it will return none.

2nd question: You can do return n%2 == 0, which will return true if n is even number and false if n is odd number.

CodePudding user response:

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.

CodePudding user response:

To answer your question: you are trying to get a False value out of something that doesn't have a value at all. Therefore it is 'none'. Just because it is true doesn't necessarily mean it's false.

There are two common ways to go about doing this though:

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

This will evaluate to either True or False depending on the parameter n and then it will return the value.

The other way:

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

Here, if we pass the if check, the function will return True and it will never make it to the return False statement. Vice versa, if we don't pass the if check we will instead return False. I prefer to write code this way because it's a little more specific in what the code is doing. Either way works though

  • Related