Arithmetic Operators
Python · Operators
Theory
Arithmetic operators do math on numbers: + add, - subtract, * multiply, / true division, // floor division, % remainder (modulo) and ** power. Python applies precedence like school maths: ** first, then unary minus, then *, /, //, %, and finally + and -. Parentheses override everything, so price * (1 - 0.1) subtracts before multiplying. ** groups from the right, so 2 ** 3 ** 2 is 2 ** 9 = 512, and -2 ** 2 is -4 because the power happens before the minus.
Types matter: / always returns a float, // rounds down to the nearest whole number, and % returns a remainder with the same sign as the divisor (-7 % 3 is 2). divmod(a, b) gives both quotient and remainder at once. Several operators also work on other types: + joins strings and lists, and * repeats them ('ab' * 3 is 'ababab').
Why we use it
Every metric in analytics, from totals and averages to discounts and growth rates, is built from arithmetic. Knowing precedence and the exact behaviour of /, // and % prevents silent calculation mistakes.
When to use it
Use % to test even/odd (n % 2 == 0) or to wrap values into a range, // to split items into whole groups, and ** for powers and compound growth. Add parentheses whenever precedence is not obvious to a reader.
How it works
- Python meets price * (1 - 0.1)
- Evaluate anything inside parentheses first: 1 - 0.1 = 0.9
- Apply ** next, then * / // %, then + -
- Are both operands int and the operator not /? Yes: Result stays an int. No: Result becomes a float.
- Output: 90.0
Syntax
+ - * / // % **Example
price = 100
discounted = price * (1 - 0.1)Key points
- Follows standard precedence: ** first, then * / // %, then + -
- // is floor division, % is remainder, ** is exponent
- / always returns a float: 10 / 2 is 5.0
- -2 ** 2 is -4; write (-2) ** 2 to get 4
- + and * also work on strings and lists: 'ab' * 3 is 'ababab'
- Dividing by zero raises ZeroDivisionError