[Entry] 3-9 Python Python Boolean type

We already know Python supports Boolean data type Boolean True and False only two kinds of value, but a Boolean operation are the following:

1. and operations:

Only two Boolean values ​​are True, the results only to True.

True and True     # ==> True

True and False     # ==> False

False and True     # ==> False

False and False     # ==> False

2. OR:

As long as there is a Boolean value is True, the calculation result is True.

True or True   # ==> True

True or False   # ==> True

False or True   # ==> True

False or False   # ==> False

3. Non-operation:

The True becomes False, False or put into a True:

not True   # ==> False

not False   # ==> True

Boolean operation used to make the conditions in the computer is determined as True or False, the computer may automatically perform different subsequent code based on the calculation result.

In Python, Boolean type can do and, or and not operator with other data types, see the following code:

a = True
print a and 'a=T' or 'a=F'

The results are not Boolean, but the string 'a = T', this is why?

Because the Python 0, empty string '' and None as False, and the other values ​​are as True non-empty strings,

and so:

True and 'a = T' calculation result is 'a = T'
continues to calculate 'a = T' or 'a = F' results or 'a = T'

To explain these results, it also involves an important rule and and or operations:

Short circuit calculation.

  1. Calculating a and b , if a is False, then in accordance with the algorithm, the entire result is necessarily False, so a return; if a is True, the entire calculation must depends b, so the return b.

  2. Calculating a or b , if a is True, the algorithm or in accordance with, the entire calculation must result is True, and therefore a return; if a is False, the result will depend on the overall calculation b, so the return b.

So Python interpreter in doing Boolean operations, as long as the results determined in advance, it will not forget the future, a direct return results.

task:

Run the following code, and interpreting the results printed:

a = 'python'
print 'hello,', a or 'world'
b = ''
print 'hello,', b or 'world'

Here Insert Picture Description
Therefore, a return to true a
B world is false is returned

The 0, empty string '' and as False None

Published 20 original articles · won praise 0 · Views 419

Guess you like

Origin blog.csdn.net/yipyuenkay/article/details/103872957