Lesson 2
The Basic Elements
Chapter 6: Variables
Statements vs. Expressions
I would also like to use this chance to point out a slight difference between how Python behaves when run as an interactive prompt and when run as a script.
If you run the following in an interactive prompt, it will show you the values for both 3+5
and print(2+4)
, but not x = 1+2
.
>>> 3+5
8
>>> print(2+4)
6
>>> x = 1+2
If you copy and save the following code as my_code.py
and run it as a script (python my_code.py
), you will find that Python only outputs 6
(test it out yourself!)
1 2 3 |
|
$ python my_code.py
6
Why does it not output 8? And why does x = 1+2
not output anything in both cases? Think about it for a second before moving on.
Statements vs Expressions
If you recall, an expression is something that can produce a value (3+5
).
And if you remember from Lesson 1, a statement is an instruction that a computer can execute. A statement may or may not produce a value. An assignment statement (x = 1+2
) is a type of statement. In Python, an expression (3+5
) on a single line is also a statement.
In Line 1, Python evaluates 3+5
. It creates an int
object with value 8
and allocates it in memory.
Python, however, does not do anything to the value. It just remains an object in memory. This is why 8
is not shown when run as a script, because you did not ask Python to do anything with the value.
In contrast, the interactive prompt will return the values of any expression you typed (since it is meant to be interactive).
In Line 2, print(2+4)
will first evaluate the expression 2+4
and create the int
object with value 6
. print()
then asks Python to print out this value. This is called the ‘side effect’ of print()
(we will cover more about this in future lessons).
Finally, in Line 3, x = 1+2
first computes the value of the expression 1+2
. The resulting object (an int
with value 3
) is then allocated some memory space. A variable x
then points to this memory location (i.e. the object is assigned to the variable x
). This statement does not return any value, so nothing is output.
Below is another example. Note that the first expression returns a string (note the single quote surrounding 'hello'
in the output), while the second statement prints out the word (note that there are no quotes around hello
). If you run this as a script, hello
will only be printed once (print("hello")
).
>>> "hello"
'hello'
>>> print("hello")
hello
So, do be aware and make sure that you understand the distinction between how Python behaves when used as a prompt and when run as a script.