Why does Python allow you to overwrite the value of False and True?

Asked

Viewed 220 times

4

I’m studying Python and in these studies I came across something curious.

> False = True
#Imprime: True

> print(False)
#Imprime: True

> False = bool(0)
> print(False)
#Imprime: False

I mean, I was able to rewrite the value of False giving him the value of True.

In languages such as javascript or PHP cannot be reallocated because False is a language constructor or even a constant.

Why in the Python is it possible to do this? How is it treated False in Python? As a variable?

  • Python implements two essential concepts, Space of Names and Space of Objects. What happens then is that you modified the value of the True/False object then changed the Object in Object Space. So when creating a variable that uses this object, the variable will use the new value and not the original.

1 answer

4


Why in Python is it possible to do this?

Because they are not reserved words, like in PHP or other languages. Are scoped variables with defined values (the documentation puts the word "Constant", but in fact you can have variables with the names True and False).

How it is treated False in Python? As variable?

False in Python is equivalent to the integer 0, and True, whole 1:

int(False)
=> 0
int(True)
=> 1

Addendum: Not valid for any Python

This applies only to Python 2. For Python 3, the following occurs:

PS C:\Users\lsanches> python
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> True = False
  File "<stdin>", line 1
SyntaxError: can't assign to keyword
  • Thank you for the Information of Python 3.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.