[Tutor] evaluating AND

Terry Carroll carroll at tjc.com
Fri Sep 14 00:04:02 CEST 2007


On Thu, 13 Sep 2007, Orest Kozyar wrote:

> Given a variable x that can either be None or a tuple of two floats [i.e.
> (0.32, 4.2)], which syntax is considered most appropriate under Python
> coding standards?
> 
> if x and x[0] > 0:
> 	pass
> 
> =====OR=====
> 
> if x:
> 	if x[0] > 0:
> 		pass

I would like either one if instead of "if x" you used "if x is not None"; 
that seems a lot easier to me to read.  It's a bit jarring to see the same 
variable used in one expression as both a boolean and a list/tuple.

Besides, suppose somehow x got set to zero.  It would pass without error, 
something you wouldn't want to have happen.  Even if you've set things up 
so that it couldn't happen, it's not obvious from looking at this code 
that it couldn't happen.

If you really want to test for x being non-None, test for x being 
non-None.



More information about the Tutor mailing list