一条线上的多重比较操作员

发布于 2025-02-09 06:46:13 字数 243 浏览 3 评论 0原文

我正在介绍Python课程的介绍,在测验上有一个问题,我无法做出头或尾巴。鉴于此代码,问题询问将分配给X的值什么值:

z = 2
y = 1
x = y < z or z > y and y > z or z < y

我对本语句中的分配的位置感到非常困惑。我是否应该将其读为“如果y小于z,x等于y”?在这种情况下,我什至无法开始理解如何阅读“,”,“和”。

提前致谢。

I'm taking an intro to python course, and there was one question on a quiz that I could not make heads or tails of. Given this code, the question asks what value will be assigned to x:

z = 2
y = 1
x = y < z or z > y and y > z or z < y

I'm really confused about where the assignment is in this statement. Should I read this as "x equals y if y is less than z"? I can't even begin to understand how to read "or" and "and" in this context.

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无法言说的痛 2025-02-16 06:46:13

您必须这样阅读,x将是布尔值(是或否),每个比较表达方式也将是

z = 2
y = 1

x = y < z or z > y and y > z or z < y

x = ( (y<z) or ((z>y) and (y>z)) or (z<y) )
x = ( True or (True and False) or False )
x = True

you have to read it like this, x will be a boolean (true or false) and so will each of the comparison expressions

z = 2
y = 1

x = y < z or z > y and y > z or z < y

x = ( (y<z) or ((z>y) and (y>z)) or (z<y) )
x = ( True or (True and False) or False )
x = True
黯然#的苍凉 2025-02-16 06:46:13

在Python中,具有比更高的优先级,因此

y < z or z > y and y > z or z < y

与与

y < z or (z > y and y > z) or z < y
          # always False

与与与

y < z or z < y

y != z

In Python, and has higher precedence than or, so

y < z or z > y and y > z or z < y

is the same as

y < z or (z > y and y > z) or z < y
          # always False

is the same as

y < z or z < y

is the same as

y != z
阳光的暖冬 2025-02-16 06:46:13

中,Python的优先级高于。因此,将首先评估(从左到右),然后将评估(从左到右),除非有()

因此,在您的情况下,要评估的第一件事是z&gt; y和y&gt; z,步骤如下:

x = y < z or (True and False) or z < y
x = (y < z or False) or z < y
x = (True or False) or z < y
x = True or False
x = True 

In python, and have higher priority than or. So, and will be evaluated first (left to right) then or will be evaluated (left to right), unless there are ().

So, in your case, first thing to be evaluated are z > y and y > z, and steps follows like:

x = y < z or (True and False) or z < y
x = (y < z or False) or z < y
x = (True or False) or z < y
x = True or False
x = True 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文