小白必看的python中的Bool运算和真假值

Python (156) 2023-06-04 16:37:19

在python中,任何对象都可以判断其真假值:True,False

在if或while条件判断中,下面的情况值为False:

1.None

2.Flase

3.数值为0的情况,如:0,0.0,0j

4.所有空序列,如:'',(),[]

5.所有空mapping,如:{}

6.instances of user-defined classes, if the class defines a __bool__() or __len__() method,

when that method returns the integer zero or bool value False.

All other values are considered true — so objects of many types are always true.

在运算操作和内建函数返回Boolean结果0或者Flase表示false(更多学习内容,请点击Python学习网)

1或True表示true

python中的Boolean运算如下:

print('xory->ifxisfalse,theny,elsex')
x,y=2,0
print('{}or{}={}'.format(x,y,xory))
x1,y1=0,10
print('{}or{}={}'.format(x1,y1,x1ory1))
x2,y2=0,0
print('{}or{}={}'.format(x2,y2,x2ory2))

print('#'*50)
print('xandy->ifxisfalse,thenx,elsey')
print('{}and{}={}'.format(x,y,xandy))
x1,y1=0,10
print('{}and{}={}'.format(x1,y1,x1andy1))
x2,y2=0,0
print('{}and{}={}'.format(x2,y2,x2andy2))

print('#'*50)
print('notx->ifxisfalse,thenTrue,elseFalse')
x=2
print('not{}={}'.format(x,notx))
x=0
print('not{}={}'.format(x,notx))

运行结果:

>>>
xory->ifxisfalse,theny,elsex
or0=2
or10=10
or0=0
##################################################
xandy->ifxisfalse,thenx,elsey
and0=0
and10=0
and0=0
##################################################
notx->ifxisfalse,thenTrue,elseFalse
not2=False
not0=True
>>>
THE END

发表回复