Statement and expression are two important terms which are commonly misunderstood. Let’s start the explanation from the expression term.
Expression:
An expression is a combination of values, variables, and operators including function call operator (), subscription operator [ ] etc. I guess that it is not clear, so let’s see an example.
1 2 3 4 |
>>> 1+1 2 >>> sum(range(2*3)) 15 |
In simple terms, an expression produces a value (1+1 is an expression as it produces a value 2) and can be written wherever a value is expected, for example as an argument in a function call, for example, 2*3 is expression given as an argument to range function in the code above.
Note: If you type an expression on the command line, the interpreter evaluates it and displays the result. While in a script an expression all by itself is a statement. You have to write print(expression) in order to display the result.
A value or variable is considered an expression as the interpreter returns the result(See example below). Functions that do not return anything is not an expression.
1 2 3 4 |
>>> 4 4 >>> x 2 |
Note: Expressions can be reduced to any kind of value, which can be any integer, string or even a Python object like
1 2 |
>>> map(lambda x: x/2 , range(6)) <map object at 0x0000006242848588> |
Note: Evaluating an expression is not quite the same thing as printing a value. Expressions are displayed by the interpreter in the same format we enter, but print statement only shows the content (See example below)
1 2 3 4 5 |
>>> name= 'Pankaj' >>> name # expression 'Pankaj' >>> print(name) # statement Pankaj |
Statements:
A statement is an instruction that the Python interpreter can execute. In short, every line of python code is a statement. Note that expressions are statements as well. Below is an example of print and assignment statements.
1 2 3 |
>>> x = 2 # assignment (Do not display result) >>> print(x) # print 2 |
Expression Statements: In this, first the expression is evaluated then the statement is executed. In the example below, the 2*3 expression is evaluated first, then the print statement is executed.
1 2 |
>>> print(2*3) 6 |
Now, you might have got some feeling about the difference between expression and statement. Hope you enjoy reading.
If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.