Python Basics · Making Decisions · lesson 6 of 12
Booleans and comparisons
about 10 minutes · free · runs in your browser
Step 1 of 2
True and False
A boolean is a value with only two possibilities: True or False. Both are
capitalised, and neither takes quotes — "True" is a piece of text, which is a different
thing entirely.
Comparisons produce booleans:
| Operator | Question |
|---|---|
== | are these equal? |
!= | are these different? |
< > | less than, greater than |
<= >= | less than or equal, greater than or equal |
7 > 3 # True
7 == 3 # False
"a" == "a" # True
The single most common beginner bug in any language is writing = where == was
meant. = assigns; == asks.
Your turn: set is_adult to whether age is at least 18, and is_teenager to
whether age is between 13 and 19 inclusive. Compare — do not just write True or False.
You start from this, and edit it in the browser:
age = 15
# Set is_adult and is_teenager using comparisons.
Step 2 of 2
Truthiness
Anything can be used where Python expects a boolean, and it has firm opinions about what counts as false:
0,0.0,""(empty string),[](empty list) andNoneare falsy- everything else is truthy
So if name: reads as "if name is not empty", which is idiomatic Python and much nicer
than if len(name) > 0:.
bool(value) shows you which way a value falls.
Your turn: set has_name to whether name is non-empty, and has_items to
whether basket is non-empty — using bool() rather than comparing to "" or 0.
You start from this, and edit it in the browser:
name = ""
basket = ["apple", "pear"]
# Set has_name and has_items.