Basic Terminology
States
The state of a program is fully captured by the mapping from name to values. We can often represent them textually as follows.
The execution of a code snippet depends on the state of the program. By modifying the state, we can have different executions of the same program.
Expressions, Statements, and Blocks
Expressions
An expression is a construct that produces a single value when evaluated. This includes arithmetic, relational, and logical operations. We may also call them arithmetic expressions, relational expressions, and logical expressions. Often, we are also interested in the type of the resulting expression. For instance, we may have a boolean expression as an expression that produces a boolean value.
In our explanation, we will only use expressions that do not modify states. Unfortunately, because Python is a mature language, it has a lot of other complicated constructs. Some of the expressions in Python may actually modify the state.
Example of Expressions
Statements
A statement is a construct that may modify the state of the program. The simplest statement that modify the state is an assignment. Statements are typically evaluated from top to bottom but some statements may have jumps including the following.
- Selection Statement:
if
- May jump to one of the branches.
- Repetition Statement:
while
andfor
- May jump back to the top of the statement.
- May jump to outside of the loop.
There is also a placeholder statement named pass
.
This is available in Python because some constructs require at least one statement.
If we wish to do nothing, then we can simply use pass
.
An expression that is written on its own outside of any assignment or other statement is also considered a statement. Although the expression itself produces a value, the statement does not propagate the value. This way, we may say that a statement will not produce a value as it "eats" up the value produced by the expression.
Blocks
A block is simply a sequence of statements with the same indentation level or contain only inner block. It contain at least 1 statement. As noted above, a block may contain inner block. To differentiate the block, we need to look at the indentation level.
The indentation level is simply how many leading whitespaces. If there are more indentation level, we say that the block is the inner block and the block surrounding it with fewer indentation level as the outer block. Note that inner/outer is a relative term so the inner block may have another inner block.
One important requirement is that the indentation level of a block should not be interrupted by a line with fewer indentation level. Below is a visualization of outer and inner block.