>>> 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?
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 != '.'
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With