Confusion on printing boolean literals in python

Viewed 287

In python shell mode, I tried using the command print(true) which I knew would not work because of absence of quotes and so showed a error, but when I used print(True) it displayed True on the screen. Can anyone please explain to me what is going on as I am just a beginner to python.

Edit: I searched for different keywords and tried them with print() but all words like and,as,assert,break showed a syntax error but only None worked and printed Can someone please explain this. 1]

5 Answers

It is happening because True is a reserved keyword.

It doesn't require quotes while true is just like a random string for the compiler.

That is why print(True) is giving you output as True

print(true) gives the output as this NameError: name 'true' is not defined

True is a reserved keyword. It is the Boolean value True and is opposite False. Lowercase true is not a reserved keyword and will cause an error because it appears to python as an undeclared variable

All keywords in Python are lower in case except True and False. That's why print(true) doesn't work and print(True) works.

In python, True is a keyword. This means when you try to execute printing True the python understands the user is telling me to print the boolean value True. But when you try to print true at that time python understands, ok the user is telling me to print a string true and it found out that as it is a string so you forgot to give ' at the first and last of the string. That's why it is giving syntax errors.

So the theory is True is a python boolean value and a keyword and true is a simple string

Python has a set of keywords that are reserved words that cannot be used as variable names, function names, or any other identifiers.

Some examples are:

if
else
for
while
and
etc...

Boolean values fall into this category. In Python, boolean values are capitalized. When you run print(True), python recognizes True as a keyword and prints the boolean value it represents.

When you run print(true) python doesn't match it to any reserved keywords and assumes it be a variable. However, in this case true has not be previously defined or assigned a value. Since Python doesn't know what true means it throws an error

Related