Numbers in Python operate the same way they do in real life. You can use them for addition, subtraction, multiplication, division – the uses go on and on. You can perform any equation in Python that you can in real life – and even a few that you can’t. The great thing about Python is that you don’t need to actually perform the math yourself – Python does all of the hard work for you.
We will be working with Python math exclusively in this series. You can use numbers for a lot more than simply math in Python, of course, and we will demonstrate that in a later article. For now, however, we are going to learn how to use basic numbers and, more specifically, Python math operators.
Editor’s Note: Looking for a good Python IDE or code editor? Check out our list of Best Python IDEs and Code Editors for 2021.
Math Operators in Python
Python math operators are something you are no doubt familiar with. You have been using them your entire life, and for the most part, they work in Python the same way you expect them to. The following are the operators you can use on numbers in Python:
- +: The addition operator. You can perform addition with this operator.
- -: The minus operator. You can perform subtractions with this operator.
- *: The multiplication operator. You can perform multiplication with this operator.
- /: The division operator. You can perform division with this operator.
- **: The exponentiation operator. You can raise numbers to a power with this operator.
- %: The modulus operator. You can use this to return the remainder from a division.
Numeric Data Types in Python
In Python, data types define what type of data or values variables can hold. Numbers have three data points in Python. These are:
- int: Integers or whole numbers. Can range from 0 to any number imaginable. Can also contain negative numbers within the same range. Example of int numbers include 0,100,10000000000, -5402342, and so on.
- float: Floating-point numbers or numbers that contain decimal points. Floats can contain negative numbers as well as positive numbers so long as they have a decimal point in them. Unlike integers, floating-point numbers do have a maximum size, at which point they become inf or -inf (in the case of negative numbers), which stands for infinity – even though it isn’t technically infinite. Examples of float numbers include 0.4, 2.2, -50.9, and so forth.
- complex numbers: Complex numbers are used for data science, scientific notation, and high-level math, all of which are beyond the scope of this article. Complex numbers are rarely used in Python outside of these areas. You can learn more about complex numbers at the official Python documentation website’s Numeric and Mathematical Functions page.
When we create variables in Python, we also define the type of data those variables will contain. There are several methods we can employ to do this. One of them is known as literal. The code below shows how to create an integer literal in Python:
secretCode = 4815162342 countdown = 108
The above code demonstrates how to create int literals in Python. We call them literals because we have assigned them a value that Python literally assumes. Python sees numbers that are not encased in quotes and knows those values are numeric and are to be treated as such. Further, Python sees that there are no floating-point numbers in our variables and can further extrapolate that the values are integers – or int in nature.
Another thing to note about numbers in Python is the fact that we cannot use comma-delineation in large numbers. That is, we cannot express 1 million as “1,000,000”. Commas are reserved for other purposes in Python, so therefore, trying to define an int holding 1,000,000 in the following manner would return an unexpected result. Try it in your IDE or code editor:
lotto = 1,000,000 print(lotto);
When you run the above code, you expect that Python will print out “1,000,000”. However, what really happens is that Python prints out:
(1, 0, 0)
To get the expected result, instead, you would need to either assign the value without any commas, or you could use underscores instead to make it more readable and add readability to your code:
lotto = 1_000_000 print(lotto);
When you run this code, it now returns the value 1000000.
Floating-Point Numbers or Floats in Python
Floats get assigned the same way as int values in Python. Here is how that looks in code:
decimalExample = 12.0 negativeExample = -108.4815162342 print("This is a positive floating-point number: ",decimalExample); print("This is a negative floating-point number: ",negativeExample);
If you run this code in your integrated development environment, you will get the following output:
This is a positive floating-point number: 12.0 This is a negative floating-point number: -108.4815162342
Again, because we assigned a float value to our variable, it becomes a float literal. The same rule applies to large floating-decimal point values as integers in that you have to use underscores to delineate them versus commas. Another thing to know is that you can also assign values to a float by using exponential notation – or E notation for short. Here is an example of how that looks:
lotto = 1e6 print(lotto);
In this example, we created a variable named lotto and assigned it the value of a one with six 0’s following it, or, 1000000.0. When we create variables with E notation, those values are always floats.
How to Convert Between Integer and Float in Python
Python has two functions that let you convert between int and float values. Neither of them permanently changes the value of the variable holding the integer or floating-point number mind you. Instead, you can use it to convert an instance of the variable in a different format.
These functions are int() and float().
Here is an example showing the int() function in Python being used to convert a float to an integer:
decimalValue = 108.0 print("Here is the original value of our variable as a float: ", decimalValue); print("Here is the value converted to an int: "); print(int(decimalValue)); print("Here is the current value of our variable, showing no change in type: ", decimalValue);
As you can see from the output below, the value of decimalValue never actually changes; it remains the same after we use int to create an instance of it. Here is the output:
Here is the original value of our variable as a float: 108.0 Here is the value converted to an int: 108 Here is the current value of our variable, showing no change in type: 108.0
The function float() works in the same way, converting an integer into an instance of a floating-point number. Here is how that looks in code:
integerValue = 108 print("Here is the original value of our variable as a float: ", integerValue); print("Here is the value converted to an int: "); print(float(integerValue)); print("Here is the current value of our variable, showing no change in type: ", integerValue);
Here is the result of running this code:
Here is the original value of our variable as a float: 108 Here is the value converted to an int: 108.0 Here is the current value of our variable, showing no change in type: 108
Using the + Operator in Python
The + operator in Python is used for addition – at least when it is used on integers or floating-point numbers. When used on strings it does something else entirely. For now, we are going to focus on its use on numeric values.
You can add one or more numbers using the + operator, as you might suspect. The code for its use is simple enough:
104 + 104
Typing the above into the Python Shell would return the result of 104 plus 104, or, 208. Simple math. The same goes if you were to add two floats:
104.1 + 104.1
Typed into the Python Shell, the above equation would result in 208.2. Again, nothing magical going on here.
Where things begin to differ, however, is when we add an int and a float together. When we do this, no matter what, the returned value is always a float. Try the following code in your IDE:
integerValue = 104 decimalValue = 104.2 totalValue = integerValue + decimalValue print(totalValue);
Here, we create two variables: one holds an integer, the other a floating-point number. We then create a new variable called totalValue and assign it the sum of integerValue and decimalValue. The result is: 208.2.
Using the – Operator in Python
Just as the + operator is used to add numeric values, the – operator is used for subtraction. It follows the same rules as the + operator in that any subtraction from a float by any number will return a float. Here is an example of the – operator being used in Python code:
integerValue = 204 decimalValue = 104.2 totalValue = integerValue - decimalValue print(totalValue);
Running this code gives us: 99.8.
Using the * Operator in Python
The * operator is used to multiply numeric values in Python. Again, anytime you multiply a value by a floating-point number, the end result will be a float. Here is how you use the * operator on numbers in Python:
integerValue = 204 decimalValue = 104.2 totalValue = integerValue * decimalValue print(totalValue);
This quick code snippet would result in the return of the value: 21256.8.
Using the / Operator in Python
The / operator is used to divide one or more numeric values in Python. This operator deviates in behavior from the +, -, and * operators, in that, no matter which type of value you divide, it always returns a float. This means that even if you divide two int values, you still get a float. Try out the following code to see this in action:
integerValueOne = 208 integerValueTwo = 104 totalValue = integerValueOne / integerValueTwo print(totalValue);
When you run the above code, you can see that instead of an integer value, you get a float: 2.0.
Using the ** Operator in Python
The ** operator is used to raise a number by a power. For instance, if you input 8 ** 8, it would be the same as typing to 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8. If you exponentiate an int, an integer will be returned; if you exponentiate a float, it will return a float. Here is how that looks in code:
powerInteger = 8 ** 8 powerIntegerTwo = 8.0 ** 8.0 print(powerInteger); print(powerIntegerTwo);
This results in the following output:
Using the % or Modulus Operator in Python
The % or modulus operator is used to return the remainder of a division in an equation. For example, if we divide 4 into 9, we know the result will be 2 with a remainder of 1. If you wrote this using the modulus operator, we would get the result of the remainder only, or, in this case, 1.
Here is the % operator in use:
modExample = 9 % 4 print(modExample);
Operator Order of Precedence in Python
When we perform math in Python, as in real life, equations are read in what is known as order of precedence. This means that certain operators get evaluated before others. In Python, the *, /, //, and % operators have the highest precedence (they are all equal to one another in precedence). They get evaluated prior to + and – operators, which have lower precedence.
We can force the order that we want equations to be evaluated in Python by encasing them in parentheses (). To see how this works and why it matters, enter the following code into your IDE and run it to see the difference order of precedence makes:
regularOrder = 4 * 4 - 2 + 2 forcedOrder = 4 * 4 - (2 + 2) print(regularOrder); print(forcedOrder);
Even thoough these equations look the same, their outcome is completely different. Running this program results in the following output:
Other Python Math Considerations
There is still a lot of ground to cover when it comes to math and numeric values in Python – we’ve only just skimmed the surface. In a later article, we will look at math functions and methods in Python as well and even take a gander at some Python math modules and libraries.
One final note about the math operators included in this Python tutorial: working with negative values will drastically change your results and can give you unexpected behavior. Take the code examples in this article and try them out on your own using negative numbers to see how it differs.