@@ -4,10 +4,10 @@ Now we understand how code like this works.
44
55``` py
66message = input (" Enter something: " )
7- if message != ' ' :
8- print (" You entered:" , message)
9- else :
7+ if message == ' ' :
108 print (" You didn't enter anything!" )
9+ else :
10+ print (" You entered:" , message)
1111```
1212
1313But 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?
2929
3030## Converting to Booleans
3131
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+
3236We can convert things to Booleans like Python did by doing
3337` bool(things) ` . Let's try that with strings.
3438
4448>> >
4549```
4650
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-
5151As we can see, the Boolean value of most strings is True. The
5252only string that has a false Boolean value is the empty string,
5353` '' ` or ` "" ` :
109109It's recommended to rely on the Boolean value when we're doing
110110something with things like lists and tuples. This way our code
111111will 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.
113113
114114For example, this code doesn't work right if we give it
115115something else than a list. It thinks that empty tuples,
@@ -202,8 +202,10 @@ if value is None: ... # best
202202
203203## Summary
204204
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.
208209- 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