# Python逻辑运算符用法示例指南

## 逻辑运算符

and 逻辑AND：如果两个操作数都为true, 则为true x和y
or 逻辑或：如果任何一个操作数为true, 则为true x或y
not 逻辑非：如果操作数为假, 则为真 不是x

#### 逻辑AND运算子

``````# Python program to demonstrate
# logical and operator

a = 10
b = 10
c = - 10

if a> 0 and b> 0 :
print ( "The numbers are greater than 0" )

if a> 0 and b> 0 and c> 0 :
print ( "The numbers are greater than 0" )
else :
print ( "Atleast one number is not greater than 0" )``````

``````The numbers are greater than 0
Atleast one number is not greater than 0``````

``````# Python program to demonstrate
# logical and operator

a = 10
b = 12
c = 0

if a and b and c:
print ( "All the numbers have boolean value as True" )
else :
print ( "Atleast one number has boolean value as False" )``````

``Atleast one number has boolean value as False``

#### 逻辑或运算符

``````# Python program to demonstrate
# logical or operator

a = 10
b = - 10
c = 0

if a> 0 or b> 0 :
print ( "Either of the number is greater than 0" )
else :
print ( "No number is greater than 0" )

if b> 0 or c> 0 :
print ( "Either of the number is greater than 0" )
else :
print ( "No number is greater than 0" )``````

``````Either of the number is greater than 0
No number is greater than 0``````

``````# Python program to demonstrate
# logical and operator

a = 10
b = 12
c = 0

if a or b or c:
print ( "Atleast one number has boolean value as True" )
else :
print ( "All the numbers have boolean value as False" )``````

``Atleast one number has boolean value as True``

#### 逻辑非运算符

``````# Python program to demonstrate
# logical not operator

a = 10

if not a:
print ( "Boolean value of a is True" )

if not (a % 3 = = 0 or a % 5 = = 0 ):
print ( "10 is not divisible by either 3 or 5" )
else :
print ( "10 is divisible by either 3 or 5" )``````

``10 is divisible by either 3 or 5``

## 逻辑运算符的评估顺序

``````# Python program to demonstrate
# order of evaluation of logical
# operators

def order(x):
print ( "Method called for value:" , x)
return True if x> 0 else False

a = order
b = order
c = order

if a( - 1 ) or b( 5 ) or c( 10 ):
print ( "Atleast one of the number is positive" )``````

``````Method called for value: -1
Method called for value: 5
Atleast one of the number is positive``````

### 觉得文章有用就打赏一下文章作者

#### 微信扫一扫打赏 • 回顶