Page 37 -
P. 37
14 Chapter 2. Variables, expressions and statements
>>> minute = 59
>>> minute/60
0
The value of minute is 59, and in conventional arithmetic 59 divided by 60 is 0.98333, not 0.
The reason for the discrepancy is that Python is performing floor division. When both of
the operands are integers, the result is also an integer; floor division chops off the fraction
part, so in this example it rounds down to zero.
In Python 3, the result of this division is a float . The new operator // performs floor
division.
If either of the operands is a floating-point number, Python performs floating-point divi-
sion, and the result is a float :
>>> minute/60.0
0.98333333333333328
2.5 Expressions and statements
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
(assuming that the variable x has been assigned a value):
17
x
x + 17
A statement is a unit of code that the Python interpreter can execute. We have seen two
kinds of statement: print and assignment.
Technically an expression is also a statement, but it is probably simpler to think of them
as different things. The important difference is that an expression has a value; a statement
does not.
2.6 Interactive mode and script mode
One of the benefits of working with an interpreted language is that you can test bits of
code in interactive mode before you put them in a script. But there are differences between
interactive mode and script mode that can be confusing.
For example, if you are using Python as a calculator, you might type
>>> miles = 26.2
>>> miles * 1.61
42.182
The first line assigns a value to miles , but it has no visible effect. The second line is an ex-
pression, so the interpreter evaluates it and displays the result. So we learn that a marathon
is about 42 kilometers.
But if you type the same code into a script and run it, you get no output at all. In script
mode an expression, all by itself, has no visible effect. Python actually evaluates the ex-
pression, but it doesn’t display the value unless you tell it to: