From 6abfb50fc6a615da53bd63a3d5cf6c669495e415 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 4 Sep 2017 22:31:18 +0530 Subject: [PATCH] Add example: Not Knot! Related to https://github.com/satwikkansal/wtfpython/issues/1 --- README.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/README.md b/README.md index 15eec68..6248820 100755 --- a/README.md +++ b/README.md @@ -1451,6 +1451,35 @@ tuple() --- +### not knot! + +Suggested by @MostAwesomeDude in [this](https://github.com/satwikkansal/wtfPython/issues/1) issue. + +```py +x = True +y = False +``` + +**Output:** +```py +>>> not x == y +True +>>> x == not y + File "", line 1 + x == not y + ^ +SyntaxError: invalid syntax +``` + +#### 💡 Explanation: + +* Operator precedence affects how an expression is evaluated, and `==` operator has higher precedence than `not` operator in Python. +* So `not x == y` is equivalent to `not (x == y)` which is equivalent to `not (True == False)` finally evaluating to `True`. +* But `x == not y` raises a `SyntaxError` because it can be thought of being equivalent to `(x == not) y` and not `x == (not y)` which you might have expected at first sight. +* The parser expected the `not` token to be a part of the `not in` operator (because both `==` and `not in` operators have same precedence), but after not being able to find a `in` token following the `not` token, it raises a `SyntaxError`. + +--- + ### Loop variable resilient to changes Suggested by @tukkek in [this](https://github.com/satwikkansal/wtfPython/issues/11) issue.