2.5. Operators and operandsΒΆ
Operators are special symbols that represent computations like addition and multiplication. The values the operator is applied to are called operands.
The operators +
, -
, *
, /
, and
**
perform addition, subtraction, multiplication, division,
and exponentiation, as in the following examples:
There was a change in the division operator between Python 2.x and Python 3.x. In Python 3.x, the result of this division is a floating point result:
The division operator in Python 2.0 would divide two integers and truncate the result to an integer:
>>> minute = 59
>>> minute/60
0
To obtain the same answer in Python 3.0 use floored ( //
integer) division.
In Python 3.0 integer division functions much more as you would expect if you entered the expression on a calculator.
- 0
- If the two values are both integers (whole numbers) you will normally get an integer (whole number) result in older Python environments. But, this book is using Python 3 so you get a decimal result.
- 1
- This would be correct if the result was rounded up before the values after the decimal point were thrown away, but it does not do this.
- 0.75
- While this isn't the what older Pyton development environments would return, in this book we are using Python 3 so it returns a decimal result.
- 0.25
- This would be correct if it was
1 / 4
,1.0 / 4
, or1 / 4.0
csp-10-2-4: What is the result of 3 / 4
?
-
csp-10-2-6: Match each expression with the operation it performs.
Try assigning values to these variables and testing out the espressions in your python interpreter.
- x + y
- addition
- x - y
- subtraction
- x * y
- multiplication
- x / y
- division
- x % y
- remainder (modulus)
- x // y
- floored division
- x ** y
- exponentiation