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.

3
  • 1
    "null" is a string with value "null". Were you looking for None or '', the empty string? Commented Mar 28, 2016 at 8: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. Commented Mar 28, 2016 at 8: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. Commented Mar 28, 2016 at 9:38

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.