Arithmetic operators are syntactical shortcuts to perform basic mathematical operations on numbers.
Operator | Name | Description | Example |
---|---|---|---|
+ | Addition | Calculating the sum of the two operands | 3 + 4 == 7 |
β | Subtraction | Subtracting the second operand from the first operand | 4 - 3 == 1 |
* | Multiplication | Multiplying the first with the second operand | 3 * 4 == 12 |
/ | Division | Dividing the first by the second operand | 3 / 4 == 0.75 |
% | Modulo | Calculating the remainder when dividing the first by the second operand | 7 % 4 == 3 |
// | Integer Division, Floor Division | Dividing the first operand by the second operand and rounding the result down to the next integer | 8 // 3 == 2 |
** | Exponent | Raising the first operand to the power of the second operand | 2 ** 3 == 8 |
Table of Contents
Python Arithmetic Operators Precedence
Python’s arithmetic operators have the following operator precedence relationship:
- parentheses takes precedence before the exponent operator,
- the exponent operator takes precedence before multiplication, division, and floor division,
- multiplication and division operators take precedence before modulo, and
- modulo takes precedence before addition and subtraction.
Here’s the table of all arithmetic operators ordered from high to low predence:
Operators | Meaning |
---|---|
() | Parentheses |
** | Exponent |
* | Multiplication |
/ | Division |
// | Floor division |
% | Modulo |
+ | Addition |
– | Subtraction |
Addition
Python provides the addition operator +
to add two objects. The semantics of the addition depends on the operands’ data types. For example, adding two integers perform arithmetic addition whereas adding two lists performs list concatenation. The specific return value of the addition operator is defined in a data types’ __add__()
magic method.
Have a look at the following examples!
The + operator on integer operands yields another integer—the mathematical sum of both operands:
>>> 2 + 2 4 >>> 2 + 3 5 >>> -99 + (-1) -100
If at least one of the operands is a float value, the result is also a float—float is infectious!
>>> 2.0 + 1 3.0 >>> 1 + 2.2 3.2 >>> 2.0 + 40.0 42.0
Can we add strings? Of course! The result is a new string from gluing the second string to the first. This is called string concatenation:
>>> 'learn' + ' python' 'learn python' >>> 'fi' + 'nxter' 'finxter'
If the operands are lists, the result of the addition operation is another list. It creates a new list with the elements of the first list plus the elements of the second list. The original lists remain unchanged.
>>> [1, 2] + [3, 4] [1, 2, 3, 4] >>> l1 = ['alice'] >>> l2 = ['ann', 'bob'] >>> l1 + l2 ['alice', 'ann', 'bob'] >>> l1 ['alice'] >>> l2 ['ann', 'bob'] >>>
What if two operands have an incompatible data type—unlike floats and integers? For example, if you try to add a string to a list?
>>> 'hello' + ['world'] Traceback (most recent call last): File "<pyshell#15>", line 1, in <module> 'hello' + ['world'] TypeError: can only concatenate str (not "list") to str
The result of incompatible addition is a TypeError
. You can fix it by using only compatible data types for the addition operation.
Related Tutorial: Addition
Subtraction
Python provides the subtraction operator -
to subtract one object from another. The semantics of the subtraction depends on the operands’ data types. For example, subtracting two integers performs the arithmetic difference operation whereas subtracting two sets performs the set difference operation. The specific return value of the minus operator is defined in a data types’ __sub__()
magic method.
Have a look at the following examples!
The – operator on integer operands yields another integer—the mathematical difference of both operands:
>>> 2 - 2 0 >>> 2 - 3 -1 >>> -99 - (-1) -98
If at least one of the operands is a float value, the result is also a float—float is infectious!
>>> 2.0 - 1 1.0 >>> 1 - 2.2 -1.2000000000000002 >>> 44.0 - 2.0 42.0
You can also perform the subtraction operator on Python sets. In this case, it calculates the set difference, i.e., it creates a new set with elements in the first but not in the second operand.
Here’s an example:
>>> {1, 2, 3} - {1, 2} {3} >>> {'Alice', 'Bob'} - {1, 'Bob'} {'Alice'} >>> {1, 2, 3} - {1, 2, 3, 4, 5} set()
What if two operands have an incompatible data type? For example, if you try to subtract a set from a string?
>>> 'hello' - {1, 2, 3} Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> 'hello' - {1, 2, 3} TypeError: unsupported operand type(s) for -: 'str' and 'set'
The result of incompatible addition is a TypeError
. You can fix it by using only compatible data types for the operation.
Related Tutorial: Subtraction
Multiplication
Python’s multiplication operator *
multiplies two objects. The semantics of the multiplication depends on the operands’ data types. For example, multiplying two integers performs arithmetic multiplication whereas multiplying a list with an integer performs list concatenation. The specific return value of the multiplication operator is defined in a data types’ __mul__()
magic method.
Have a look at the following examples!
The *
operator on integer operands yields another integer—the mathematical product of both operands:
>>> 2 * 2 4 >>> 2 * 3 6 >>> 2 * 4 8 >>> 16 * 16 256
If at least one of the operands is a float value, the result is also a float—float is infectious!
>>> 2.0 * 44 88.0 >>> 4 * 2.2 8.8 >>> 2.2 * -2.2 -4.840000000000001
We can also multiply a string with an integer that performs string concatenation, concatenating the same string n times assuming n is the second integer operand:
>>> 'boom! ' * 10 'boom! boom! boom! boom! boom! boom! boom! boom! boom! boom! '
In fact, you can multiply other sequence types with integers as well such as lists. The result is the same sequence appended to itself n times. The original lists remain unchanged.
>>> [1, 2] * 3 [1, 2, 1, 2, 1, 2] >>> ('Alice', 'Bob') * 5 ('Alice', 'Bob', 'Alice', 'Bob', 'Alice', 'Bob', 'Alice', 'Bob', 'Alice', 'Bob')
What if two operands have an incompatible data type—unlike floats and integers?
>>> 'hello' * 'hi' Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> 'hello' * 'hi' TypeError: can't multiply sequence by non-int of type 'str'
The result of incompatible addition is a TypeError
. You can fix it by using only compatible data types for the operation.
Related Tutorial: Multiplication
Division
The double-frontslash //
operator performs integer division and the single-frontslash /
operator performs float division. An example for integer division is 40//11 = 3
. An example for float division is 40/11 = 3.6363636363636362
.
>>> # Python 3 >>> 40//11 3 >>> 40/11 3.6363636363636362
Related Tutorial: Division
Modulo
In Python like in many other programming languages, the modulo operator is represented by the percent %
symbol. It returns the remainder of dividing the left by the right operand. For example, the modulo operation 7%2 returns 1 because seven divided by two is three with remainder 1.
The figure shows how the modulo operator works in Python for the example 7%3
.
- There’s a set with seven elements. This is the dividend of the operation.
- The divisor is 3. You divide the set of seven elements into packages of three elements.
- The remainder is 1. When dividing the set of seven elements into packages of three elements, one remains. This is the result of the modulo operation.
Here are a few examples:
Division | Division Without Remainder / Integer Division | Remainder / MODULO |
---|---|---|
7/2 == 3.5 | 7//2 == 3 | 7%2 == 1 |
8/2 == 4.0 | 8//2 == 4 | 8%2 == 0 |
10/3 == 3.33 | 10//3 == 3 | 10%3 == 1 |
14/5 == 2.8 | 14//5 == 2 | 14%5 == 4 |
The table shows the result of applying three different operators to two operands:
- The division operator
/
that divides the left by the right operand and returns a relatively precise float value. - The integer division operator
//
that divides the left by the right operand and returns the absolute (rounded down) integer value. - The modulo operator
%
that divides the left by the right operand using integer division and returns the remainder of the integer division.
Related Tutorial: Modulo
Integer Division
Integer division consists of two steps:
- Perform normal float division
a / b.
- Round the resulting float number down to the next integer.
Python 2.x per default divides two integers using integer division, also known as floor division because it applies the floor function after the regular division to “round it down”. Python 2 evaluates the expression 5/2
to 2
. However, the single front-slash for floor division “/” is depreciated and from Python 2.2 onwards, you should use the double front-slash operator for floor division. For example, the result of 5//2
is 2
.
An example of floor division is noted in the Python 3 code listed below:
>>> x = 60 // 12 >>> print(x) 5
So we see that when we need a whole number generated in our code to accomplish particular tasks we will use this floor division operator //
.
Related Tutorial: Integer Division, Floor Division
Exponentiation
Python has four ways to calculate the n
-th power (exponent) of x
so that xβΏ=x*x*...*x
that multiplies the base x
with itself, and repeating this n
-times.
- Method 1: Use the double-asterisk operator such as in
x**n
. - Method 2: Use the built-in
pow()
function such as inpow(x, n)
. - Method 3: Import the math library and calculate
math.pow(x, n)
. - Method 4: Import the NumPy library and calculate
np.power(x, n)
.
Let’s dive into these four methods one by one!
Related Tutorial: Exponent
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.