Next / Previous / Contents / TCC Help System / NM Tech homepage

6. Branching

By default, statements in Python are executed sequentially. Branching statements are used to break this sequential pattern.

Before we look at how Python does conditional branching, we need to look at Python's Boolean type.

6.1. Conditions and the bool 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 x < y is True if x is less than y, False otherwise.

>>> 2 < 5
True
>>> 2 < 2
False
>>> 2 < 0
False

Here are the six comparison operators:

Math symbolPythonMeaning
<<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(x, y) that compares two values and returns:

  • Zero, if x and y are equal.

  • 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(x) converts any value x to a Boolean value. The values in this list are considered False; 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