位置:首頁 > 腳本語言 > Python教學 > Python邏輯運算符示例

Python邏輯運算符示例

下表列出了所有Python語言支持的邏輯運算符。假設變量a持有10和變量b持有20,則:

運算符 描述 例子
and 所謂邏輯與運算符。如果兩個操作數都為真,則條件為真。 (a and b) 為 true.
or 所謂邏輯OR運算符。如果有兩個操作數都為非零,則條件變為真。 (a or b) 為 true.
not 所謂邏輯非運算符。用反轉操作數的邏輯狀態。如果條件為true,則邏輯非運算符將為false。 not(a and b) 為 false.

示例:

試試下麵的例子就明白了所有的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