while var, but var ==16 != true

John Machin sjmachin at lexicon.net
Mon Jul 14 04:08:24 EDT 2008


On Jul 14, 3:32 pm, Tim Roberts <t... at probo.com> wrote:
> maestro <notnorweg... at yahoo.se> wrote:
>
> >why does this work?  "while p" = "while p != 0" ? 1 is True and 0 is
> >false in python but other numbers have no boolean value so why doesnt
> >it abort.
>
> Because your statement is incorrect.  Everything has a boolean value in
> Python.  0, None, False, '' (empty string), [] (empty list), () (empty
> tuple), and {} (empty dictionary) all have a False value.  Everything else
> has a True value.

Not quite; for example:

>>> bool(set())
False
>>>

According to section 5.10 of the Reference Manual:
"""
In the context of Boolean operations, and also when expressions are
used by control flow statements, the following values are interpreted
as false: False, None, numeric zero of all types, and empty strings
and containers (including strings, tuples, lists, dictionaries, sets
and frozensets). All other values are interpreted as true.
"""

... and for the definition for what a user-written class needs to do,
see section 3.4.1:
"""
__nonzero__( self)

Called to implement truth value testing, and the built-in operation
bool(); should return False or True, or their integer equivalents 0 or
1. When this method is not defined, __len__() is called, if it is
defined (see below). If a class defines neither __len__() nor
__nonzero__(), all its instances are considered true.
"""

Cheers,
John



More information about the Python-list mailing list