Break and Continue: While Loops

Chris Angelico rosuav at gmail.com
Thu Jun 23 12:23:11 EDT 2016


On Fri, Jun 24, 2016 at 1:52 AM, BartC <bc at freeuk.com> wrote:
> On 23/06/2016 12:39, Chris Angelico wrote:
>>
>> On Thu, Jun 23, 2016 at 8:15 PM, BartC <bc at freeuk.com> wrote:
>>>
>>> Actually pretty much any expression can be used, because Python can
>>> interpret almost anything as either True or False. Don't ask for the
>>> rules
>>> because they can be complicated, but for example, zero is False, and any
>>> other number is True. I think.
>>
>>
>> The rules are very simple. Anything that represents "something" is
>> true, and anything that represents "nothing" is false. An empty
>> string, an empty list, an empty set, and the special "None" object
>> (generally representing the absence of some other object) are all
>> false. A string with something in it (eg "Hello"), a list with
>> something in it (eg [1,2,4,8]), etc, etc, are all true.
>
>
> But even with ordinary conditionals, False is False, but [False] is True.
> And [] is False, while [[]] is True. A class instance is always True, even
> when empty. And then "False" is True as well!

[False] is a list with something in it. So is [[]]. "False" is a
string with something in it, and honestly, if you think that ought to
come out falsey, you're asking for magic. I don't know what you mean
by a "class instance", or how it would be empty, but if you're
creating a custom class and it might sometimes represent emptiness,
you need to define either __len__ or __bool__ so the interpreter can
understand what you mean by "empty".

> Maybe I was thinking of 'is' where sometimes the results are unintuitive.
>

Not at all. The 'is' operator tells you whether the left and right
operands are the same object. That's it. Maybe you have unintuitive
situations where you don't realize you have the same object (or don't
realize you have different objects), but the operator itself still has
one very simple rule to follow.

ChrisA



More information about the Python-list mailing list