Hero Stradivari
Hero Stradivari

Reputation: 595

if True and if False statements

I've always been confused about using True and False on if statements. For instance, let's say that I've defined a function that returns True or False.

def isEven(number):
    if number % 2 == 0:
        return True
    else:
        return False

Now I need to use that function on one of my code which can only proceed if the number is even. I believe I have seen codes like if isEven(number): proceed etc etc, my question is, is it considered True by default? Or should I keep using if isEven(number) == True

Upvotes: 1

Views: 6492

Answers (4)

Paolo
Paolo

Reputation: 15847

if isEven(number):

will execute the indented code after if when isEven returns True

You don't need to check isEven(number) == True

Upvotes: 0

Simgate
Simgate

Reputation: 188

When you have something like that :

if myboolean : ...

it means "if myboolean is true, then do whatever is after". So it's the same as :

if myboolean==true : ...

Upvotes: 3

Mihai Maruseac
Mihai Maruseac

Reputation: 21460

Both uses are exactly the same. In

if expr:
    pass

first expr is evaluated so you get

if True:
    pass

or

if False:
    pass

no matter what the original expr was.

PS:

Now, I always found the if True: return True pattern obsolete. Why not return True directly. That is:

def isEven(number):
    return (number % 2 == 0)

Upvotes: 3

John La Rooy
John La Rooy

Reputation: 304463

You should just use

if isEven(number):
   # proceed

It only has a possible different meaning if isEven doesn't return True or False

For example 1, 2, 3 etc. are treated as True
None, 0, [] etc are treated as False

Additionally, you have the same type of redundancy in your function

def isEven(number):
    return number % 2 == 0

works just as well. The following works too, but is less clear

def isEven(number):
    return not number % 2

Upvotes: 2

Related Questions