gpt4 book ai didi

python - 古怪的输出python

转载 作者:太空狗 更新时间:2023-10-30 00:02:41 26 4
gpt4 key购买 nike

请在下面解释,我认为它应该打印 True 或 False,因为这些是 bool 表达式。以及为什么它打印 2 1 然后 1 2

print 1 and 2
print 2 and 1
print 1 or 2
print 2 or 1

输出:

2
1
1
2

最佳答案

为什么你认为结果必须是 bool 类型?

来自 python 维基:

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.

请注意,andor 都不会将它们返回的值和类型限制为 False 和 True,而是返回最后计算的参数。这有时很有用,例如,如果 s 是一个字符串,如果它为空,则应该用默认值替换,表达式 s 或 'foo' 会产生所需的值.因为无论如何都不必发明一个值,它不会费心返回一个与其参数相同类型的值,所以例如,not 'foo' yields False, not ''.

关于python - 古怪的输出python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27540823/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com