Search code examples
pythonmontecarlo

Difference between x>0 and x (as a condition) in python?


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

Solution

  • 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.