Just like in mathematics, programming languages like Python have operators. You can think of them as extremely simple functions that lie at the basis of computer science. These are the simplest operations to which a computer program can be reduced. They are essential knowledge for any aspiring Data Scientist or Software Engineer.
In this tutorial, you will learn about
- The different types of operators: Arithmetic, Assignment, Comparison and Logical
- Operator Overloading
If you would like to learn more about the basics of the Python Programming Language, make sure to check out our free Intro to Python for Data Science course.
You will probably already be familiar with these, since they come from basic mathematics.
The arithmetic operators are addition (
+), subtraction (
-), multiplication (
*), division (
/), exponent (
**), floor division (
//) and modulus (
%). The first four are fairly simple; they are addition, subtraction, multiplication and division, and you will probably already be familiar with them.
# Addition print(5 + 2) # Subtraction print(5 - 2) # Multiplication print(5 * 2) # Division print(5 / 2)
7 3 10 2.5
The other three are a bit more complicated. The exponent operator means 'raised to the power of'. For example,
2 ** 3 means that
2 is multiplied with itself
3 times, so
2 ** 3 is the same as
2 * 2 * 2, which is equal to 8.
Floor division is the same as normal division, except that the result is always rounded off to the bottom. In the example below, 5 is divided by 2, resulting in 2.5. But since it's the floor division, 2.5 is rounded off to 2.
Finally, the modulus is the remainder after division. In the case of
5%2, the number 2 only fits twice in 5, which means that the remained is 1.
# Exponent print(5 ** 2) # This is the same as 5 * 5 # Floor Division print(5 // 2) # Modulus print(5 % 2)
25 2 1
In Python, the addition operator can also be used to concatenate strings. This means that they will be assembled into a single string, for example:
firstName = "Théo" introduction = "Hi, my name is " + firstName + "." print(introduction)
Hi, my name is Théo.
If you have some programming experience, you will certainly have used assignment operators before. They assign a certain value to a variable. The most used one is
=. To use it, simply type the name of the variable you want to assign a new value to, the
=, and the value you want to be assigned. For example, if you want to assign the value 100 to the variable
balance, you can do the following:
balance = 100 print(balance)
If you want to increment the value of
balance with 10, you can use
balance += 10. This is the equivalent of
balance = balance + 10, but it's much shorter.
balance += 10 print(balance)
The same holds for
balance -= 10 is the same as
balance = balance - 10:
print(balance) balance -= 10 print(balance)
The other assignment operators work in exactly the same way. These are:
You can use comparison operators to, you guessed it, compare the values of variables. They will always return a boolean value, which is either
False. There are six of them:
- Not equal:
- Greater than:
- Less than:
- Greater than or equal:
- Less than or equal:
Here are some example comparisons:
a = 3 b = 5 print(a == b) # Equal print(a != b) # Not equal print(a > b) # Greater than print(a < b) # Less than print(a >= b) # Greater than or equal to print(a <= b) # Less than or equal to
False True False True False True
!= can also be used to compare strings instead of numbers. The other operators are not compatible with strings, since a string can't really be greater than another string.
print("Hello" == "World") print("Python" != "R")
You might already be familiar with these! In logic, they are called logical connectives. These are also widely used in human language. They are:
and will only return True if both operands (the two boolean objects you are comparing) are True. For example:
print(True and True) print(True and False) print(False and False)
True False False
To understand the behavior of this logical operator, you can make use of a truth table:
|a||b||a and b|
or is True, whenever any (one or more) operand is True.
print(True and True) print(True and False)
|a||b||a or b|
Notice that these also work with more than two operands, for example:
print(True and True and True and True) print(True and True and True and False) print(False or False or False or False) print(False or False or False or True)
True False False True
not will return the opposite of its operand, so
False is given and vice-versa.
Remember that earlier, you saw how
+ can be used to add up numbers, but that it can also be used to concatenate, or combine strings. So
+ works differently, depending on what type of object you use it on. But this will not always be the case. Sometimes, the operator you're working with just doesn't support the type of object you want to use it on.
Here's an example. Say you have two
filou. These belong to the
Dog class below. You can think of the class as a blueprint for what the objects must look like and how they should behave. In this case, the
Dog objects have a name, age and height. After the class is defined, you can instantiate objects. One of them is Ozzy, with an age of 3 and height of 30 centimeters. The other one is Filou, he is 5 years old and 65 centimeters tall.
This example uses the concept of Object-Oriented Programming. If you would like to learn more about that, make sure to read our tutorial on Object-Oriented Programming in Python
Say you wanted to compare both dogs with the greater than:
>. This will not work. You will get an error saying
'>' not supported between instances of 'Dog' and 'Dog'. This means that
> does not know how to compare objects of the
class Dog: def __init__(self, name, age, height): self.name = name self.age = age self.height = height ozzy = Dog("Ozzy", 3, 30) filou = Dog("Filou", 5, 65) print(filou > ozzy)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-96-428069ab24cc> in <module>() 9 filou = Dog("Filou", 5, 65) 10 ---> 11 print(filou > ozzy) TypeError: '>' not supported between instances of 'Dog' and 'Dog'
Luckily, with operator overloading, you can define the operator's behavior for when it is called on
Dog objects. In this case, a method called
__gt__, meaning 'greater than', has to be defined, taking in two arguments. Since we want to compare our dogs on their height, the method returns
self.height > other.height.
class Dog: def __init__(self, name, age, height): self.name = name self.age = age self.height = height def __gt__(self,other): return self.height > other.height ozzy = Dog("Ozzy", 3, 30) filou = Dog("Filou", 5, 65) print(filou > ozzy) print(ozzy > filou)
When you're combining lots of operators, things can get confusing. Take a look at the example below:
a = 2 b = 3 c = 9 a ** b > 5 and c - a // b >= 9 or b ** 2 == c
How do you know which one will be executed first? How should you read a line of code a lot of these symbols? Is it executed from left to right or is there some specific order?
This is where precedence comes in. Python operators are executed in a very specific order, and some have priority over others.
In the following table, you can see the precedence for operators, in order from top to bottom. These rules are the same in mathematics, where certain calculations in a formula have to be performed before others.
|2||*, /, %, //||multiply, divide, modulo, floor division|
|3||+, -||plus, minus|
|4||>, <, >=, <=||comparison|
|6||= %= /= //= -= += *= **=||assignment|
|7||and, or, not||logical|
You have seen that precedence matters! But what about the ones that are on the same precedence level, like multiplication and division? Are they executed at the same time? No.
\\ are executed from left to right, while
** is executed from right to left. This is called associativity.
Take a look at the following example. In this case, the operators will be executed from left to right, and the output is 3.
print(5 * 2 // 3)
By adding parentheses, however, you can change the order in which the operators are executed. That is associativity, which works the same way as associativity in maths. Whatever is between brackets will be calculated first. In this case, the floor division will be performed first, followed by the multiplication.
print(5 * (2 // 3))
You now know what operators are, how you should use them and how they work. You also learned about overloading, precedence and associativity. You're well on your way to becoming a Python master! If you want to learn even more, don't hesitate to check out our Intermediate Python for Data Science course.
← Back to tutorial