Mathematical Operators

When we think about programming, we often think about mathematics and algorithms. While there are applications that go beyond mathematics, a lot of the calculations can be consolidated to a few main operators. In this chapter, we will dive into these basic operators and how we can use them on two numbers to calculate values.

While some of these mathematical operators exist in many other languages, Python has some operators that operate differently than other languages. The table below contains the operator, name of the operator, a brief description of the operator, an example of the operator used, and the result of the example.

OperatorNameDescriptionExample UseExample Result
+AdditionFinds the sum of two numbers19 + 221
-SubtractionFinds the difference of two numbers19 - 217
*MultiplicationFinds the product of two numbers19 * 238
/Floating Point DivisionFinds the floating quotient of two numbers19 / 29.5
//Integer DivisionFinds the integer quotient of two numbers19 // 29
**PowerFinds the exponent of two numbers19 ** 2361
%ModuloFinds the remainder of two numbers19 % 21

These are the basic mathematical operators in Python. Each operator has its usage. Some of these types can be used on more than one data type. The table below shows the possible data types each operator can be applied to.

OperatorApplicable Types
+Integer, Float, String, Boolean
-Integer, Float, Boolean
*Integer, Float, String (with an Integer), Boolean
/Integer, Float, Boolean
//Integer, Float, Boolean
**Integer, Float, Boolean
%Integer, Float, Boolean

You may have noticed that all of the operators can be applied to Integers, Floats, and Booleans. Addition can be applied to Strings too and Multiplication can be applied to Strings when they're with an Integer. This extra part about strings and integers may seem strange, but let's go into it more.

Why the Addition Operator is special

When we add two integers, the behavior is expected. We simply get the sum of two integers. For example, 3 + 9 will give us 12. However, normally, if we add two floats together, we should get the same expected behavior. For example, 3.0 + 4.0 will give us 12.0. There is one case that gives a strange outcome. This is when we try to take the sum of 0.1 + 0.2. While we may expect to get 0.3, we end up getting a different value with the value of 0.30000000000000004. This is due to how floating point decimals are handled in the binary representation itself. For more information, please read the appendix chapter on IEEE-754, Binary, and Floating Points.

That's the addition operator on integers and floating points, but what about on Boolean values? Well, if we try this on Booleans, we'll see the following behavior:

Let's say we add two True values together. So we get True + True. This will give us 2. What if we try True + False? If we run this code, we'll see that we get 1. This can be broken down to a simple mathematics problem. What number added to itself gives us 2? Well, the answer must be 1. Concurrently, what number added to 1 will give us 1? That must be 0. Therefore, from this deduction, True must be 1 and False must be 0! Knowing this, this should answer the question about how we're able to use all the mathematical operators on boolean values. At the end of the day, boolean values can be simply converted into 1 or 0 depending if the value is True or False.

So, that explains integers, floats, and boolean values with the addition operator. What about strings? What happens when we add two strings together? Let's take the following code snippet for instance:


print("hello" + "world")

When we run this, we get helloworld as one long string. Here, we can see that adding two strings together will simply combine the two strings. This is what we call Concatenation. We will see this in far more detail in the Strings chapter. For now, it's important to understand that strings can be added together and they simply create longer strings.

Why the Multiplication operator is special

When we multiply two integers or two floating point values, we get an expected result. We get the product of these two numbers. This time, there's no strange outcome when we multiple two floating point values. While we could multiply two boolean values together, there aren't really any reasons to do so, since we'd be multiplying with 1 or 0. Multiplying strings are where this operator changes.

While we can multiply two integers with each other, as we can with two floats and two boolean values, we cannot do the same with strings. If we try to multiply two strings together, we're met with an error stating: TypeError: can't multiply sequence by non-int of type 'str'. This may seem intimidating but all it's saying is that we cannot multiply a string with a string. However, as stated above and stating in the error message, we can multiply a string by an integer. Let's try it with "hello" * 3. If we try to print("hello" * 3), we are no longer greeted by an error message, but now get hellohellohello. This follows the concept of concatenation. The string is being concatenated by itself based on the integer provided. If we standardized this with variables, we could take a string, let's call it string, and multiply it by some integer, let's call that n. When we multiply the string variable string, by the integer variable n, we extend string n times. Try this yourself to see how this works!

Subtraction operator

The subtraction operator behaves as expected with the numeric data types. Integers, floats, and boolean values subtracted together give the expected output. If we try to subtract from a string, we'll get the error message: TypeError: unsupported operand type(s) for -: 'str' and 'str'. This is an error telling us we cannot subtract two strings together. If we try to subtract a number from a string, we also get the error message: TypeError: unsupported operand type(s) for -: 'str' and 'int'.

Floating Division Operator

When we divide with a single /, we get floating point division. This will divide two numbers and keep the decimal. Regardless of whether we divide two integers or two floats, we will end up with decimal values, even if the resulting quotient is a whole number. For example, 4 / 2 gives us 2.0. This is important because we may not always want the decimal value. This is where the Integer Division Operator comes in. Before that, let's quickly address strings. Strings cannot be divided using either division operators. The error message will be similar to the subtraction error message.

Integer Division Operator

When we divide with two /, we get integer division. The difference between // and / is the floating point decimal given. When we use the integer division on either two integers or two floats or a mix between them, we'll always get a whole number returned. For example, 4 // 2 gives us 2. If we use numbers that should not return a whole number, such as 5 // 2, we end up with 2. We lose the decimal place as only an integer is returned. If we use the integer division operator on two floating points, the result remains as a float, but excludes the actual decimal value. For example, if we tried 3.3 / 2, we would get 1.65. However, if we did 3.3 // 2, we end up with 1.0. This may seem strange, but it is effectively turning the numbers into integers, running the division operation on the integers, then turning the resulting integer back into a floating point. This causes the result to be 1.0 instead of 1. This change of type will be explored more in the Casting chapter.

Power Operator

When we take the power of two numbers, we end up with the expected outcome. If we take 2 ** 8, we would find 28 , which gives us 256. This works with floating point values too, such as 9 ** 1.5 giving us 27.0.We cannot use the power operator on strings.

Modulo Operator

The last of the main mathematical operators, we have the modulo operator. This operator takes the remainder of two numbers. If the left number is less than the right number, we are left with the smaller number. Otherwise, integer division is used and ultimately, the returning value is the remainder of the quotient before entering decimal division. While the modulo or remainder operator may not seem useful, it has many uses in the field of programming. From checking for the parity of a number, to divisibility, to processing rotations in turn-based systems.

Zero Division

One point to note about both division operators and the modulo operator is we cannot divide a number by 0. In Python, we are left with a ZeroDivisionError: division by zero error.