what is the precedence of a ternary operator in this example?

Viewed 484
>>> count = 0
>>> for c in "##.#.":
...     count = count + 1 if c == '.' else 0
... 
>>> print(count)
1
>>> count = 0
>>> for c in "##.#.":
...     count = count + (1 if c == '.' else 0)
... 
>>> print(count)
2

Why doesn't the first example print out a counter of 2?

3 Answers

Conditional expressions have a very low precedence.

So the first expression is actually parsed as:

count = (count + 1) if c == '.' else 0

That will set count to 0 every time c != '.'.

In the first case, count value gets replaced

>>> for c in "##.#.":
...     count = count + 1 if c == '.' else 0
...     print (count)
... 
0
0
1
0
1

Here count gets append

>>> count=0
>>> for c in "##.#.":
...     count = count + (1 if c == '.' else 0)
...     print (count)
... 
0
0
1
1
2
>>> 

Because this corresponds to the True state of if.

(True) if (Condition) else (Else)

count = count + 1 if c == '.' else 0 True status for this (count + 1)

count + (1 if c == '.' else 0) True status for this (1)

Did I tell you a little bit complicated?

Related