1

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

Hero Stradivari
  • 565
  • 1
  • 6
  • 13
  • You should never test `== True`; you don't need to, and you could run into [comparison operator chaining](http://stackoverflow.com/q/19751556) giving you confusing results. – Martijn Pieters Nov 17 '13 at 23:10

4 Answers4

3

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)
Mihai Maruseac
  • 20,967
  • 7
  • 57
  • 109
3

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 : ...
Simgate
  • 168
  • 1
  • 7
  • How about if I need a False before proceeding to the statement? Should I then use `if myboolean == False` ? – Hero Stradivari Nov 17 '13 at 23:11
  • Exactly. You don't need to do `if myboolean == true`, because it's implicit, but if you need it to be false to continue, you have to do something like that : `if myboolean==false` – Simgate Nov 17 '13 at 23:18
  • 2
    @HeroStradivari It would be idiomatic to use `if not myboolean: ...` – cryptojuice Nov 18 '13 at 00:44
2

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
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
0
if isEven(number):

will execute the indented code after if when isEven returns True

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

Paolo
  • 15,233
  • 27
  • 70
  • 91