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

yipeiwu_com6年前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 sorted函数详解(高级篇)

sorted 用于对集合进行排序(这里集合是对可迭代对象的一个统称,他们可以是列表、字典、set、甚至是字符串),它的功能非常强大 1、对列表排序,返回的对象不会改变原列表 lis...

python连接mysql并提交mysql事务示例

复制代码 代码如下:# -*- coding: utf-8 -*-import sysimport MySQLdbreload(sys)sys.setdefaultencoding('u...

python 检查是否为中文字符串的方法

python 检查是否为中文字符串的方法

【目标需求】 查看某一个字符串是否为中文字符串 【解决办法】 def check_contain_chinese(check_str): for ch in check_str:...

python散点图实例之随机漫步

python散点图实例之随机漫步

随机漫步是这样行走得到的途径:每次行走都是完全随机的,没有明确的方向,结果是由一系列随机决策决定的。 random_walk.py #random_walk.py from ran...

用django-allauth实现第三方登录的示例代码

用django-allauth实现第三方登录的示例代码

现在我们已经拥有一个可以进行用户本地登录的博客系统了。如果有人欣赏你的文章,说不定就会注册成为本地用户,并和你好好交流一番。 但头疼的是,用户可能每天都在互联网上浏览很多非常棒的博客,如...