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

Posted in 未分类

发表评论