怎么做“和”和“或”合并在一个声明中的工作? [英] How do "and" and "or" work when combined in one statement?

查看:145
本文介绍了怎么做“和”和“或”合并在一个声明中的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某种原因,这个功能使我感到困惑:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆