> For the complete documentation index, see [llms.txt](https://dinoin.gitbook.io/shi-py-bu-shi-pi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dinoin.gitbook.io/shi-py-bu-shi-pi/boolean.md).

# Boolean

python有別的寫法

Python裡的Boolean不叫boolean，是「bool」。

```python
a = True
b = False
print(a and b) #False
print(a or b) #True
print(not a) #False
```

{% hint style="warning" %}
在做if判斷時，「非」的寫法可以直接寫「not」(用「\~」反而會無效)

```python
if not result.__contains__(value):
```

{% endhint %}

## &

{% hint style="warning" %}
python中沒有「&&, ||」這種「兩個&|」的符號(其他語言中視為and, or)，寫為「and, or」
{% endhint %}

{% code title="EX" %}

```python
a = None
b = "S"
print(a is None) # >True
print(b is None) # >False
print(a is None and b is None) # >False
print(a & b) # >TypeError: unsupported operand type(s) for &: 'NoneType' and 'stry
```

{% endcode %}

{% code title="數值EX" %}

```python
a = 7
b = 3
print(a is None) # >False
print(b is None) # >False
print(a is None and b is None) # >False
print(a & b) # >3

print(a is None & b is None)
# >TypeError: unsupported operand type(s) for &: 'NoneType' and 'int' =>「X is None」的回傳是個NoneType的物件
```

{% endcode %}

{% hint style="info" %}
基本上一般會用到的會是「and, or」!
{% endhint %}

## Transfer type

### string to boolean

```python
bool(str)
```

python視任何object為「truthy」，其值非空時布林為True，空值時為False；所以只有空字串為False。

{% code title="EX" %}

```python
print(bool('True'))  # >True
print(bool(''))  # >False
print(bool('X'))  # >True
print(bool(0))  # >False
print(bool(3))  # >True
```

{% endcode %}
