python中and、or、not、三元运算

在python中逻辑运算符有and、or、not,分别表示与、或、非。这里对他们进行简单的解释。
1.and是与的意思。
(1)当前后两边都为True,返回后一个结果

In [1]: True and “a”
Out[1]: ‘a’

In [2]: “a” and True
Out[2]: True

(2)当有False时,返回False
2.or
(1)前后都为True 返回前面的结果。

In [6]: “a” or “b”
Out[6]: ‘a’

(2)当一个为True一个为False,返回True的结果。都为False返回False。

3.not 非。这里not后面跟除0、空列表、空元组、空字符串、空字典、以外的结果都是False。

In [9]: not 1
Out[9]: False

In [10]: not 0
Out[10]: True

In [11]: not []
Out[11]: True

In [12]: not ""
Out[12]: True

In [13]: not ()
Out[13]: True

In [14]: not {}
Out[14]: True

4.python中的两种三元运算的实现
(1)条件 and 结果1 or 结果2:
分析:当条件为真时,也就是条件、结果1、结果2都为真,and返回后面的,or返回前面的,也就是结果1。
当条件为假时,条件and结果1为假,假or结果2,为结果2.

In [17]: 1<2 and “a"or"b”
Out[17]: ‘a’

In [18]: 1>2 and “a"or"b”
Out[18]: ‘b’

(2)为真时结果 if 判断条件 else 为假时结果

In [19]: "a"if 1<2 else “b”
Out[19]: ‘a’

In [20]: "a"if 1>2 else “b”
Out[20]: ‘b’

猜你喜欢

转载自blog.csdn.net/zhangbiaoxiaoming/article/details/84101247
今日推荐