Interesting Things with logic operator in Python

Question: What’s the answer of this code:

parameter and (" " + parameter) or ""

What and and or operator does:

  • a and b returns b if a is True, else returns a.
  • a or b returns a if a is True, else returns b.

So, this expression:
parameter and (" " + parameter) or ""
which is effectively equivalent to:
(parameter and (" " + parameter)) or ""
# A1 A2 B
# A or B
How the expression is evaluated if:

  • parameter - A1 is evaluated to True:
    result = (True and " " + parameter) or ""
    result = (" " + parameter) or ""
    result = " " + parameter
  • parameter - A1 is None:
    result = (None and " " + parameter) or ""
    result = None or ""
    result = ""

As a general suggestion, it’s better and more readable to use A if C else B form expression for conditional expression. So, you should better use:
" " + parameter if parameter else ""
instead of the given expression. See PEP 308 – Conditional Expression for motivation behind the if-else expression.

In conclusion, short-cut is the key to solve this problem.

发表评论

电子邮件地址不会被公开。 必填项已用*标注

17 + 20 =

− 1 = 3