How do “and” and “or” work when combined in one statement?

前端 未结 7 1701
后悔当初
后悔当初 2020-12-03 11:44

For some reason this function confused me:

def protocol(port):
    return port == \"443\" and \"https://\" or \"http://\"

Can somebody expl

7条回答
  •  -上瘾入骨i
    2020-12-03 12:25

    C and X or Y is the long-running early attempt by Python users to proxy for C ? X : Y

    For the most part it works, except if X is False -- this has led to many bugs in Python code, so in the Python FAQ, you'll find the more correct solution being (C and [X] or [Y])[0] because a list with a single element, regardless of its evaluated Boolean value, is always True! For example: [None] is True but None isn't. The OP's example above works because the string representing X is not empty.

    However, all this changed in Python 2.5, when the ternary or conditional operator was added to the language, allowing you to use the cleaner X if C else Y as stated in other posts here. If you see code using the older format, it's because the user has been a long time Python programmer who hasn't adopted the new syntax yet, they cut-n-paste other old code, or their employer is still using 2.4.x (or earlier releases), etc.

提交回复
热议问题