pytho boolean operations

Computer programs are composed of countless logic branches. Through Boolean operations, conditional judgments can be realized in the computer. According to the calculation results as True or False, the computer can automatically execute different follow-up codes. Therefore, learning Boolean operations is also very necessary.

In Python, the Boolean type can also perform and, or, and not operations with other data types (strings, numbers, etc.). Please see the following code:

a = True
print(a and 0 or 99) # ==> 99
The result of the calculation is not a Boolean type, but the number 99. Why?

Because Python treats 0, empty strings, and None as False, and other numeric values ​​and non-empty strings as True , so:

True and 0 calculation result is 0
continue to calculate 0 or 99 calculation result is 99
Therefore, the result is 99.
It should be noted that the priority of not calculation is higher than that of and and or .

True and not False # ==> True
In the above Boolean calculation, not False = True is calculated first, and then True and True are calculated, so the result of True is obtained.

When the Python interpreter is doing Boolean operations , as long as the result of the calculation can be determined in advance, it will not calculate it later and return the result directly.

Guess you like

Origin blog.csdn.net/angelsweet/article/details/109142017