总结Python中逻辑运算符的使用

yipeiwu_com5年前Python基础

下表列出了所有Python语言支持的逻辑运算符。假设变量a持有10和变量b持有20,则:

2015513121854474.jpg (586×254)

 示例:

试试下面的例子就明白了所有的Python编程语言提供了逻辑运算符:

#!/usr/bin/python

a = 10
b = 20
c = 0

if ( a and b ):
  print "Line 1 - a and b are true"
else:
  print "Line 1 - Either a is not true or b is not true"

if ( a or b ):
  print "Line 2 - Either a is true or b is true or both are true"
else:
  print "Line 2 - Neither a is true nor b is true"


a = 0
if ( a and b ):
  print "Line 3 - a and b are true"
else:
  print "Line 3 - Either a is not true or b is not true"

if ( a or b ):
  print "Line 4 - Either a is true or b is true or both are true"
else:
  print "Line 4 - Neither a is true nor b is true"

if not( a and b ):
  print "Line 5 - Either a is not true or b is not true"
else:
  print "Line 5 - a and b are true"

当执行上面的程序它会产生以下结果:

Line 1 - a and b are true
Line 2 - Either a is true or b is true or both are true
Line 3 - Either a is not true or b is not true
Line 4 - Either a is true or b is true or both are true
Line 5 - Either a is not true or b is not true

相关文章

Python3内置模块之json编解码方法小结【推荐】

Python3中我们利用内置模块 json 解码和编码 JSON对象 ,JSON(JavaScript Object Notation)是指定 RFC 7159(废弃了RFC 4627)...

pandas删除行删除列增加行增加列的实现

创建df: >>> df = pd.DataFrame(np.arange(16).reshape(4, 4), columns=list('ABCD'), ind...

手把手教你pycharm专业版安装破解教程(linux版)

手把手教你pycharm专业版安装破解教程(linux版)

1.首先到jetbrains下载专业版 https://www.jetbrains.com/pycharm/download/#section=linux 我这里下载的是pycharm-...

解决安装tensorflow遇到无法卸载numpy 1.8.0rc1的问题

最近在关注 Deep Learning,就在自己的mac上安装google的开源框架Tensorflow 用 sudo pip install -U tensorflow 安装的时候总...

Python内存管理方式和垃圾回收算法解析

概要 在列表,元组,实例,类,字典和函数中存在循环引用问题。有 __del__ 方法的实例会以健全的方式被处理。给新类型添加GC支持是很容易的。支持GC的Python与常规的Python...