[Tutor] equality check difference

Chris Fuller cfuller084 at thinkingplanet.net
Sun Apr 20 02:50:42 CEST 2014


On Saturday, April 19, 2014, Vipul Sharma wrote:
> Hello,
> 
> Suppose we want some block of code to be executed when both '*a'* and
> '*b'*are equal to say 5. Then we can write like :
> 
> *if a == 5 and b == 5:*
> *    # do something*
> 
> But a few days ago, I just involuntarily wrote a similar condition check as
> 
> 
> *if a == b and b == 5:*
> *    # do something *
> 
> which made me think, is there any difference between the two ?

Transitivity is one factor, but another one I don't think got mentioned is 
short-circuiting.  When two conditions are joined by an "and" or an "or", 
sometimes only the first condition is actually executed, if the result is 
sufficient to determine the outcome.

If the first condition of an "or" is True, then the result must be True, and no 
further computation is necessary.  For "and", if the first condition is False, 
then the outcome must be False, and evaluation of the other condition does not 
occur.

Most of the time, this doesn't matter.  But if the expressions are expensive 
to compute, or contain "side effects", it can become significant.

Side effects are things computations do that have some effect beyond the 
immediate result.  Print statements are familiar examples.  Changing an 
internal variable in a class instance is another.

Cheers


More information about the Tutor mailing list