为什么 PHP 代码与 Python 代码的功能不同?
Why does the PHP code function differently than the Python code?
PHP 节目
$x = (False or 123)
echo $x
python代码
x= (False or 123)
print(x)
在 php 中答案是 1
而在 python 中答案是 123
。
这是为什么?
Python and
和 or
做一个 "McCarthy evaluation" 那 returns 最后一个值,见 or Wikipedia.
PHP 也进行短路评估,但始终只返回一个布尔值:http://php.net/manual/en/language.operators.logical.php
PHP: $x =(错误或 123)。 False 为 false(!),123 为 true,false 或 true == true,因此 $x 为 true(或打印时为 1。
Python:先做or运算,再将结果赋值给x。 int(False) 是 0,int(123) 是 123,所以它得到 123。在 Python 中有一个技巧,或者 return 值是使它为真的值,而不是布尔结果。看到这个页面:
http://www.diveintopython.net/power_of_introspection/and_or.html
PHP 节目
$x = (False or 123)
echo $x
python代码
x= (False or 123)
print(x)
在 php 中答案是 1
而在 python 中答案是 123
。
这是为什么?
Python and
和 or
做一个 "McCarthy evaluation" 那 returns 最后一个值,见 or Wikipedia.
PHP 也进行短路评估,但始终只返回一个布尔值:http://php.net/manual/en/language.operators.logical.php
PHP: $x =(错误或 123)。 False 为 false(!),123 为 true,false 或 true == true,因此 $x 为 true(或打印时为 1。
Python:先做or运算,再将结果赋值给x。 int(False) 是 0,int(123) 是 123,所以它得到 123。在 Python 中有一个技巧,或者 return 值是使它为真的值,而不是布尔结果。看到这个页面: http://www.diveintopython.net/power_of_introspection/and_or.html