Math in PythonΒΆ

division can be a touch odd. Here are some interesting examples of division:

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # result * divisor + remainder
17
division operators:
  • // floor division; division that rounds down to nearest integer.
  • % calculate just the remainder from division.

Also you can calculate powers:

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128

There is a lot more math around, if you are a math-type person, but I’ll finish off here with one more thing, you can do grouping with () as expected when doing math on paper:

>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
So our complete list of operators on numbers:
  • addition: +
  • subtraction: -
  • multiplication: *
  • division: /
  • // floor division; division that rounds down to nearest integer.
  • % calculate just the remainder from division.
  • ** powers (squaring numbers)
  • () grouping