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

前端 未结 7 1723
后悔当初
后悔当初 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:11

    This is an ugly hack that is not recommended. It works because of the short-circuiting behaviour of and and or and that they return the one of their arguments rather than a boolean value. Using this technique gives a risk of introducing hard-to-find bugs, so don't use it in new code.

    Here's an example of how the and/or idiom can give an unexpected result:

    >>> foo = 'foobar'
    >>> bar = 'foobar'
    >>> x = 0
    >>> y = 1
    >>> (foo == bar) and x or y   # Will this return the value of x if (foo == bar)?
    1
    

    Prefer instead the newer notation:

    return "https://" if port == "443" else "http://"
    

提交回复
热议问题