Syntax Errors in Logical Operators

Python favours letters and meaningful keywords for the logical operators, and all of them return a value depending on the conditions:

  1. not: The opposite of a condition, the reverse of the logical state of its operand. If the condition is True, it returns False, or vice versa.
  2. and: It needs to compare two operands, It returns True if both operands are True.
  3. or: It’s similar to and, but it returns True if at least one of the operands is True.

The operands do not have to be boolean, Python will return the condition itself through the comparison logic to keep the code writing simple. Now let’s look at this output to see the difference between not and the other operators, focusing on the position of the hats (^):

>>> not
  File "<stdin>", line 1
    not
       ^
SyntaxError: invalid syntax

>>> and
  File "<stdin>", line 1
    and
    ^^^
SyntaxError: invalid syntax

>>> or
  File "<stdin>", line 1
    or
    ^^
SyntaxError: invalid syntax

>>> or 0
  File "<stdin>", line 1
    or 0
    ^^^
SyntaxError: invalid syntax

The syntax error starts in the first character of and and or, but the end of not, after t. Is this normal? Absolutely, yes. As I said before, we don’t need a comparison for using not, but we can not say the same thing for the others, the keyword should be between in two conditions. Now let’s try to give a condition for not to solve the syntax error:

>>> bool(1)
True

>>> not 1
False

>>> bool(0)
False

>>> not 0
True

1 is a truthy value, it’s something like YES or ON in programming logic, but it returned False when we added not keyword before 1. I am aware that I am explaining very simple and boring things but please be patient. Let’s make the syntax a bit confusing:

>>> not(1)
False

>>> not(0)
True

>>> not()
True

>>> bool()
False

Wait.. Is there also a built-in function for not? No, it’s definitely not a function. Honestly, I would expect a syntax error because of the missing space between the not keyword and the parentheses, but the formatter tools will probably add it automatically anyway. So, you can consider using parentheses to group the conditions, that’s all. And, when you ran not with an empty parentheses, it will return always True because empty tuples, lists, dictionaries are falsy values:

>>> not{}
True

>>> not[]
True

>>> not      ()
True

The best thing to do is to use a code formatter and read the code that way. This is not always possible, so we have to get our eyes used to strange syntax. Let me end the article with a more ugly syntax (but meaningful):

if not(False or False) and(True):
    print("This will print")

Will it print the expected output, or raise a syntax error?