not, and & or
not, and & or
We've already dicusses the and, or and not operators in the previous chapter. Let's see how they can be combined.
not
The not operator is a unary operator, meaning it only takes one operand. It negates the truth value of the operand.
| Condition | not Condition |
|---|---|
| not True | False |
| not False | True |
The operand of the not operator can be any expression that evaluates to a Boolean value.
server_status = "Healthy"
if not server_status == "Healthy":
print("CRITICAL ERROR: Server down!!")This executes as follows:
- server_status is compared with the string "Healthy', which returns True,
- The result of
server_status == "Healthy"is negated, so True becomes False. - The script does nothing since there is no else branch.
and
The and operator is a binary operator, meaning it takes two operands. It evaluates to True if both operands are True, and False otherwise.
| Operand 1 | Operand 2 | Operand 1 and Operand 2 |
|---|---|---|
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
server_status = "Healthy"
environment = "Production"
# Evaluates to: (not True) and True => False and True => False
# Nothing is printed
if not server_status == "Healthy" and environment == "Production":
print("CRITICAL ERROR: Server down!!")
server_status = "Down"
# Evaluates to: True and True => True
# The alert is printed
if server_status == "Down" and environment == "Production":
print("CRITICAL ERROR: Server down!!")or
The or operator is also a binary operator, meaning it takes two operands. It evaluates to True if at least one of the operands is True, and False only if both operands are False.
| Operand 1 | Operand 2 | Operand 1 or Operand 2 |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
is_root_user = True
is_administrator = True
if is_root_user or not is_administrator:
print("This script can only be executed by members of the administrator group that aren't the root user.")
# Do some administrative task
# ...Order of operations
When combining multiple logical operators in a single expression, it's important to understand the order of operations. The three operators are evaluated in the following order:
==notandor
So the expression
if not status == "Healthy" and env == "Production":is evaluated as
if (not (status == "Healthy")) and (env == "Production"):