2.2 Control
2.2.1 Boolean Operators
Python supports three boolean operators: and
, or
, and not
:
>>> a = 4
>>> a < 2 and a > 0
False
>>> a < 2 or a > 0
True
>>> not (a > 0)
False
and
evaluates toTrue
only if both operands evaluate toTrue
. If at least one operand isFalse
, then and evaluates toFalse
.or
evaluates toTrue
if at least one operand evaluates toTrue
. If both operands areFalse
, then or evaluates toFalse
.not
evaluates toTrue
if its operand evaluates toFalse
. It evaluates toFalse
if its operand evaluates toTrue
.
What do you think the following expression evaluates to? Try it out in the Python interpreter.
>>> True and not False or not True and False
It is difficult to read complex expressions, like the one above, and understand how a program will behave. Using parentheses can make your code easier to understand. Python interprets that expression in the following way:
>>> (True and (not False)) or ((not True) and False)
This is because boolean operators, like arithmetic operators, have an order of operation:
not
has the highest priorityand
or
has the lowest priority
Truthy and Falsey Values: It turns out and
and or
work on more than just booleans (True
, False
). Python values such as 0
, None
, ''
(the empty string), and []
(the empty list) are considered false values. All other values are considered true values.
2.2.2 Short Circuiting
What do you think will happen if we type the following into Python?
1 / 0
Try it out in Python! You should see a ZeroDivisionError
. But what about this expression?
True or 1 / 0
It evaluates to True
because Python's and
and or
operators short-circuit. That is, they don't necessarily evaluate every operand.
Operator | Checks if: | Evaluates from left to right up to: | Example |
---|---|---|---|
AND | All values are true | The first false value | False and 1 / 0 evaluates to False |
OR | At least one value is true | The first true value | True or 1 / 0 evaluates to True |
Short-circuiting happens when the operator reaches an operand that allows them to make a conclusion about the expression. For example, and
will short-circuit as soon as it reaches the first false value because it then knows that not all the values are true.
If and
and or
do not short-circuit, they just return the last value; another way to remember this is that and
and or
always return the last thing they evaluate, whether they short circuit or not. Keep in mind that and
and or
don't always return booleans when using values other than True
and False
.
2.2.3 If Statements
You can review the syntax of if
statements in Section 1.5.4 of Composing Programs.
Tip: We sometimes see code that looks like this:
if x > 3: return True else: return False
This can be written more concisely as
return x > 3
. If your code looks like the code above, see if you can rewrite it more clearly!
2.2.4 While Loops
You can review the syntax of while
loops in Section 1.5.5 of Composing Programs.