Simple arithmetic Flashcards
Symbol for ‘exponent/to the power of’
**
Symbol for ‘floor division’
//
Order of operations in Python
BODMAS: Brackets, power Of (exponent), Division & Multiplication, addition, subtraction
Multiplication & division are ranked equally in precedence and therefor are evaluated left to right.
Exponents are ‘right-associative’ (ie top down, or right to left): eg,
CORRECT: 2 ** 2 ** 3 = 2 ** (2 ** 3) = 2 ** 8 = 256
NOT: 2 ** 2 ** 3 != (2 ** 2) ** 3 = 4 ** 3 = 64
What is the use of ‘_’ (underscore) in simple arithmetic in the Python interactive interpreter?
Recalls the previous calculated value, eg: >> 2 ** 3 8 >> _ + 3 11 Since _ will recall 8
Explain floor division.
Floor division rounds towards zero:
Positive division rounds ‘down’, eg 10//3 = 3
Negative division rounds ‘up’, eg 12//-5 = -2
Also called integer division as it only returns a number of type Int even if the calculation used floating point, eg:
11.0//4 = 2 (where 2 is type Int, 2.0 type Float)
Symbol for ‘modulo’
%
Explain %
Returns the remainder of a division, eg:
10 % 3 = 3 r 1 = 1
-12 % 5 = -2 r -2 = -2
The modulo operator always yields a result with the same sign as its [first/second] operand (or [???])
The modulo operator always yields a result with the same sign as its SECOND operand (or ZERO)
Give the answer to the follow arithmetic in Python 2x vs Python 3x:
x = 3/4
Python 2: 0 (truncated floor division, now represented by ‘//’ operator in Python 3)
Python 3: 0.75 (true division - conversion of operands to floating point)
Give an example of how you can ‘break’ Python’s simple arithmetic.
Divide by 0