Overriding True and False ?
ian.g.kelly at gmail.com
Mon Jan 30 11:12:50 EST 2017
On Jan 30, 2017 1:32 AM, "Irv Kalb" <Irv at furrypants.com> wrote:
I teach intro to programming using Python. In my first assignment,
students are asked to assign variables of different types and print out the
One student (who really did not understand Booleans) turned in the
following for his/her interpretation of Booleans (Python 2.7):
True = 'shadow'
False = 'light'
print "If the sun is behind a cloud, there is", True
print "If it is a clear day, there is", False
And it printed:
If the sun is behind a cloud, there is shadow
If it is a clear day, there is light
It seems very odd that Python allows you to override the values of True and
False. In the code, True and False were clearly recognized as keywords as
they were colored purple. But there was no error message.
Plenty of people have remarked that this is fixed in Python 3, but nobody
that I see has explained yet the reason for this behavior in the first
place. True and False are not keywords in Python 2 for backward
compatibility. Many versions ago, Python did not define True and False at
all. It was common in that era to lead scripts with:
False = 0
True = 1
To define useful boolean constants. When the built-in constants were added,
the developers did not want to break programs that followed this pattern.
This is also the reason why bool is a subclass of int -- so that False == 0
and True == 1 remain true for programs that depend on this.
More information about the Python-list