Learn python (4) from scratch - Boolean type

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

  1. Some friends may be curious, what? It is clear that the input is and Falsewhy it is returned True. 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 returned False, even if a space is entered (line 9) True.
  2. In the number type, only a few specific numbers will be returned False, and the rest will be True.

Through testing, we found that bool() will return False only in some specific cases, which can be summarized as follows:

  1. constant NoneandFalse
  2. 00.00jDecimal(0)Fraction(0, 1)
  3. 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
  1. For andoperators, the operands on both sides must be Truethe result to return True, otherwise return False.
  2. For oroperators, as long as there is an operand is True, the result is True, otherwise it returns False.
  3. For notoperators, is will Truebecome False, will Falsebecome True.

Any object in Python can directly perform a truth test (test whether the object’s Boolean type value Trueis 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.

Guess you like

Origin blog.csdn.net/m0_46376148/article/details/108530092