Can I use True and False like normal variables?

Question

True and False seem like valid variable names, so can these be used like normal variables in Python?

Answer

No, True and False cannot be used like other variables. Reassigning these will result in a SyntaxError.

In Python, True and False are known as reserved words or keywords, which means they cannot be used as ordinary identifiers and cannot be reassigned like a variable.

This is an important implementation, because it would prevent issues like accidentally updating the values to something different, like True = 100 or False = True which would be an inconvenience when we need to utilize them in a program later on.

22 Likes

“True” and “False” are reserved words, however “true” and “false” are not, the first letter capitalization appears to be the difference.

5 Likes

Without quotes, though. True and False. Their numeric equivalents are 1 and 0.

int(True)     # 1
int(False)    # 0
8 Likes

We can also go in the opposite direction:

>>> bool(1)
True
>>> bool(0)
False

Also note this:

>>> bool(7)
True
>>> bool([])
False
>>> bool(None)
False
>>> bool({})
False
>>> bool(())
False
>>> bool([0])
True
4 Likes

I used quotation marks not to indicate a string, but to specify the words being referred to.

I can name a variable:
true = 10

but I can not name a variable:
True = 10

My apologies for any confusion caused by using quotation marks.

3 Likes

No problem; I thought as much but felt the need to interject. Happily, @appylpye added to the topic to bring about balance.

Point taken. We cannot redefine a primitive.

1 = 0

'a' = 'b'
3 Likes

I see that even in the forum syntax is important. Always learning and improving! :grinning::grinning::grinning:

5 Likes

While there is absolutely nothing wrong with using true as a variable, i will rather avoid it so as to avoid room for confusion (even though it shouldn’t cause any confusion). Simplicity and precision makes our code better

2 Likes

This is a very good point, while it could be used, for all intents and purposes it is a terrible variable name that could very easily lead to confusion and mistakes.

2 Likes

2 posts were split to a new topic: [PENDING] Typo in Python 3 Boolean Variables Lesson