CodeMIRAI
0 XP

Arithmetic operators

2 min read 5 runnable examples Quiz included

Operators are the symbols that do work on values: + adds, * multiplies, and so on.

Arithmetic operators

OperatorNameExampleResult
+addition7 + 29
-subtraction7 - 25
*multiplication7 * 214
/division7 / 23.5
//floor division7 // 23
%remainder (modulo)7 % 21
**power7 ** 249
Python
print(7 + 2, 7 - 2, 7 * 2)
print(7 / 2)
print(7 // 2)
print(7 % 2)
print(7 ** 2)

Floor division and remainder

// divides and rounds down to a whole number; % gives what is left over. Together they answer questions like "how many whole hours, and how many minutes left?":

Python
total_minutes = 135
hours = total_minutes // 60
minutes = total_minutes % 60
print(f"{hours} h {minutes} min")

% is also the standard way to test divisibility: n % 2 == 0 means n is even.

Python
for n in [10, 7, 0, 15]:
    print(n, "is even" if n % 2 == 0 else "is odd")

Order of operations

Python follows the usual maths rules: brackets first, then powers, then * / // %, then + -.

Python
print(2 + 3 * 4)       # 14, not 20
print((2 + 3) * 4)     # 20
print(2 ** 3 ** 2)     # powers go right to left: 2 ** 9 = 512
print(-3 ** 2)         # -(3 ** 2) = -9

When in doubt, add brackets. They cost nothing and make the meaning obvious.

Assignment shorthands

Updating a variable using its own value is so common that Python has shortcuts:

ShorthandSame as
x += 5x = x + 5
x -= 5x = x - 5
x *= 5x = x * 5
x /= 5x = x / 5
x //= 5x = x // 5
x %= 5x = x % 5
x **= 5x = x ** 5
Python
score = 10
score += 5
score *= 2
print(score)

Python has no ++ operator; write x += 1.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.