bool and int
2QdxY4RzWzUUiLuE at potatochowder.com
2QdxY4RzWzUUiLuE at potatochowder.com
Thu Jan 26 15:31:37 EST 2023
On 2023-01-26 at 12:12:30 -0500,
Dino <dino at no.spam.ar> wrote:
> On 1/25/2023 5:42 PM, Chris Angelico wrote:
>
> >
> > Try this (or its equivalent) in as many languages as possible:
> >
> > x = (1 > 2)
> > x == 0
> >
> > You'll find that x (which has effectively been set to False, or its
> > equivalent in any language) will be equal to zero in a very large
> > number of languages. Thus, to an experienced programmer, it would
> > actually be quite the opposite: having it NOT be a number would be the
> > surprising thing!
>
> I thought I had already responded to this, but I can't see it. Weird.
>
> Anyway, straight out of the Chrome DevTools console:
>
> x = (1>2)
> false
>
> x == 0
> true
>
> typeof(x)
> 'boolean'
>
> typeof(0)
> 'number'
>
> typeof(x) == 'number'
> false
>
> So, you are technically correct, but you can see that JavaScript - which
> comes with many gotchas - does not offer this particular one.
When you start a new language, try to start from the beginning. Yes,
you know other languages, to varying degrees, and the language you are
learning is very likely similar, at least superficially, in some way or
another, to one of those other languages. Use that existing knowledge
to the extent that it is useful; be prepared to forget everything you
know.
Python's choice of type hierarchy is not at all uncommon, and it's only
a gotcha if you come in with a predetermined idea of how certain things
"should" work. I've already noted that writing FORTRAN in any language
is a meme.
For a completely different take on booleans, take a look at Python's
logical "and" and "or" operators (*not* the arithmetic "|" and "&"
operators), which only sometimes return an actual boolean value. Then
compare them to the "any" and "all" builtins, which came along much
later. Idiomatic Python uses the right tool for the job *in Python*,
whether or not that same tool is or isn;'t the right tool for the same
job in some other language.
Python is like Lisp in that it (Python) has strong dynamic typing. From
my Common Lisp REPL:
CL-USER> (let ((x (< 1 2)))
(cons x (type-of x)))
(T . BOOLEAN)
CL-USER> (let ((x (> 1 2)))
(cons x (type-of x)))
(NIL . NULL)
In English, the canonical "true" value in Lisp is T, and its type is
BOOLEAN. Likewise, the canonical "false" value in Lisp is NIL, and its
type is NULL. Out of the box, Lisp will not convert T or NIL to a
number.
More information about the Python-list
mailing list