Part 3: Python Programming

3. Numbers, Operators & Math

Numbers, Operators & Math

Computers were invented to do arithmetic, and Python makes calculating easy. In this chapter you will learn the arithmetic operators, how Python decides the order of operations, and how the math module adds extra power.

The two number types

Python has int for whole numbers and float for numbers with a decimal point. Mixing them in a calculation produces a float:

PYTHON
print(4 + 2)
print(4 + 2.0)
▸ OUTPUT
6
6.0

Arithmetic operators

Here are the operators you will use most often.

OperatorNameExampleResult
+Addition7 + 310
-Subtraction7 - 34
*Multiplication7 * 321
/Division (always float)7 / 23.5
//Floor division7 // 23
%Modulo (remainder)7 % 21
**Exponent (power)2 ** 38

Floor division and modulo

Regular division with / always gives a float. Floor division // throws away the fractional part and keeps the whole number. Modulo % gives the remainder. These two are a great team:

PYTHON
total_minutes = 125
hours = total_minutes // 60
minutes = total_minutes % 60
print(hours, "hours and", minutes, "minutes")
▸ OUTPUT
2 hours and 5 minutes

The modulo operator is also the usual way to check whether a number is even: n % 2 == 0 is true for even numbers because they divide by 2 with no remainder.

Exponents

Use ** to raise a number to a power. It also works with fractional powers to find roots:

PYTHON
print(5 ** 2)
print(2 ** 10)
print(9 ** 0.5)
▸ OUTPUT
25
1024
3.0

Operator precedence

When an expression has several operators, Python follows the same precedence rules you learned in school, often remembered as PEMDAS: Parentheses first, then Exponents, then Multiplication and Division (left to right), then Addition and Subtraction (left to right).

PYTHON
print(2 + 3 * 4)
print((2 + 3) * 4)
print(2 ** 3 + 1)
▸ OUTPUT
14
20
9

In the first line, 3 * 4 happens before the addition, giving 14. Parentheses let you override the default order, as the second line shows. When in doubt, add parentheses to make your intent clear, even if they are not strictly required.

The math module

For more advanced operations, Python includes a math module. You bring it in with an import statement, then use its functions and constants with a dot:

PYTHON
import math

print(math.sqrt(16))
print(math.pi)
print(math.floor(3.7))
print(math.ceil(3.2))
print(round(3.14159, 2))
▸ OUTPUT
4.0
3.141592653589793
3
4
3.14

Notice that round() is a built-in function (no import needed) that rounds to a chosen number of decimal places, while math.floor and math.ceil always round down and up to whole numbers. You will learn much more about modules later.

Try a small calculation of your own: compute the area of a circle using math.pi * radius ** 2. Notice how precedence handles the exponent before the multiplication automatically.