Arithmetic Operators
Arithmetic Operators will let you perform simple mathematical-like operations. The most intuitive use case is with numbers, but they'll also work with several other type like strings or collections.
These are the most common ones:
print(5 + 2)
print(5 - 2)
print(5 * 2)
print(5 / 2)
print(5 ** 2) # 5² == 5 * 5
7
3
10
2.5
25
But we also have a few less-common but equally important:
Floor Division
(Also known as Integer Division)
print(5 // 2)
print(4 // 2)
2
2
Modulus
(Also known as "the remainder")
print(4 % 2)
print(5 % 2)
print(10 % 2)
print(11 % 2)
0
1
0
1
Arity of arithmetic operators
As you saw in the introduction, some of these operators will work as both binary and unary operators. Both the minus (-
) and plus (+
) symbols fall in this category:
print(+3)
print(-5)
x = 2
print(+x)
print(-x)
3
-5
2
-2
Files associated with this lesson:
Lesson.ipynb
Arithmetic Operators will let you perform simple mathematical-like operations. The most intuitive use case is with numbers, but they'll also work with several other type like strings or collections.
Binary Operators¶
Probably the most common type of operator, the type you deal with everyday:
print(5 + 2)
print(5 - 2)
print(5 * 2)
print(5 / 2)
print(5 ** 2) # 5² == 5 * 5
x = 5 + 2
x
Unary operators¶
Binary operators are the ones we're most used to. But there are also Unary operators we might need. Check out this example:
x = 1
-x
In this case we're negating the content of x
. Important, the value of x
is still the same:
x
Other important operators¶
There are some other operators less common in "human arithmetics" but we still use in programming, for example:
Floor Division
(Also known as Integer Division)
5 / 2
print(5 // 2)
print(4 // 2)
Modulus
(Also known as "the remainder")
print(4 % 2)
print(5 % 2)
print(10 % 2)
print(11 % 2)
Python 2 vs Python 3¶
Python 3 changed the way division operators worked in Python 2. In Py2, the regular divisor operator /
worked as "integer" division when applied with integers. Python 3 changed that and introduced the "integer divisor" //
as we saw before.
Operator overloading¶
As you'll see in more advanced courses (Advanced Object Oriented programming in Python), operators in Python can be overloaded to integrate them in our own classes. For example, the +
operator can be overridden with the __add__
method:
(2).__add__(3)
You don't need to worry about this now, it's something we'll see in the future to create more expressive and readable code. It's also what allows us to use operators with other types that are not numbers, for example with strings or collections:
"hello" + " " + "world"
['Python', 'Ruby', 'C++'] + ['R', 'Stata', 'Fortran']