Skip to content

Commit caa608d

Browse files
committed
new chapter
1 parent 4fe93ff commit caa608d

1 file changed

Lines changed: 209 additions & 0 deletions

File tree

what-is-true.md

Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
# What is true?
2+
3+
Now we understand how code like this works.
4+
5+
```py
6+
message = input("Enter something: ")
7+
if message != '':
8+
print("You entered:", message)
9+
else:
10+
print("You didn't enter anything!")
11+
```
12+
13+
But most Python programmers would write that code like this
14+
instead:
15+
16+
```py
17+
message = input("Enter something: ")
18+
if message:
19+
print("You entered:", message)
20+
else:
21+
print("You didn't enter anything!")
22+
```
23+
24+
What the heck was that? We did `if message`, but `message`
25+
was a string, not True or False!
26+
27+
Python converted our message to a Boolean and then checked if
28+
the Boolean it ended up with was True. But when will it be true?
29+
30+
## Converting to Booleans
31+
32+
We can convert things to Booleans like Python did by doing
33+
`bool(things)`. Let's try that with strings.
34+
35+
```py
36+
>>> bool('hello')
37+
True
38+
>>> bool('there')
39+
True
40+
>>> bool('True')
41+
True
42+
>>> bool('False') # this isn't special in any way
43+
True
44+
>>>
45+
```
46+
47+
The `if message:` actually did the same thing as `if bool(message)`,
48+
which is same as `if bool(message) == True:`. Usually we just don't
49+
write the `==True` part anywhere because we don't need it.
50+
51+
As we can see, the Boolean value of most strings is True. The
52+
only string that has a false Boolean value is the empty string,
53+
`''` or `""`:
54+
55+
```py
56+
>>> bool('')
57+
False
58+
>>>
59+
```
60+
61+
Most other things are also treated as False if they're empty and
62+
True if they're not empty.
63+
64+
```py
65+
>>> bool([1, 2, 3])
66+
True
67+
>>> bool([])
68+
False
69+
>>> bool((1, 2, 3))
70+
True
71+
>>> bool(())
72+
False
73+
>>> bool({'a': 1, 'b': 2})
74+
True
75+
>>> bool({})
76+
False
77+
>>>
78+
```
79+
80+
None and zero are also falsy, but positive and negative numbers
81+
are treated as True.
82+
83+
```py
84+
>>> bool(None)
85+
False
86+
>>> bool(0)
87+
False
88+
>>> bool(0.0)
89+
False
90+
>>> bool(1)
91+
True
92+
>>> bool(-1)
93+
True
94+
>>>
95+
```
96+
97+
Most other things are also treated as True.
98+
99+
```py
100+
>>> bool(OSError)
101+
True
102+
>>> bool(print)
103+
True
104+
>>>
105+
```
106+
107+
## When and why should we use Boolean values of things?
108+
109+
It's recommended to rely on the Boolean value when we're doing
110+
something with things like lists and tuples. This way our code
111+
will work even if it gets a value of a different type than we
112+
were expected it to get originally.
113+
114+
For example, this code doesn't work right if we give it
115+
something else than a list. It thinks that empty tuples,
116+
strings and dictionaries aren't empty just because they aren't
117+
empty lists:
118+
119+
```py
120+
>>> def is_this_empty(thing):
121+
... if thing == []:
122+
... print("It's empty!")
123+
... else:
124+
... print("It's not empty.")
125+
...
126+
>>> is_this_empty([1, 2, 3])
127+
It's not empty.
128+
>>> is_this_empty([])
129+
It's empty!
130+
>>> is_this_empty(())
131+
It's not empty.
132+
>>> is_this_empty('')
133+
It's not empty.
134+
>>> is_this_empty({})
135+
It's not empty.
136+
>>>
137+
```
138+
139+
We could improve the code by checking against different empty
140+
things.
141+
142+
```py
143+
>>> def is_this_empty(thing):
144+
... if thing == [] or thing == () or thing == '' or thing == {}:
145+
... print("It's empty!")
146+
... else:
147+
... print("It's not empty.")
148+
...
149+
>>>
150+
```
151+
152+
But Python has many other data types that can be empty and we
153+
haven't talked about in this tutorial. Trying to check all of
154+
them would be pointless because functions like this already
155+
work with all of them:
156+
157+
```py
158+
>>> def is_this_empty(thing):
159+
... if thing:
160+
... print("It's not empty.")
161+
... else:
162+
... print("It's empty!")
163+
...
164+
>>>
165+
```
166+
167+
There's also cases when we should not rely on the Boolean value.
168+
When we're doing things with numbers and None it's best to
169+
simply compare to None or zero. Like this:
170+
171+
```py
172+
if number != 0:
173+
print("number is not zero")
174+
175+
if value is not None:
176+
print("value is not None")
177+
```
178+
179+
Not like this:
180+
181+
```py
182+
if number:
183+
print("number is not zero")
184+
185+
if value:
186+
print("value is not None")
187+
```
188+
189+
We used `is not` instead of `!=` in the first example because
190+
the official style guide recommends it. The reason is that it's
191+
possible to create a value that isn't really None but seems like
192+
None when we compare it with None using `==` or `!=`, and we want
193+
to make sure that we don't treat values like that as None.
194+
195+
So here's how we should check if something is None:
196+
197+
```py
198+
if not value: ... # not good if we want to check if it's None
199+
if value == None: ... # better
200+
if value is None: ... # best
201+
```
202+
203+
## Summary
204+
205+
- `if thing:` does the same thing as `if bool(thing):`.
206+
- `bool()` of most things is True, but `bool()` of None, zero and
207+
most empty things are False.
208+
- Use `is` and `is not` when comparing to None, `==` and `!=` when
209+
comparing to numbers and rely on the Boolean value otherwise.

0 commit comments

Comments
 (0)