0

Coding in Python is pretty structured and straight forward. So every now an then you might run into a possibility for getting the same result with different code.

Would it make any difference, for the functionality of the code, in these if statements:

if root:  
    pass

if root != None:  
    pass

if root is not None:  
    pass

In this case, I only want to check if a value exists.

So to check if a value is empty, these are the opposite options:

if not root:
    pass

if root == None:
    pass

if root is None:
    pass
TayTay
  • 6,882
  • 4
  • 44
  • 65
Johan Vergeer
  • 5,208
  • 10
  • 48
  • 105
  • 1
    Are you talking about [`property` objects](https://docs.python.org/2/library/functions.html#property) or Python values in general? – Martijn Pieters Dec 08 '15 at 13:29
  • Also see [is None vs. ==None](http://stackoverflow.com/q/3257919) – Martijn Pieters Dec 08 '15 at 13:30
  • 1
    Please note that `none` does not equal `None`. This is a keyword that must be capitalized. I edited your question to include the proper syntax, but just an FYI... – TayTay Dec 08 '15 at 13:31
  • @MartijnPieters I have changed the question, in this case I only wish to know if the parameter contains a value. – Johan Vergeer Dec 08 '15 at 13:39
  • 1
    The main thing is: suppose root exists, can it take a value like 0 or [] or ''? – RemcoGerlich Dec 08 '15 at 13:40
  • @RemcoGerlich That is a good question. In this case the value cannot hold something like 0 or []. But if it is for some situations, please feel free to explain. – Johan Vergeer Dec 08 '15 at 13:42
  • Well those values are falsy, just like None is. So if you use `if not root:`, then that detects a None value but also 0; it doesn't work to distinguish between "no value was given" and "a value 0 was given". – RemcoGerlich Dec 08 '15 at 13:53
  • Generally though tests for 'is None' are both the fastest and the most explicit, so it's best to use that, normally. – RemcoGerlich Dec 08 '15 at 13:54
  • always use `is None` or `is not None` rather than `== None` or `!= None` ...otherwise choice of `if var is None` or `if var` comes down desired logic to if you want to e.g. distinguish empty list (as a valid value) from no list at all – Anentropic Dec 08 '15 at 13:59

0 Answers0