Why does whitespace not matter in this case?

Question:

My question is fairly simple but after looking around a bit I still have no idea why this even compiles- nevermind produce the correct result (Python 3.10).

# Testing conjunction/disjunction boolean values of a and b
a = 1
b = 2

# AND
a == 1and b == 2
True
a == 1and b == 1
False
a == 2and b == 1
False
a == 2and b == 2
False

# OR
a == 1or b == 2
True
a == 1or b == 1
True
a == 2or b == 1
False
a ==2or b == 2
True

Not only does python not mind the lack of whitespace, but it also produces the correct results for both "and" and "or"

Maybe this is due to Python parsing code in some particular way, but I’m not sure.

Asked By: Omaro_IB

||

Answers:

From the language spec:

Whitespace is needed between two tokens only if their concatenation
could otherwise be interpreted as a different token (e.g., ab is one
token, but a b is two tokens).

Answered By: Ture Pålsson
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.