Skip to main content
 首页 » 编程设计

python之Python 中带数字的 boolean 值

2025年05月04日13emanlee

我在 Python 中遇到了 gcd 的这个实现:

def gcd(x,y): return y and gcd(y, x % y) or x 

我不明白的是 boolean 值在返回中是如何工作的?在解释器中尝试了一些数字后,我注意到 and 总是返回右边的数字,而 or 返回左边的数字。为什么是这样?另外,您能否逐步引导我简单调用此函数,以便我了解发生了什么?

请您参考如下方法:

这是因为 and 和 or 运算符在 Python 中的计算方式。

来自 documentation -

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

它们不返回 True 或 False,它们返回最后计算的值,这就是为什么我们可以这样写 -

s = s or "Some default value" 

如果 None 或空字符串或空列表,或 0,则默认 s 的值。


基本上,或返回第一个非类假值(其中类假值是0,或无或空字符串/列表/元组等)或最后一个类假值,如果所有的值都是假的。示例 -

In [1]: 0 or 10 
Out[1]: 10 
 
In [2]: 5 or 0 or 10 
Out[2]: 5 
 
In [7]: 0 or '' or [] or () 
Out[7]: () 

And,and 返回第一个类假值,或最后一个类真值,如果所有值都是类真值。示例 -

In [3]: 0 and 10 
Out[3]: 0 
 
In [4]: 5 and 10 
Out[4]: 10 
 
In [6]: 5 and 0 and 10 
Out[6]: 0 

在您的情况下,它的作用是 -

  1. 如果 y 为 0,则返回 x(不考虑 x 的值)。

  2. 否则它计算 gcd(y, x%y) 如果它不为零则返回它。 (虽然它永远不会是 0)

  3. 如果 gcd(y, x%y) 的结果为 0,则返回 x。