x = 42
x + 1Operations
Expressions, Statements, and Programs
An expression is a combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable, so the following are all legal expressions: 42, x, x+1
When you type an expression at the prompt, the interpreter evaluates it, which means that it finds the value of the expression. In this example, x + 1, the interpreter adds one to the current value of x. But it doesn’t display the value unless you tell it to:
A statement is a unit of code that has an effect, like creating a variable or displaying a value.
x = 42
print(x)The first line is an assignment statement that gives a value to x. The second line is a print statement that displays the value of x.
The types of statements we have seen so far are assignments and print statements. Other types of statements include:
- Import statements: Import a module.
- If statements: Execute code depending on the value of a condition.
- For statements: Execute code for each item in a sequence.
- While statements: Execute code while a condition is true.
- Def statements: Define a function.
- Return statements: Exit a function and return a value.
- Break statements: Exit a loop.
- Continue statements: Skip the rest of the loop body.
When you type a statement, the interpreter executes it, which means that it does whatever the statement says. In general, statements don’t have values.
A program is a sequence of statements. If there is more than one statement, the results appear one at a time as the statements execute.
For example, the script below contains three statements:
x = 42
print(x)
x = x + 1The output of this program is 42. The second line displays the value of x, which is 42. The third line increases the value of x by one. But it doesn’t display the value.