Boolean type
The Boolean type is a data type whose values are only true and false, expressed in Python with and True
.False
Let's do a test in IDLE first, and bool()
the corresponding result can be directly given by using the built-in function:
>>> bool("假")
True
>>> bool("False") #字符串
True
>>> bool(False)
False
>>> bool("") #双引号中没有内容
False
>>> bool(" ") #输入空格
True
>>> bool(0)
False
>>> bool(0.0)
False
>>> bool(0j)
False
>>> bool(123)
True
analyze
- Some friends may be curious, what? It is clear that the input is
假
andFalse
why it is returnedTrue
. In fact, this is just a small trick, because they are enclosed in double quotes, so they are strings (the first and third lines), and there are only empty characters in the strings (the seventh line ) will be returnedFalse
, even if a space is entered (line 9)True
. - In the number type, only a few specific numbers will be returned
False
, and the rest will beTrue
.
Through testing, we found that bool() will return False only in some specific cases, which can be summarized as follows:
- constant
None
andFalse
0
,0.0
,0j
,Decimal(0)
,Fraction(0, 1)
- empty string, empty collection, sequence, etc.,
''
,()
,[]
,set()
,range(0)
Some of these are unfamiliar to us, but it doesn't matter, we will come into contact with them slowly in the future.
boolean operation
There are three types of Boolean operators: and
, or
, not
, I have summarized these three logical operators and other commonly used operators before, click here to view them.
Test code:
>>> 2 > 3 and 3 > 2
False
>>> 2 > 1 and 3 > 1
True
>>> 2 > 1 or 3 < 5
True
>>> 1 > 4 or 3 > 2
True
>>> 1 > 3 or 3 > 6
False
>>> not False
True
>>> not 250
False
- For
and
operators, the operands on both sides must beTrue
the result to returnTrue
, otherwise returnFalse
. - For
or
operators, as long as there is an operand isTrue
, the result isTrue
, otherwise it returnsFalse
. - For
not
operators, is willTrue
becomeFalse
, willFalse
becomeTrue
.
Any object in Python can directly perform a truth test (test whether the object’s Boolean type value True
is still False
), of course, it can also be used as an operand of a Boolean logic operator, and it can also be said that any type can be used as an operation of a Boolean logic operator number.
>>> 2 and 4
4
>>> 3 or 5
3
>>> "python" and "C"
'C'
>>> "Hello" or 123
'Hello'
So why is this the case? Here I leave it for everyone to think about it, and I will write another article to answer it later.