and和or都有四种情况,x真y真,x真y假,x假y真,x假y假
但and和or不同的是and只有两者全为真才取真,or只要有一个为真就取真
下面看一组实例
true and true true and false false and true false and false
>>>true >>> flase >>>false >>>false
true and 1 true and 0 false and 2 false and 0
>>>1 >>>0 >>>false >>>false
1and 6 1and 0 0and 2 0 and 0
>>>6 >>>0 >>>0 >>>0
从这一组发现结果有时候是布尔型有时是整数型,那何时区分呢,通过发现规律我们发现当x是真时永远输出y的值,当x为假时永远输出x的值
无论x和y是什么类型,机器从左往右开始判断,当x假时不需要在判断y,因为and一定为假了,只需要输出x,x代表假。当x真时也不需要在判断y,因为x为真时,y真and就真,y假and一定就假,这首y值与and值相同,只需输出y即可
or类型也是同理
true or true true or false false or true false or false
>>>true >>> true >>>true >>>false
true or 1 true or 0 false or 2 false or 0
>>>true >>>true >>>2 >>>0
1 or 6 1 or 0 0 or 2 0 or 0
>>>1 >>>1 >>>2 >>>0
最终得出结论:
and:当第一个数为假时,返回第一个值
当一个数为真时,返回第二个值
or: 当第一个数为真时,返回第一个值
当第一个数为假时,返回第二个值
not 类型无论何时返回的都是布尔类型