[Tutor] equality check difference

Alan Gauld alan.gauld at btinternet.com
Sun Apr 20 00:07:00 CEST 2014


On 19/04/14 21:48, Vipul Sharma wrote:

> *if a == 5 and b == 5:*
> *    # do something*
>
> *if a == b and b == 5:*
> *    # do something *
>
> which made me think, is there any difference between the two ?

Yes.
I don't know how python actually does it but in a general
sense there is not much if any difference when the conditions
are true but if, for example, a is 5 and b is 4 then consider
what happens:

a==5 and b==5
1) check if a==5 -> True
2) check if b==5 -> False
3) skip if block

a==b and b==5
1) check if a == b -> False
2) skip if block

So the second version notionally does one less test for a
false condition. But its arguable less readable so do you
trade readability for a (marginal) speed improvement?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list