布尔值的Python混乱 [英] Boolean Python Value confusion

查看:147
本文介绍了布尔值的Python混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Python和尝试Python的逻辑statements.I遇到这里面我不能understand.Can谁能告诉我什么是在Python这里发生在Python 2.7.Whats 0和False值之间的差异

I'm new to Python and while trying Python logical statements.I came across this which I'm not able to understand.Can anyone tell me whats happening here in Python 2.7.Whats the difference between 0 and False value in Python.


>>> 0 or False
False
>>> False or 0
0

为什么国米preTER是给不同的答案?

Why the interpreter is giving different answers ?

推荐答案

您正在由经营者的行为感到困惑;它返回第一八佰伴pression只有当它是一个的真正的值;既不 0 也不所以返回第二个值假是正确的:

You are being confused by the behaviour of the or operator; it returns the first expression that only if it is a true value; neither 0 nor False is true so the second value is returned:

>>> 0 or 'bar'
'bar'
>>> False or 'foo'
'foo'

任何值不是数字0,一个空的容器,被认为是真(自定义类可以通过实现 __布尔__ 办法(蟒蛇3), __非零__ (蟒蛇2)或 __ __ LEN (长度为0为空)。

Any value that is not numerical 0, an empty container, None or False is considered true (custom classes can alter that by implementing a __bool__ method (python 3), __nonzero__ (python 2) or __len__ (length 0 is empty).

第二个前pression甚至没有进行评估,如果第一个是

The second expression is not even evaluated if the first is True:

>>> True or 1 / 0
True

1/0 前pression将提高 ZeroDivision 例外,但竟然没有通过评估蟒蛇。

The 1 / 0 expression would raise a ZeroDivision exception, but is not even evaluated by Python.

这是在href=\"http://docs.python.org/2/reference/ex$p$pssions.html#boolean-operations\" rel=\"nofollow\">布尔运算符文档<

This is documented in the boolean operators documentation:

这位前pression x或y 首先评估 X ;如果 X 是真实的,它的值返回;否则,评估并返回结果值。

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.

同样,返回第一八佰伴pression如果是,否则第二个前pression被返回。

Similarly, and returns the first expression if it is False, otherwise the second expression is returned.

这篇关于布尔值的Python混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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