Theory
Basic Arithmetic Operations
A + B— additionA - B— subtractionA * B— multiplicationA / B— division (always returns afloat)A ** B— exponentiation (e.g. square root:x ** 0.5; nth root:x ** (1/n))
There is also a unary minus operator that takes a single argument and returns its negation:
>> -AOperator Precedence
When several operations appear in one expression, Python applies them in this order:
- Exponentiation, evaluated right to left (so
3 ** 3 ** 3is3 ** (3 ** 3)). - Unary minus (negation).
- Multiplication and division (including
*,/,//,%), evaluated left to right. - Addition and subtraction, evaluated left to right.
For example:
>> 1 + 2 * 3 ** 1 + 18
Integer Division and Modulo
The / operator always produces a float.
To perform integer (floor) division—discarding any fractional part—use //:
>> 17 // 3
5
>>> -17 // 3
-6
To get the remainder of a division, use the modulo operator %:
>> 17 % 3
2
>>> -17 % 3
1