By default, statements in Python are executed sequentially. Branching statements are used to break this sequential pattern.
Sometimes you want to perform certain operations only in some cases. This is called a conditional branch.
Sometimes you need to perform some operations repeatedly. This is called looping.
Before we look at how Python does conditional branching, we need to look at Python's Boolean type.
Boolean algebra is the mathematics of true/false
decisions. Python's bool type has only
two values: True and False.
A typical use of Boolean algebra is in comparing two
values. In Python, the expression is x < yTrue if is less than x, yFalse otherwise.
>>> 2 < 5 True >>> 2 < 2 False >>> 2 < 0 False
Here are the six comparison operators:
| Math symbol | Python | Meaning |
|---|---|---|
| < | < | Less than |
| ≤ | <= | Less than or equal to |
| > | > | Greater than |
| ≥ | >= | Greater than or equal to |
| ≡ | == | Equal to |
| ≠ | != | Not equal to |
The operator that compares for equality is “==”. (The “=”
symbol is not an operator: it is used only in the
assignment statement.)
Here are some more examples:
>>> 2 <= 5 True >>> 2 <= 2 True >>> 2 <= 0 False >>> 4.9 > 5 False >>> 4.9 > 4.8 True >>> (2-1)==1 True >>> 4*3 != 12 False
Python has a function cmp( that compares two values and returns:
x, y)
Zero, if and x
are equal.
y
A negative number if .
x < y
A positive number if .
x > y
>>> cmp(2,5) -1 >>> cmp(2,2) 0 >>> cmp(2,0) 1
The function bool( converts any value x) to a Boolean value. The values
in this list are considered xFalse; any
other value is considered True:
Any numeric zero: 0, 0L, or 0.0.
Any empty sequence: "" (an empty
string), [] (an empty list), () (an empty tuple).
{} (an empty dictionary).
The special unique value None.
>>> print bool(0), bool(0L), bool(0.0), bool(''), bool([]), bool(())
False False False False False False
>>> print bool({}), bool(None)
False False
>>> print bool(1), bool(98.6), bool('Ni!'), bool([43, "hike"])
True True True True