On Tue, Oct 6, 2009 at 2:40 AM, Vern Ceder <vce...@canterburyschool.org>wrote:
> Dave Angel wrote: > > Now in this case where it is only used as boolean checks which would be >>>> the most pythonic way if writing these checks? >>>> >>>> >>> The shorter version may be preferable, but it doesn't generally give the >> same results. Without knowing the possible data, these substitutions are >> not safe. >> >> For example, replacing "if not n == 0" with "if n" >> >> will give different results for values of "", [] and so on. It WILL >> work if you know that n is an int or float, however. >> >> DaveA >> > > True, I took the OP's statement that they were to be used "only as boolean > checks" to mean that there was no type mixing going on. Personally, I would > say that checking a list or string for equality (or lack thereof) with 0 is > even less "preferable". ;) > > Otherwise, one would at least prefer "if n != 0" to "if not n == 0", I > would think. > Actually, I just realized that "not" has higher precedence than "==" so this is really checking if (not n) is equal to 0, not if (n == 0) is (not) True. So essentially "not n" is evaluated and is turned into a bool, which is then compared to 0, which is the same as False in a boolean context, but "n != 0" is comparing n to 0, where n may not be the same type (eg. a string). I'm not sure if there's a situation where this difference matters, but I feel like there might be. Anyone have some counter-examples to n != 0 being the same as "not n == 0"?
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor