Basic Math in Python

John John (304)
10 minutes

The goal for this guide is to demonstrate the most commonly used arithmetic operators. You should try to become familiar with each of these as they will be used in all kinds of Python applications.

Posted in these interests:
h/python67 guides
h/code69 guides

Unlike the previous guide, we're going to use a Python shell to run the commands. A shell is simply an interface for accessing some service, in this case Python.

Python ships with a shell by default. To open the Python shell, use the following:

python3

You should shell a Python prompt that looks something like this:

Python 3.6.5 (default, Mar 30 2018, 06:41:53)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

Here are the operators we'll cover in this guide:

Operator Name Description Example
+ Addition Add two numbers. 2 + 2
- Subtraction Subtract a number from another. 2 - 1
* Multiplication Multiply two numbers. 2 * 2
/ Division Divide a number by another. 2 / 2
% Modulus Get the remainer of the left hand operand divided by the right hand operand. 10 % 3
** Exponent Performs exponential power operations. 2 ** 3
// Floor Division Division with the decimal point removed. 3 // 2

Each of these operators will be covered in the following steps. To gain familiarity with the Python shell as well as arithmetic operators, open a Python shell and practice using each operator.

Chances are, you've encountered this one before. In case you haven't, it's the process of finding the sum of two or more numbers.

>>> 2 + 2
4
>>> 100 - 30
70
>>> 10 * 3
30
>>> 40 / 10
4.0

Notice here that the result is not 4. It's 4.0. Python 3 uses true division (as opposed to Python 2, which uses floor division). This means the result will always be a floating point number representing the fractional result. See the different:

Python 2

>>> 1 / 2
0

Python 3

>>> 1 / 2
0.5

Related to the division operator, this operator gives us the remainder of a division operation.

>>> 10 % 3
1
>>> 2 ** 8
256

This operator gives us what we expect from the division operator in Python 2. It performs the division operation and returns an integer, chopping off any trailing decimals.

>>> 10 // 3
3
John John (304)
0

Descriptors are used to manage access to an attribute. They can be used to protect an attribute from changes or automatically update the value of a dependent attribute, as we'll see in this guide.