Nick
Nick

Reputation: 687

Difference between if not: and if False:

I have a probably quite simple question but was wondering between the difference of these two statements:

if not os.path.isfile(file):
  #Do some stuff
if os.path.isfile(file) is False:
  #Do some stuff

What are the differences (if any) between the two? To my understanding they both return a True or False value, so is it just a matter of preference or are there any significant differences?

Upvotes: 2

Views: 9749

Answers (4)

blue note
blue note

Reputation: 29071

In python (and other dynamic languages) there is the concept of truthy/falsy value. True/False are not the only things that evaluate as true/false

if not []: 
   print("this will be printed")

if [] is False:
   print("this won't")

Another problem is that you should compare with x == False, and not x is False. The False is a singleton object in the current implementation of CPython, but this is not guaranteed by the specification.

Upvotes: 4

milanbalazs
milanbalazs

Reputation: 5329

You should know: False == 0 == None in case of if condition. If you use if not, you can cover all version of False (zero value). If you use == False you cannot handle the 0 or None. if not is recommended. The is operator is a different story (is not same as ==) but you can read more details on this link: Understanding Python's "is" operator

Upvotes: 0

molbdnilo
molbdnilo

Reputation: 66371

It's usually better to use the first, since it works even if you're not checking an actual boolean value in a Python implementation where False is a singleton object.
Uniformity is good, and so is portability.

>>> if 0 is False: print "false"
>>> if not 0: print "false"
false
>>> if [] is False: print "false"
>>> if not []: print "false"
false
>>> if "" is False: print "false"
>>> if not "": print "false"
false

It also protects against mishaps like this:

>>> False = 1
>>> True == False
True

Upvotes: 2

bracco23
bracco23

Reputation: 2211

In your case, since we know os.path.isfile returns True or False, there is no difference.

In general, there are a lot of objects in python which, when interpreted as boolean, will evaluate to False.

Think of this:

empty_list = []
if not empty_list:
    print('List is not empty')
if empty_list is False:
    print('List is False')

Among the others, None, "" and [] will evaluate to False.

So testing with not variable is usually the preferred way.

Upvotes: 1

Related Questions