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.
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.
Artithmetic Operators
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.
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.
# Exponentprint(5**2)# This is the same as 5 * 5# Floor Divisionprint(5//2)# Modulusprint(5%2)
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:
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.
The other assignment operators work in exactly the same way. These are:
*=
/=
**=
//=
%=
Comparison Operators
You can use comparison operators to, you guessed it, compare the values of variables. They will always return a boolean value, which is either True or False. There are six of them:
a =3
b =5print(a == b)# Equalprint(a != b)# Not equalprint(a > b)# Greater thanprint(a < b)# Less thanprint(a >= b)# Greater than or equal toprint(a <= b)# Less than or equal to
== and != 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.
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, or and not.
and will only return True if both operands (the two boolean objects you are comparing) are True. For example:
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 Dog objects, ozzy and 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 Dog class.
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.
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.
Precedence
Operator
Description
1
**
exponent
2
*, /, %, //
multiply, divide, modulo, floor division
3
+, -
plus, minus
4
>, <, >=, <=
comparison
5
==, !=
equality
6
= %= /= //= -= += *= **=
assignment
7
and, or, not
logical
Associativity
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. *, \, % and \\ 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.
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.
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.
Python offers three logical operators: and, or, and not. These operators, also known as Boolean operators, evaluate multiple conditions and determine an expression's overall truth value.
Get introduced to Python data structures: learn more about data types and primitive as well as non-primitive data structures, such as strings, lists, stacks, etc.
Learn about Python tuples: what they are, how to create them, when to use them, what operations you perform on them and various functions you should know.
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
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.
Artithmetic Operators
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.The other three are a bit more complicated. The exponent operator means 'raised to the power of'. For example,
2 ** 3means that2is multiplied with itself3times, so2 ** 3is the same as2 * 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.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:
Assignment Operators
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 variablebalance, you can do the following:If you want to increment the value of
balancewith 10, you can usebalance += 10. This is the equivalent ofbalance = balance + 10, but it's much shorter.The same holds for
-=,balance -= 10is the same asbalance = balance - 10:The other assignment operators work in exactly the same way. These are:
*=/=**=//=%=Comparison Operators
You can use comparison operators to, you guessed it, compare the values of variables. They will always return a boolean value, which is either
TrueorFalse. There are six of them:==!=><>=<=Here are some example comparisons:
==and!=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.Logical Operators
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,orandnot.andwill only return True if both operands (the two boolean objects you are comparing) are True. For example:To understand the behavior of this logical operator, you can make use of a truth table:
oris True, whenever any (one or more) operand is True.Notice that these also work with more than two operands, for example:
notwill return the opposite of its operand, soTrueifFalseis given and vice-versa.Operator overloading
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
Dogobjects,ozzyandfilou. These belong to theDogclass 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, theDogobjects 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 theDogclass.Luckily, with operator overloading, you can define the operator's behavior for when it is called on
Dogobjects. 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 returnsself.height > other.height.Precedence
When you're combining lots of operators, things can get confusing. Take a look at the example below:
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.
Associativity
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.
*,\,%and\\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.
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.
Conclusion
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.