Why Does ('0' ? 'A':'B') Behave Different Than ('0' == True ? 'A':'B')

Why does ('0' ? 'a' : 'b') behave different than ('0' == true ? 'a' : 'b')

First, for completeness:

('0' ? 'a' : 'b') 

is 'a', because '0' is a non-empty string, which always evaluates to true:

String: The result is false if the argument is the empty String (its length is zero);
otherwise the result is true.


Now to '0' == true.

Two type conversions will take place here. We can follow this in the specification, section 11.9.3, The Abstract Equality Comparison Algorithm.

The operands are denoted as x and y (x == y).

In our case, x is a string ('0') and y is a Boolean (true). Hence step 7 is executed:

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

When booleans are converted to numbers, the following conversion takes place:

Boolean: The result is 1 if the argument is true. The result is +0 if the argument is false.

Now we have

'0' == 1

which matches the condition in step 5:

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

How strings are converted to numbers is more complex but of course can also be found in the specification.

So the final comparison is

0 == 1

which is false (step 1. a. vi.)

In JavaScript, why is 0 equal to false, but when tested by 'if' it is not false by itself?

The reason is because when you explicitly do "0" == false, both sides are being converted to numbers, and then the comparison is performed.

When you do: if ("0") console.log("ha"), the string value is being tested. Any non-empty string is true, while an empty string is false.

Equal (==)

If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

(From Comparison Operators in Mozilla Developer Network)

Why == 0 is false in javascript?

Why “” == “0” is false in javascript?

Because the operands are two strings with different content. Type coercion only takes place if the data types of the operands are different.

Related questions:

  • Why does ('0' ? 'a' : 'b') behave different than ('0' == true ? 'a' : 'b')
  • '\n\t\r' == 0 is true?

If "" evaluates to false and "0" evaluates to false the logic predicts that it is the same as i write false == false

Lets have a look how the comparisons are actually resolved:

"" == false is coerced to 0 == 0

"0" == false is coerced to 0 == 0

false == false: same data type, hence the values are directly compared

As you can see "0" doesn't "evaluate" to false, it is converted to an integer, and that value is compared. ("" does evaluate to false (empty string) but when converted to a number, it is 0).

There is a big difference between converting a value to a boolean and comparing a value to a boolean. Most obvious example: !!"0" (true) and "0" == false (true).

When you compare values of different datatypes with loose comparison (==), they are always coerced to numbers (or potentially strings, if you are comparing an object with a string).

Have a look at the specification for more information about the comparison algorithm.

How are iloc and loc different?

Label vs. Location

The main distinction between the two methods is:

  • loc gets rows (and/or columns) with particular labels.

  • iloc gets rows (and/or columns) at integer locations.

To demonstrate, consider a series s of characters with a non-monotonic integer index:

>>> s = pd.Series(list("abcdef"), index=[49, 48, 47, 0, 1, 2]) 
49 a
48 b
47 c
0 d
1 e
2 f

>>> s.loc[0] # value at index label 0
'd'

>>> s.iloc[0] # value at index location 0
'a'

>>> s.loc[0:1] # rows at index labels between 0 and 1 (inclusive)
0 d
1 e

>>> s.iloc[0:1] # rows at index location between 0 and 1 (exclusive)
49 a

Here are some of the differences/similarities between s.loc and s.iloc when passed various objects:









































































<object>descriptions.loc[<object>]s.iloc[<object>]
0single itemValue at index label 0 (the string 'd')Value at index location 0 (the string 'a')
0:1sliceTwo rows (labels 0 and 1)One row (first row at location 0)
1:47slice with out-of-bounds endZero rows (empty Series)Five rows (location 1 onwards)
1:47:-1slice with negative stepthree rows (labels 1 back to 47)Zero rows (empty Series)
[2, 0]integer listTwo rows with given labelsTwo rows with given locations
s > 'e'Bool series (indicating which values have the property)One row (containing 'f')NotImplementedError
(s>'e').valuesBool arrayOne row (containing 'f')Same as loc
999int object not in indexKeyErrorIndexError (out of bounds)
-1int object not in indexKeyErrorReturns last value in s
lambda x: x.index[3]callable applied to series (here returning 3rd item in index)s.loc[s.index[3]]s.iloc[s.index[3]]

Replacements for switch statement in Python?

Python 3.10 (2021) introduced the match-case statement which provides a first-class implementation of a "switch" for Python. For example:

def f(x):
match x:
case 'a':
return 1
case 'b':
return 2
case _:
return 0 # 0 is the default case if x is not found

The match-case statement is considerably more powerful than this simple example.


The original answer below was written in 2008, before match-case was available:

You could use a dictionary:

def f(x):
return {
'a': 1,
'b': 2,
}[x]

Why would ternary (0 ? yes : no) return yes in javascript?

Non-empty strings are truthy. "0" is not 0.

However, comparison will coerce 0 to a number.

Note, the only string which can be coerced to true during comparison is "1". (Please let me know if there are edge cases I'm missing!)

"true" == true // false
"foo" == true // false
"0" == true // false
"1" == true // true

What does axis in pandas mean?

It specifies the axis along which the means are computed. By default axis=0. This is consistent with the numpy.mean usage when axis is specified explicitly (in numpy.mean, axis==None by default, which computes the mean value over the flattened array) , in which axis=0 along the rows (namely, index in pandas), and axis=1 along the columns. For added clarity, one may choose to specify axis='index' (instead of axis=0) or axis='columns' (instead of axis=1).

+------------+---------+--------+
| | A | B |
+------------+---------+---------
| 0 | 0.626386| 1.52325|----axis=1----->
+------------+---------+--------+
| |
| axis=0 |
↓ ↓

Detecting an undefined object property

The usual way to check if the value of a property is the special value undefined, is:

if(o.myProperty === undefined) {
alert("myProperty value is the special value `undefined`");
}

To check if an object does not actually have such a property, and will therefore return undefined by default when you try to access it:

if(!o.hasOwnProperty('myProperty')) {
alert("myProperty does not exist");
}

To check if the value associated with an identifier is the special value undefined, or if that identifier has not been declared:

if(typeof myVariable === 'undefined') {
alert('myVariable is either the special value `undefined`, or it has not been declared');
}

Note: this last method is the only way to refer to an undeclared identifier without an early error, which is different from having a value of undefined.

In versions of JavaScript prior to ECMAScript 5, the property named "undefined" on the global object was writeable, and therefore a simple check foo === undefined might behave unexpectedly if it had accidentally been redefined. In modern JavaScript, the property is read-only.

However, in modern JavaScript, "undefined" is not a keyword, and so variables inside functions can be named "undefined" and shadow the global property.

If you are worried about this (unlikely) edge case, you can use the void operator to get at the special undefined value itself:

if(myVariable === void 0) {
alert("myVariable is the special value `undefined`");
}

How can I map True/False to 1/0 in a Pandas DataFrame?

A succinct way to convert a single column of boolean values to a column of integers 1 or 0:

df["somecolumn"] = df["somecolumn"].astype(int)

What is the difference between null and undefined in JavaScript?

undefined means a variable has been declared but has not yet been assigned a value :

var testVar;
console.log(testVar); //shows undefined
console.log(typeof testVar); //shows undefined


Related Topics



Leave a reply



Submit