dorothy
dorothy

Reputation: 1243

Comparing True False confusion

I have some confusion over testing values that are assigned False, True

To check for True value, we can simply just

a = True
if (a):

how about False?

a=False
if (a) <--- or should it be if (a==False), or if not a ?

Upvotes: 9

Views: 25603

Answers (3)

falsetru
falsetru

Reputation: 368954

use not:

if not a:
    ....
    # If a is the empty value like '', [], (), {}, or 0, 0.0, ..., False
    # control flow also reach here.

or is False:

if a is False:
    ....

Upvotes: 7

rlms
rlms

Reputation: 11060

To check for if a value is true:

if a:
    pass

To check if a value is not true:

if not a:
    pass

However, not a: is True (and true) for values other than False, eg. None, 0, and empty containers.

If you want to check if a value is True or False (although you generally don't) try:

if a is True:
    pass

or

if a is False:
    pass

Edit: for checking if a value is True or False it seems you should use if isinstance(a, bool) and a, and if isinstance(a, bool) and not a

Upvotes: 1

Burhan Khalid
Burhan Khalid

Reputation: 174624

From the Python Style Guide:

For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

Yes: if not seq:
     if seq:

No: if len(seq)
    if not len(seq)

[..]

Don't compare boolean values to True or False using ==.

Yes: if greeting:
No: if greeting == True:
Worse: if greeting is True:

Upvotes: 32

Related Questions