怎么做“和”和“或”合并在一个声明中的工作? [英] How do "and" and "or" work when combined in one statement?
问题描述
出于某种原因,这个功能使我感到困惑:
For some reason this function confused me:
def protocol(port):
return port == "443" and "https://" or "http://"
有人可以解释订单在幕后发生的事情使它按照它的方式工作。
Can somebody explain the order of what's happening behind the scenes to make this work the way it does.
在我尝试之前我理解为:
I understood it as this until I tried it:
要么A)
def protocol(port):
if port == "443":
if bool("https://"):
return True
elif bool("http://"):
return True
return False
或B)
def protocol(port):
if port == "443":
return True + "https://"
else:
return True + "http://"
这是Python中的某种特殊情况,还是我完全误解了语句如何工作?
Is this some sort of special case in Python, or am I completely misunderstanding how statements work?
推荐答案
这是一个旧的 - 是成语;插入括号以显示优先级,
It's an old-ish idiom; inserting parentheses to show priority,
(port == "443" and "https://") or "http://"
x和y
返回 y
如果 x
是真实的, x
如果 x
是假的; a或b
,反之亦然,如果它是真的,则返回 a
,否则 b
。
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
.
因此,如果 port ==443
为真,则返回RHS 和
,即https://
。否则,和
为false,因此或
进入播放并返回http://,它的 RHS。
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.
在现代Python中,更好的方法是翻译这个古老的习语:
In modern Python, a better way to do translate this old-ish idiom is:
"https://" if port == "443" else "http://"
这篇关于怎么做“和”和“或”合并在一个声明中的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!