Datasheet

Chapter 1: A Python Primer
7
Expressions and Statements
Expressions and statements are the building blocks of Python programs. They are the equivalent of
phrases and sentences in English. To understand Python, it s critical to understand how to put these
building blocks together.
Expressions
Expressions consist of combinations of values , which can be either constant values, such as a string
( Jim ) or a number (12), and operators , which are symbols that act on the values in some way.
The following examples are expressions:
10 - 4
11 * (4 + 5)
x - 5
a / b
Operator Precedence in Expressions
When you have a multiple expression like 5 + 4 * 7 , which operation is done first, the addition or the
multiplication? If it isn t too painful to recall your high school algebra class, you might remember
learning the rules of operator precedence . These kinds of complex expressions require a set of rules
defining which expressions are executed first.
The following list describes the basic rules of operator precedence in Python (don t worry if you don ’ t
understand all the terms right now; they ll be explained as you need them):
Expressions are evaluated from left to right.
Exponents, multiplication, and division are performed before addition and subtraction.
Expressions in parentheses are performed first.
Mathematical expressions are performed before Boolean expressions (
AND , OR , NOT )
Statements
The statement is the basic unit of programming. In essence, it says do this to this. Statements in Python
are not delimited by a visible character, such as the semicolon in C or C#. Every time you press Enter and
start a new line, you are entering a new statement.
c01.indd 7c01.indd 7 6/2/08 12:03:10 PM6/2/08 12:03:10 PM