1

I have 2 variables: x="null" and y=3

Following which I execute the command below:

if(x and y):
  print 'True'

Output:True

I am looking for guidance to understand this behavior better.

The answer to this question fixed my issue Most elegant way to check if the string is empty in Python?

But I want to understand the behavior of this. I want to know how an AND of "null" and a numeric value of 3 returns in 3 which in turn results in truthify value.

Community
  • 1
  • 1
suprita shankar
  • 1,554
  • 2
  • 16
  • 47
  • 1
    "null" is a string with value "null". Were you looking for `None` or `''`, the empty string? – Bhargav Rao Mar 28 '16 at 08:39
  • Any non empty string can be considered as a `True` boolean value, in the same way that any int which is not `0`. So, `"null"` is just a string like any other, it is different from `None`. – Delgan Mar 28 '16 at 08:41
  • 1
    The string `"null"` has no special significance in Python itself, although of course you are free to give it special significance in your own code. Note that the JSON module will translate `"null"` in a JSON object to `None`, and vice versa; thus `import json;print(json.loads('null'))` prints `None`. – PM 2Ring Mar 28 '16 at 09:38

2 Answers2

4

A non empty string is always True in python. So "null" evaluates to True in a boolean operation, just as "banana"

galinette
  • 8,896
  • 2
  • 36
  • 87
2

"" is an empty string, "null" is not:

In[2]: bool("")
Out[2]: False
In[3]: bool("null")
Out[3]: True

Playing with the console to test your code behaviour is a good practice.

Netwave
  • 40,134
  • 6
  • 50
  • 93