checking whether a var is empty or not

Jeff Shannon jeff at ccvcorp.com
Thu Jul 29 22:42:27 EDT 2004


Bart Nessux wrote:

> Are these equivelent? Is one approach prefered over the other
>
> #check to see if var contains something... if so proceed.
> if var is not None:
>     continue
>
> #check to see if var is empty... if so prompt user again.
> if not var:           
>    print "Please specify the amount."
>    ...


They're not quite equivalent.  The second form ('if not var') will 
resolve to be true if var is any value that resolves to false -- this 
could be None, 0, [], {}, '', or some user-defined objects.  The first 
form will only be true if var is None.

This could be significant if, for instance, 0 is a valid value.  You 
might want to initialize var to None, conditionally assign an integer to 
it, and then later see if an integer (including 0) was actually 
assigned.  In that case, you'd need to use the first form.

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list