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

前端 未结 7 1700
后悔当初
后悔当初 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条回答
  • 2020-12-03 12:35

    It's an old-ish idiom; inserting parentheses to show priority,

    (port == "443" and "https://") or "http://"
    

    x and y returns y if x is truish, x if x is falsish; a or b, vice versa, returns a if it's truish, otherwise b.

    So if port == "443" is true, this returns the RHS of the and, i.e., "https://". Otherwise, the and is false, so the or gets into play and returns `"http://", its RHS.

    In modern Python, a better way to do translate this old-ish idiom is:

    "https://" if port == "443" else "http://"
    
    0 讨论(0)
提交回复
热议问题