True and False
Programs constantly ask questions. Is the stock empty? Is the order big
enough for free delivery? Python answers every such question with one of two
values: True or False.
print(10 > 3)
print(10 < 3)
print(10 == 10)
True and False are values like 42 or "bread". They are called
booleans. You can print them, name them, and return them from functions.
Comparisons
| Written | Meaning |
|---|---|
a == b |
equal |
a != b |
not equal |
a < b, a > b |
less than, greater than |
a <= b, a >= b |
less than or equal, greater than or equal |
Equality uses two equals signs. One = gives a name a value; two ==
ask whether two values are the same. Mixing them up is the most common
mistake at this stage.
stock = 0
print(stock == 0)
print(stock != 0)
Comparisons work on text too. == checks the text matches exactly, including
capital letters.
item = "Bread"
print(item == "bread")
print(item == "Bread")
Combining questions
and is true only if both sides are true. or is true if either side is.
not flips a boolean.
quantity = 3
price = 40
print(quantity > 0 and price < 50)
print(quantity > 5 or price < 50)
print(not (quantity > 0))
Read quantity > 0 and price < 50 as "quantity is positive and price is
under 50". Python works out the left side first, and only looks at the
right side if it still needs to: for and, a false left side already
settles it; for or, a true left side does.
The parentheses in not (quantity > 0) are optional, because not applies
to the whole comparison, but they make it clear what is being flipped.
Functions that answer questions
A function can return a boolean. By convention their names read like a
question: is_empty, has_discount, can_deliver.
def is_in_stock(quantity):
return quantity > 0
print(is_in_stock(5))
print(is_in_stock(0))
There is no if here. quantity > 0 already is True or False, so it is
returned directly.
Try it
Free delivery?
Delivery is free for orders of 50 or more. Write is_free_delivery(total)
that returns True when delivery is free and False otherwise.
is_free_delivery(60) -> True
is_free_delivery(50) -> True
is_free_delivery(49) -> False
def is_free_delivery(total):
...
Valid quantity?
A customer can order between 1 and 20 of an item. Write
is_valid_quantity(q) that returns True if q is in that range, inclusive,
and False otherwise.
is_valid_quantity(1) -> True
is_valid_quantity(20) -> True
is_valid_quantity(0) -> False
is_valid_quantity(21) -> False
def is_valid_quantity(q):
...
Same item?
Write same_item(a, b) that returns True if the two item names are the
same, ignoring whether letters are capitals or not.
same_item("bread", "bread") -> True
same_item("Bread", "bread") -> True
same_item("bread", "milk") -> False
You can turn a string into all lowercase with .lower(), like a.lower().
Methods get a full page later; for now, use that one.
def same_item(a, b):
...
Next: Making decisions.