Knowledge for the World

Basic math in Python

  • by tyler (203)
  • 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.

1

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.
>>>
2

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

OperatorNameDescriptionExample
+AdditionAdd two numbers.2 + 2
-SubtractionSubtract a number from another.2 - 1
*MultiplicationMultiply two numbers.2 * 2
/DivisionDivide a number by another.2 / 2
%ModulusGet the remainer of the left hand operand divided by the right hand operand.10 % 3
**ExponentPerforms exponential power operations.2 ** 3
//Floor DivisionDivision 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.

3

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
4

>>> 100 - 30
70
5

>>> 10 * 3
30
6

>>> 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
7

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

>>> 10 % 3
1
8

>>> 2 ** 8
256
9

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
Series: Python Basics
Show all in this series