Arithmetic Operators and Precedence

40 min read Operators and Expressions

This is a free course. Log in to run the code exercises and track your progress.

Arithmetic Operators and Precedence

OperatorMeaningExampleResult
+addition7 + 29
-subtraction7 - 25
*multiplication7 * 214
/division (always a float)7 / 23.5
//floor division7 // 23
%remainder (modulus)7 % 21
**exponent (power)7 ** 249

Precedence decides which operator is applied first: **, then * / // %, then + -. Operators of the same level work left to right. Brackets always come first.

print(2 + 3 * 4)     # 14, not 20
print((2 + 3) * 4)   # 20
print(2 ** 3 ** 2)   # 512: ** works right to left
minutes = 135
print(minutes // 60, minutes % 60)   # 2 15
Python exercise

Read a number of minutes and print it as hours and minutes, exactly like 2 hours 5 minutes. Use // and %.

total = int(input())
hours = 0    # whole hours in total
minutes = 0  # minutes left over
print(hours, "hours", minutes, "minutes")

Log in to edit and run this code.