Overriding True and False ?

Deborah Swanson python at deborahswanson.net
Mon Jan 30 02:50:21 EST 2017


Irv Kalb wrote, on Sunday, January 29, 2017 9:04 PM
> 
> I teach intro to programming using Python.  In my first 
> assignment, students are asked to assign variables of 
> different types and print out the values.  
> 
> 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.
> 
> You cannot assign new values to other keywords.  Simple tests 
> of things like:
> 
> for = 5
> 
> while = 2
> 
> not = 3
> 
> As expected, all result in SyntaxError: invalid syntax.  Why 
> would Python allow you to override the values of True and 
> False?  I wonder if this is some sort of historical thing as 
> these are the only keywords besides None that are uppercased. 
>  This line:
> 
> None = 5
> 
> Even gives a special SyntaxError: cannot assign to None
> 
> Just curious,
> 
> Irv

Just guessing, but in the examples you give in Python 2.7, substitute
strings are syntactically correct in print statements, but:

5 in list('abc'):

2 True:

if a 3 b:

would all be syntactical errors.

As is 'None = 5'.

Looks like the moral of the story is that in Python 2.7 you can redefine
keywords, so long as you don't get any syntax errors after (or during)
redefinition.




More information about the Python-list mailing list