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:
Arithmetic operators
Here are the operators you will use most often.
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 7 + 3 | 10 |
- | Subtraction | 7 - 3 | 4 |
* | Multiplication | 7 * 3 | 21 |
/ | Division (always float) | 7 / 2 | 3.5 |
// | Floor division | 7 // 2 | 3 |
% | Modulo (remainder) | 7 % 2 | 1 |
** | Exponent (power) | 2 ** 3 | 8 |
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:
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:
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).
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:
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.