[Tutor] beginning to code
On Mon, Sep 18, 2017 at 11:30 PM, Antoon Pardon <antoon.pardon at vub.be> wrote:
> Op 18-09-17 om 14:58 schreef Chris Angelico:
>> On Mon, Sep 18, 2017 at 10:42 PM, Rick Johnson
>> <rantingrickjohnson at gmail.com> wrote:
>>> (2) Python is, in essence, converting the source code
>>> syntax of:
>>> if someObject:
>>> if BOOLEAN_VALUE_OF_SOMEOBJECT:
>>> Which, although the result of such a conversion (a
>>> Boolean) will be perfectly symmetrical with formal logic
>>> statements, the conversion is not obvious, because it
>>> happens behind the curtains.
>> What a surprise. In the context of a statement that has exactly two
>> possible courses of action (either you go into the 'if' block, or you
>> go into the 'else' block (if any)), you use the boolean value of an
>> object. What part of this is not obvious?
> Well that you reduce an object to a boolean value is not obvious to
> begin with. A TypeError because you are treating a non-boolean as
> a boolean would have been more obvious to me.
Sure, but those are basically your only two options. Either you have a
way of interpreting some/all objects as booleans, or you require an
explicit conversion. In Python syntax:
# Interpret all objects as boolean:
if x: pass
# Require explicit conversion or comparison:
if bool(x): pass
if x == True: pass
But not BOTH of the above:
if bool(x) == True: pass
That's pointless. It's not "more explicit". It's just more redundant.
> A second thought is that it isn't obvious that empty strings, lists ...
> should be thought of as falsy. Sometimes I am treating a stream of
> values/objects and when I ask for the next available items, i get
> a string/list. An empty string/list in that context would mean that
> nothing was available, but it is possible that more will be available
> later and so could be treated just like a non-empty list/string.
Yep. That's a philosophical choice; Python has decided that a
container with nothing in it is falsy, on the assumption that you're
more likely to be contrasting [1,2,3] against  than either of the
above against None. Other languages have made other choices. Python is
100% consistent within its native data types - including that, unless
otherwise specified, an object is truthy and the absence of an object
(eg None) is falsy. One notable violation of that rule was that a
datetime.time() representing midnight used to be considered false, but
that was treated as a bug and corrected, since a time of midnight is
not equivalent to a number of zero, but to a point on a clock.
> Once you understand how python does things, you can work with it, but
> IMO the way python does things is IMO not at all that obvious as people
> would like us to think.
Understood - but it's not arbitrary, and you *can* get to know the rules.