总结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

相关文章

python 参数列表中的self 显式不等于冗余

self在区分全局变量/函数和对象中的成员变量/函数十分有用。例如,它提供了一种作用域机制,我个人认为比Ruby的@和@@清晰多了,这可能是习惯使然吧,但它确实和C++、Java中的th...

Python基于pandas实现json格式转换成dataframe的方法

本文实例讲述了Python基于pandas实现json格式转换成dataframe的方法。分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- #!pyth...

python实现指定字符串补全空格的方法

本文实例讲述了python实现指定字符串补全空格的方法。分享给大家供大家参考。具体分析如下: 如果希望字符串的长度固定,给定的字符串又不够长度,我们可以通过rjust,ljust和cen...

Python3.8对可迭代解包的改进及用法详解

Python 3 的可迭代解包 在 PEP 3132 - Extended Iterable Unpacking 里面描述了一种对可迭代对象的解包用法,Python 3 可用: In...

python 实现图片上传接口开发 并生成可以访问的图片url

python 实现图片上传接口开发 并生成可以访问的图片url

版本:python3.7 功能,开发一个用户访问的页面,支持图片上传,并将其保存在服务器。 项目结构: app.py文件内容如下: from flask import Flask,...