checking whether a var is empty or not
David M. Cooke
cookedm+news at physics.mcmaster.ca
Thu Jul 29 22:40:14 EDT 2004
At some point, Bart Nessux <bart_nessux at hotmail.com> 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 equivalent: if var is None, the first doesn't trigger, but
the second does.
Do you mean:
if var is None:
# do something
if not var:
# do something
The first if only triggers if var is the singleton None.
The second if will trigger if var is False, 0, 0.0, 0j, '', [], (), None,
or anything else that has a length of 0 or var.__nonzero__() returns
False. In this case, you're checking if var is false in a boolean
logic context.
If you're checking arguments to a function to see if a non-default
argument has been passed, you probably want the first, like this:
def function(var=None):
if var is None:
# do something to get a default argument
But if you want a flag that's true or false, you want the second:
def function(var):
if var:
# yes, do something
else:
# no, do something else
--
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca
More information about the Python-list
mailing list