Under the assumption that bal
is a positive integer from the start and that function()
returns a positive integer, then both code snippets are indeed equivalent.
Although, if bal
is to be decremented as a counter, you should favor using bal > 0
. This is both safer and more explicit.
Here is what could go wrong otherwise.
bal
could be a float
bal = 0.5
while bal:
bal -= 1
...
Never will the condition bal == 0
be fulfilled.
bal
could be negative from the start.
bal = -1
while bal:
bal -= 1
...
Again bal
will never be falsy since it will always be below 0
.
function
could return a float
Adding an int
and a float
will yield a float
and due to float arithmetic errors it is ill-advised to rely on falsiness of a float.
Here is an example
bal = 0.1
bal += 0.2
bal -= 0.3
bal # 5.551115123125783e-17
bool(bal) # True
You would mathematically expect bal
to be zero, although in float arithmetic it is truthy in that case.