Learn python with socratica [My notes] - part 7- Python Booleans

Lesson 9

Booleans就是常说的布尔运算,True or False?计算机用1和0来隐形地表示,python中布尔变量是如何表达的呢。

1
2
3
4
5
6
7
8
9
10
11
12
13
# Booleans Value: True and False.

>>> True
> True

>>> true
> ---------------------------------------------------------------------------

NameError Traceback (most recent call last)

<ipython-input-2-724ba28f4a9a> in <module>()
----> 1 true
NameError: name 'true' is not defined

如果之间键入True,python会直接返回True。但是如果你键入true,python是不会识别的,所以需要注意大小写,表示布尔变量的只有第一个字母大写的情况。

1
2
3
4
5
6
7
8
9
10
11
12
# similarly
>>> False
> False

>>> false
>---------------------------------------------------------------------------

NameError Traceback (most recent call last)

<ipython-input-4-b73d74fcede9> in <module>()
----> 1 false
NameError: name 'false' is not defined

布尔变量一般用于比较,举个例子:

1
2
3
4
>>> a = 4
>>> b = 5
>>> a == b
> False

上面这个例子中,我们用一个等号来赋值,用两个等号来比较二值是否相等,其返回值就是布尔变量。如果想要返回True也很简单,这些只要在python数值运算的部分找表格。

1
2
>>> a!=b
> True

!=表示不等于,类似的还有>,<等等,做一下实验看看吧。

1
2
3
4
5
6
7
8
9
10
>>> a < b
> True

>>> a > b
> False

>>> type(True)
> bool
>>> type(False)
> bool

当我们用type去看它们的类型时,可以看出它们在python中并不是字符串。

1
2
3
4
5
6
7
8
9
10
11
>>> bool(20)
> True

>>> bool(-2.78)
> True

>>> bool(0)
> False

>>> bool(2.3+0.7j)
> True

在python中,bool其他类型的数字,0转换成False,其他的都转换成True。

1
2
3
4
5
6
7
8
>>> bool('Turing')
> True

>>> bool(' ')
> True

>>> bool('')
> False

对字符串做bool强制类型转换的话,挺有意思。空字符串转换成False,其他的都是True。

1
2
3
4
5
6
7
8
9
10
11
12
# you can convert bool values like this
>>> str(True)
> 'True'

>>> str(False)
> 'False'

>>> int(True)
> 1

>>> int(False)
> 0

不仅如此,你还可以直接用True和False进行算术运算,比如:

1
2
3
4
5
>>> 5 + True
> 6

>>> 10 * False
> 0

python内核中 bool[True] ->1 [int]

python中的booleans就是这样啦。

Youtube source:
https://www.youtube.com/watch?v=bY6m6_IIN94&list=PLi01XoE8jYohWFPpC17Z-wWhPOSuh8Er-