Numbers are extremely common in programming. They are used to represent things like screen size dimensions, geographic locations, money and points, the amount of time that passes in a video, positions of game avatars, and colors through assigning numeric codes.
We’ll be working with two of Python’s most used numeric data types, integers and floats:
• Integers are whole numbers that can be positive, negative, or 0 (…, -1, 0, 1, …).
• Floats are real numbers, they contain a decimal point (as in 9.0 or -2.25).
This tutorial will go over operators that can be used with number data types in Python.
An operator is a symbol or function that indicates an operation. For example, in math the plus sign or + is the operator that indicates addition.
In Python, we will see some familiar operators that are brought over from math, but other operators we will use are specific to computer programming.
Here is a quick reference table of math-related operators in Python.
Addition and Subtraction
In Python, addition and subtraction operators perform just as they do in mathematics. In fact, you can use the Python programming language as a calculator.
Let’s look at some examples, starting with integers:
print(1 + 5)
Instead of passing integers directly into the print statement, we can initialize variables to stand for integer values:
a = 88
b = 103
print(a + b)
Because integers can be both positive and negative numbers (and 0 too), we can add a negative number with a positive number:
c = -36
d = 25
print(c + d)
Multiplication and Division with float values
k = 100.1
l = 10.1
print(k * l)
When you divide in Python 3, your quotient will always be returned as a float, even if you use two integers:
m = 80
n = 5
print(m / n)
Python 2’s / operator performs floor division, where for the quotient x the number returned is the largest integer less than or equal to x. If you run the above example of print(80 / 5) with Python 2 instead of Python 3, you’ll receive 16 as the output without the decimal place. In Python 3, you can use // to perform floor division. The expression 100 // 40 will return the value of 2. Floor division is useful when you need a quotient to be in whole numbers.
The % operator is the modulo, which returns the remainder rather than the quotient after division. This is useful for finding numbers that are multiples of the same number, for example.
Let’s look at the modulo in action:
o = 85
p = 15
print(o % p)