-5

What is the difference between the following code snippets? (I'm aware that a negative value of bal will be truthy but why would bal ever be negative?)

while spin and bal>0:
    bal = bal - 1
    bal = bal + funciton() #adds either 0 or a positive value to bal
    spin-=1
if (spin==0):
    s=s+1

Snippet 2:

while spin and bal:
    bal = bal - 1
    bal = bal + funciton() #adds either 0 or a positive value to bal
    spin-=1
if (spin==0):
    s=s+1
  • The second case bal will be true for any value other than zero. for e.g bal <0 – mad_ Aug 10 '18 at 20:54
  • if you subtract 1 and then add 0 I'm pretty sure you can eventually go below zero – Lev Levitsky Aug 10 '18 at 20:55
  • ^ But won't we reach zero before reaching a negative value? In which case the expression should evaluate to false –  Aug 10 '18 at 20:55
  • If bal cannot be negative then both are equivalent – mad_ Aug 10 '18 at 20:56
  • Yeah, but I'm getting an incorrect result for snippet 2 –  Aug 10 '18 at 20:58
  • Under the assumption that `bal` starts as a positive integer and the function returns a non-negative integer, the only difference should be in readability. If you are having problems with this code, try printing all variables at every step to see what's going on. – Lev Levitsky Aug 10 '18 at 20:58
  • To diagnose the failure, we need to see the code that fails. The posted code hasn't defined `spin` and `bal`, whose values are critical to the execution. – Prune Aug 10 '18 at 21:12

1 Answers1

2

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.

Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
  • 1
    Or `bal` could also be an `np.uint16` that rolls over at 65536, or it could be some crazy user-defined counter type that acts a lot like an integer within the bounds you're expected to use it but is never falsey, or… So yeah, definitely, as your second sentence suggests, write what you mean, don't write something that happens to do the same thing as what you mean under some unstated assumptions… – abarnert Aug 10 '18 at 21:08