# Operators in Python

This tutorial covers the different types of operators in Python, operator overloading, precedence and associativity.
Aug 2018  · 9 min read

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.

``````# 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.
``````

## 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 variable `balance`, you can do the following:

``````balance = 100
print(balance)
``````
``````100
``````

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)
``````
``````110
``````

The same holds for `-=`, `balance -= 10` is the same as `balance = balance - 10`:

``````print(balance)
balance -= 10
print(balance)
``````
``````110
100
``````

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:

• Equal: `==`
• 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
``````

`==` 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.

``````print("Hello" == "World")
print("Python" != "R")
``````
``````False
True
``````

## 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`, `or` and `not`.

`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
True True True
True False False
False True False
False False False

`or` is True, whenever any (one or more) operand is True.

``````print(True and True)
print(True and False)
``````
``````True
False
``````
a b a or b
True True True
True False True
False True True
False False False

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 `True` if `False` is given and vice-versa.

``````print(not True)
``````
``````False
``````
a not a
True False
False True

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.

``````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)
``````
``````True
False
``````

## Precedence

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
``````
``````True
``````

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.

``````print(5 * 2 // 3)
``````
``````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))
``````

## 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.

Python Courses

### .css-1531qan{-webkit-text-decoration:none;text-decoration:none;color:inherit;}Introduction to Data Science in Python

BeginnerSkill Level
4 hr
443.2K
Dive into data science using Python and learn how to effectively analyze and visualize your data. No coding experience or skills needed.
See Details
Start Course

### Intermediate Python

BeginnerSkill Level
4 hr
988.7K
Level up your data science skills by creating visualizations using Matplotlib and manipulating DataFrames with pandas.

### Introduction to Python

BeginnerSkill Level
4 hr
5.1M
Master the basics of data analysis with Python in just four hours. This online course will introduce the Python interface and explore popular packages.
See More
Related  ### Free Access Week | Aug 28 – Sept 3

Access DataCamp's entire platform for free, including all 440+ courses, for an entire week. No catch, no credit card required—just unlimited learning for anyone with internet access.

Will Rix

5 min

### How to Choose The Right Data Science Bootcamp in 2023 (With Examples)

Learn everything about data science bootcamps, including a list of top programs to kickstart your career.  ### DataCamp Portfolio Challenge: Win \$500 Publishing Your Best Work

Win up to \$500 by building a free data portfolio with DataCamp Portfolio. DataCamp Team

5 min

### 10 Essential Python Skills All Data Scientists Should Master

All data scientists need expertise in Python, but which skills are the most important for them to master? Find out the ten most vital Python skills in the latest rundown.

Thaylise Nakamoto

9 min

### A Complete Guide to Socket Programming in Python

Learn the fundamentals of socket programming in Python Serhii Orlivskyi

41 min

### Chroma DB Tutorial: A Step-By-Step Guide

With Chroma DB, you can easily manage text documents, convert text to embeddings, and do similarity searches.
See MoreSee More