Boolean operations and if statements
- A boolean a value that is either
TrueorFalse. - A
Boolean expressionis an expression that evaluates to a boolean.
Relational operators, such as x > y and y != z are boolean expressions.
Booleans are useful for a wide range of applications, from filtering datasets to error handling.
Further, boolean logic underpins the if control structure, which allows for conditional execution
of statements.
For example, say we have an integer, and we want to know if its even or odd.
# uci_bootcamp_2021/examples/booleans.py:2:9
# init x to some constant
x = 32
# Comparing via modulo and equality
if x % 2 == 0:
print("even!")
else:
print("odd!")
# even!
The syntax for if is as follows:
if condition:
... # true branch
else:
... # false branch
"Truthiness"
Python has a concept of "Truthy" and "Falsy" values. In effect, all objects have a truth value. For
instance, the integer zero (0) is considered "Falsy", while any non-zero integer is "Truthy."
# All types have a truth value
# Zero, for instance, is falsy.
print(bool(0))
# False
print(bool(1))
# True
All objects have a truth value that is evaluated when that object is treated as a boolean.
- All non-zero numbers are truthy
- All non-empty containers are truthy
- All custom user-types are truthy unless they specifically define a special method
When python evaluates the
conditionof anifstatement, it checks for the truthiness of the condition.
the not operator
It can also be useful to take the negation of a boolean operation.
This can be achieved via the not operator.
print(not False)
# True
print(not True)
# False