If X:, VS If X == True, VS If X Is True

if x:, vs if x == True, vs if x is True

The following values in Python are false in the context of if and other logical contexts:

  • False
  • None
  • numeric values equal to 0, such as 0, 0.0, -0.0
  • empty strings: '' and u''
  • empty containers (such as lists, tuples and dictionaries)
  • anything that implements __bool__ (in Python3) to return False, or __nonzero__ (in Python2) to return False or 0.
  • anything that doesn't implement __bool__ (in Python3) or __nonzero__ (in Python2), but does implement __len__ to return a value equal to 0

An object is considered "false" if any of those applies, and "true" otherwise, regardless of whether it's actually equal to or identical with False or True

Now, if you've arranged that x is necessarily one of the objects True or False, then you can safely write if x. If you've arranged that the "trueness" of x indicates whether or not to perform the operation, regardless of type, then you can safely write if x. Where you can write that you should prefer to do so, since it's cleaner to read.

Normally, if it is allowed for x to take the value True then you're in one of those two cases, and so you would not write if x is True. The important thing is to correctly document the meaning of x, so that it reflects the test used in the code.

Python programmers are expected to know what's considered true, so if you just document, "runs the function if x is true", then that expresses what your original code does. Documenting it, "runs the function if x is True" would have a different meaning, and is less commonly used precisely because of the style rule in PEP8 that says to test for trueness rather than the specific value True.

However, if you wanted the code to behave differently in the case where x is an empty container from the case where it is None, then you would write something like if x is not None.

What is the difference between if x == True and if x:

The difference is that if x: checks the truth value of x. The truth value of all integers except 0 is true (in this case, the 2).

if x == True:, however, compares x to the value of True, which is a kind of 1. Comparing 2 == 1 results in a false value.

To be exact, there are two adjacent concepts:
* the one is the "truth value", which determines the behaviour of if, while etc.
* the other are the values True and False, which have the respective truth values "true" and "false", but are not necessary equal ot other true resp. false values.

If you absolutely need to check for the exact values of True and False for whatever reason, you can do so with if x is True or if x is False. This ensures that if y is exactly True will pass the test, if it is 1, it won't.

Why is if(x) different from if(x==True) in Python?

Simply put, in general, you cannot say that if x has the same meaning as if x == True in Python. Their result depends on how x's methods __bool__ and __eq__ are defined, respectively.

For classes themselves, like bool or int (i.e. the type, not an object of that class), __bool__ is defined to always return True; while the comparison against True returns False.

Therefore:

if int == True: print("NOT printed")
if int: print("printed")
if bool(int): print("printed") # equivalent to the previous one

Is if(x) same as if(x==true)?

Yes,

if(x) {

}

is the succinct equivalent of

if(x == true) {

}

As @Sotirios points out, they are different at the bytecode level. Consider the following Java class:

class Test { 
public void foo() {
boolean x = true;
if(x == true) {
}
}
}

emits:

  public void foo();
Code:
0: iconst_1
1: istore_1
2: iload_1
3: iconst_1
4: if_icmpne 7
7: return

vs

class Test { 
public void foo() {
boolean x = true;
if(x) {
}
}
}

which emits:

  public void foo();
Code:
0: iconst_1
1: istore_1
2: iload_1
3: ifeq 6
6: return

I don't think this has any bearing on the performance or correctness of the program.

JavaScript if(x) vs if(x==true)

They are not at all equal.

if (x)

checks if x is Truthy where as the later checks if the Boolean value of x is true.

For example,

var x = {};
if (x) {
console.log("Truthy");
}
if (x == true) {
console.log("Equal to true");
}

Not only an object, any string (except an empty string), any number (except 0 (because 0 is Falsy) and 1) will be considered as Truthy, but they will not be equal to true.

As per ECMA 5.1 Standards, in if (x), Truthiness of x will be decided, as per the following table

+-----------------------------------------------------------------------+
| Argument Type | Result |
|:--------------|------------------------------------------------------:|
| Undefined | false |
|---------------|-------------------------------------------------------|
| Null | false |
|---------------|-------------------------------------------------------|
| Boolean | The result equals the input argument (no conversion). |
|---------------|-------------------------------------------------------|
| Number | The result is false if the argument is +0, −0, or NaN;|
| | otherwise the result is true. |
|---------------|-------------------------------------------------------|
| String | The result is false if the argument is the empty |
| | String (its length is zero); otherwise the result is |
| | true. |
|---------------|-------------------------------------------------------|
| Object | true |
+-----------------------------------------------------------------------+

Note: The last line object, which includes both objects and Arrays.

But in the later case, as per The Abstract Equality Comparison Algorithm,

If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).

value of x will be converted to a number and that number will be checked against true.

Note:

In JavaScript, true is 1 and false is 0.

console.log(1 == true);
# true
console.log(0 == false);
# true

Boolean identity == True vs is True

If you want to determine whether a value is exactly True (not just a true-like value), is there any reason to use if foo == True rather than if foo is True?

If you want to make sure that foo really is a boolean and of value True, use the is operator.

Otherwise, if the type of foo implements its own __eq__() that returns a true-ish value when comparing to True, you might end up with an unexpected result.

As a rule of thumb, you should always use is with the built-in constants True, False and None.

Does this vary between implementations such as CPython (2.x and 3.x), Jython, PyPy, etc.?

In theory, is will be faster than == since the latter must honor types' custom __eq__ implementations, while is can directly compare object identities (e.g., memory addresses).

I don't know the source code of the various Python implementations by heart, but I assume that most of them can optimize that by using some internal flags for the existence of magic methods, so I suspect that you won't notice the speed difference in practice.

In python, in what order would x = y == true evaluate

It is more obvious if you add parentheses according to operator precedence:

x = (y == "true")

y == "true" is an expression that evalutates to a bool, so it will be True or False. That value is then assigned to x.

Or in more words:

if y == "true":
x = True
else:
x = False

Is the conditional if(x) different than if(x == true)?

EDIT: Below only holds true for the original question, in which the === operator was used.

The first one will execute the body of the if-statement if something is "truthy" while the second will only execute it if it is equal in type and value to true.

So, what is "truthy"? To understand that, you need to know what is its opposite: falsey. All values in JavaScript will be coerced into a Boolean value if placed in a conditional expression. Here's a list of falsey values:

  • false
  • 0 (zero)
  • "" (empty string)
  • null
  • undefined
  • NaN

All other values are truthy, though I've probably missed some obscure corner case that someone will point out in the comments.

Here's my answer to the updated question:

The conditional if (something) and if (something == true) are equivalent, though the second is redundant. something will be type coerced in the same way in either case. This is wrong. See Felix Kling's answer.



Related Topics



Leave a reply



Submit