Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

>>> 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?

like image 891
lostdong12 Avatar asked Sep 06 '25 03:09

lostdong12


1 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 != '.'.

like image 195
Yam Mesicka Avatar answered Sep 07 '25 21:09

Yam Mesicka