0
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?

  • 2
    If you don't explicitly return something, it returns `None`. What is unclear about that? – gre_gor Dec 18 '21 at 04:16
  • Related: [Function returns None without return statement](https://stackoverflow.com/q/7053652/15497888) – Henry Ecker Dec 18 '21 at 04:17
  • `return False`? But why do you not want to use an else? There's nothing wrong with it, and indeed if you always considered the `else` this problem wouldn't have happened... – juanpa.arrivillaga Dec 18 '21 at 04:44

3 Answers3

3

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.

ytan11
  • 908
  • 8
  • 18
3
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.

Luke Singham
  • 1,536
  • 2
  • 20
  • 38
Schart
  • 56
  • 1
  • 3
1

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 isn't 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

Rhett Harrison
  • 430
  • 4
  • 19