@@ -4,10 +4,10 @@ Now we understand how code like this works.
4
4
5
5
``` py
6
6
message = input (" Enter something: " )
7
- if message != ' ' :
8
- print (" You entered:" , message)
9
- else :
7
+ if message == ' ' :
10
8
print (" You didn't enter anything!" )
9
+ else :
10
+ print (" You entered:" , message)
11
11
```
12
12
13
13
But most Python programmers would write that code like this
@@ -29,6 +29,10 @@ the Boolean it ended up with was True. But when will it be true?
29
29
30
30
## Converting to Booleans
31
31
32
+ The ` if message: ` actually did the same thing as ` if bool(message) ` ,
33
+ which is same as ` if bool(message) == True: ` . Usually we just don't
34
+ write the ` ==True ` part anywhere because we don't need it.
35
+
32
36
We can convert things to Booleans like Python did by doing
33
37
` bool(things) ` . Let's try that with strings.
34
38
44
48
>> >
45
49
```
46
50
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
51
As we can see, the Boolean value of most strings is True. The
52
52
only string that has a false Boolean value is the empty string,
53
53
` '' ` or ` "" ` :
109
109
It's recommended to rely on the Boolean value when we're doing
110
110
something with things like lists and tuples. This way our code
111
111
will work even if it gets a value of a different type than we
112
- were expected it to get originally.
112
+ expected it to get originally.
113
113
114
114
For example, this code doesn't work right if we give it
115
115
something else than a list. It thinks that empty tuples,
@@ -202,8 +202,10 @@ if value is None: ... # best
202
202
203
203
## Summary
204
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.
205
+ - ` if thing: ` does the same thing as ` if bool(thing): ` . This also
206
+ works with while loops and most other things.
207
+ - ` bool() ` of most things is True, but ` bool() ` values of None,
208
+ zero and most empty things are False.
208
209
- Use ` is ` and ` is not ` when comparing to None, ` == ` and ` != ` when
209
- comparing to numbers and rely on the Boolean value otherwise.
210
+ checking if a number is zero and rely on the Boolean value
211
+ when checking if something is empty.
0 commit comments