Maybe you’ve finished a course on YouTube or Udemy about Python Programming, and you’ve learned some intermediate level concepts such as object-oriented programming and using functions. Most of these courses do not broach the Python Operators subject very well, but this tutorial will explain all of them one by one in-depth.
Table of Contents
- 7 Categories of Python Operators
- 1. Arithmetic Operators
- 2. Assignment Operators
- 3. Comparison Operators
- 4. Logical Operators
- 5. Identity Operators
- 6. Membership Operators
- 7. Bitwise Operators
7 Categories of Python Operators
- Arithmetic Operators
- Assignment Operators
- Comparison Operators
- Logical Operators
- Identity Operators
- Membership Operators
- Bitwise Operators
=> Join the Waitlist for Early Access.
1. Arithmetic Operators
We all studied the arithmetic operations in elementary school like addition, subtraction, multiplication, and division, but that was in the math class; and now as a programmer, we must understand how to use these arithmetic operators inside of our programs. So, let’s start with a simple example:
Age1 = 15 Age2 = 40 print("The addition is:", Age1 + Age2)
The addition operator is the same as the one that you’ve used in math class when you were a kid. It sums together as many numbers as you want. But there is something that you can do in Python with this symbol that grade school mathematics did not allow, which is adding string objects (Texts) together.
Let’s see an example:
name1 = "Python" name2 = "Developer" print("My position is a:", name1 + name2)
We could add two strings but as you see they are very close to each other, so we can fix this by adding “ “ to our code:
name1 = "Python" name2 = "Developer" print("My position is a:", name1 + " " + name2)
Next, let’s move to the subtraction operator which is the same symbol that you know from math class:
Age1 = 15 Age2 = 40 print("The subtraction is:", Age1 - Age2) print("The subtraction is:", Age2 - Age1)
If the first number is smaller than the second number you will get a negative result.
For the multiplication operator, we’ve learned that this “x” symbol is used in mathematics, but in programming, we use the “*” asterisk:
Age1 = 15 Age2 = 40 print("The Multiplication is:", Age1 * Age2)
We can also perform multiplication on strings:
name = "Python" print(name * 3)
The division operator in Python is performed by using the “/” symbol:
Age1 = 15 Age2 = 40 print("The division is:", Age1 / Age2) print("The division is:", Age2 / Age1)
There is another symbol used in Python that you probably never heard of called the modulo operator which returns the remainder of a division calculation:
Age1 = 15 Age2 = 40 print("The Modulo is:", Age1 % Age2) print("The Modulo is:", Age2 % Age1)
Another arithmetic operator in Python is the floor division operator:
Age1 = 15 Age2 = 40 print("The floor division is:", Age1 // Age2) print("The floor division is:", Age2 // Age1)
The floor division operator returns the largest possible integer in a division calculation without a remainder.
The final arithmetic operator is the exponential operator. Denoted with two asterisks “**”:
Age1 = 15 print("The exponential is:", Age1 ** 3)
2. Assignment Operators
The assignment operator is the “=” symbol, which is used in every programming language, not just Python to assign a value to a variable like this example below:
num = 55 print(num)
Augmented Assignment Operators
Augmented Assignment Operators (“+=“, “-=“, “/=“, “*=“, “//=“, “%=“, and “**=“) are slightly different than the normal “=” assignment operator because augmented assignment operators not only assign values to variables, but apply mathematical operations to those values, then stores them inside of the variable.
num = 55 num += 22 print(num)
The code block above has added the number 22 to the num value and the code is equivalent to the code block below but shorter:
num 55 num = num + 22 print(num)
These operations are often used in for loops and while loops as seen below:
num = 55 while num < 60: print(num) num +=1
In the example above the num variable’s value increases by 1 for every iteration of the while loop because of the addition operator. The same can be done to the value of a variable for all respective arithmetic operations using Augmented Assignment Operators.
3. Comparison Operators
The “equal to” operator utilizes two “==” equal symbols, not to be confused with a single “=” equal symbol (assignment operator) to make comparisons between two or more values/objects by returning True or False if the value(s)/object(t) share equivalence or do not share equivalence, respectively.
Let us see an example:
num1 = 55 num2 = 22 print(num1 == num2)
The above example will return False since they are not equal.
Let’s see another comparison operator which is the “!=” not equal operator and it evaluate if the two values are equal or not:
num1 = 55 num2 = 22 print(num1 != num2)
The code above returns True because the two values are not equal, hence the function of the “not qual to” comparison operator.
Next are the “>” greater than and “<” less than operators:
num1 = 55 num2 = 22 print(num1 > num2)
The code above will return True and the code below will return False since the second number is less than the first number:
num1 = 55 num2 = 22 print(num1 < num2)
Not only can both the greater than “>” and less than “<” symbols be represented, but also the greater than or equal to “>=”and the less than or equal to “<=” symbols, as well.
num1 = 55 num2 = 55 print(num1 >= num2)
The code above will return True because num1 and num2 are equal, likewise the code below will return True because num1 is greater than num2. Only one condition needs to be true (condition 1: greater than or condition 2: equal to), in order for the statement to return True:
num1 = 55 num2 = 22 print(num1 <= num2)
The results of comparison operators True and False are called Boolean expressions.
4. Logical Operators
Logical operators are special words that return a Boolean expression True or False if a specific condition is met. There are three different logical operators in Python; “and”, “or”, and “not”.
Let’s explore of the “and” logical operator:
A = True B = False print(A and B)
The “and” logical operator returns True if both values are true. Thus, the above example returns False.
Let’s explore an example of the “or” operator:
A = True B = False print(A or B)
The “or” logical operator returns True if and only if one of the values being compared to one another other is true, thus the above code returns True.
The final logical operator is “not”:
A = True print(not A)
The “not” logical operator will always contradict a Boolean expression, thus the above code block example returns False since the A variable’s value is True.
5. Identity Operators
Identity Operators are used to compare two or more objects in Python. There are two, “is” and “is not“. Both identity operators return a Boolean True or False if the two separate objects being compared are the exact same object in memory.
For instance, an initialized object being saved to multiple variables:
A = True B = A C = B print(A is B is A)
In contrast to:
A = ["California"] B = ["California"] print(A is B)
Although, in the code block above, variables A and B are identical in value, they return False because they do not share the same location in memory.
The “is not” identity operator returns True, if two or more objects do not share the same location in memory:
A = ["California"] B = ["California"] print(A is not B)
6. Membership Operators
There are two Membership Operators used to validate whether or not an object belongs to a Python sequence (lists, tuples, strings, dictionaries, and sets) “in” and “not in“.
A = ["USA", "Canada", "Germany"] x = "Germany" print(x in A)
The example above will evaluate to True since the value (Germany) represented by the x variable is in the list (USA, Canada, Germany) of values represented by the A variable.
The “is not” membership operator does the opposite:
A = ["USA", "Canada", "Germany"] x = "Germany" print(x not in A)
The code block above returns False because the value represented by variable x is in list represented by variable A.
7. Bitwise Operators
Bitwise Operators perform their calculations with binary digits (machine code) also referred to as bits. There are six bitwise operators in total “&“, “|“, “~“, “^“, “>>“, and “<<” (AND, OR, Complement, XOR, Shift left, and Shift right; respectively ).
Unlike the other operators covered in this tutorial bitwise operators are mostly used in lower-level programming languages like C and Assembly to manage memory. Python forces their use for manipulating DataFrames with Pandas and other data manipulation libraries.
Most programmers and coders never use use bitwise operators because they’ve never used them, but they are important in both Computer Science and Data Science.
Our first example is the “&” or “and” bitwise operator:
A = 50 # 110010 B = 25 # 011001 C = A & B # 010000 print(C)
The binary representations of the 50 and 25 are “110010” and “011001” respectively.
The “&” operator combines two or more binary numbers; if two numbers are 1 (Yes), but if there is a 0 (No), or both numbers are zero, it will return 0.
Combining these two binary numbers with “&” give us “010000” which is 16.
Let’s see an example of the “|” (or) bitwise operator:
A = 50 # 110010 B = 25 # 011001 C = A | B # 111011 print(C)
The way the “|” operator works when comparing tow numbers is; if one of the numbers is 1, then it returns 1, but if both numbers are 0, then it returns 0, thus our example returns the value of 59.
Our third bitwise operator is the XOR operator, written with “^“.
Let’s see an example of the “^” operator in action:
A = 50 # 110010 B = 25 # 011001 C = A ^ B # 101011 print(C)
If both binary values are equal, the “^” operator will return 0, otherwise it will return 1.
Next is the Complement, also known as theNOT bitwise operator, written “~“:
A = 50 # 110010 print(~ A)
Normally, the “~” bitwise operator means turning all of the 1s (Yes/On) to 0s (No/Off) and the zeros to ones. But integers in Python are signed, and this only works on unsigned integers. Because of this we will always end up getting the negative of an integer minus 1.
Our next bitwise operator is the Shift right:
A = 50 # 110010 print(A >> 2) # 001100
The “>>” bitwise operator shifts the two left digits of the binary number to the right, returning 12 as the result.
Finally, we’ve reached our last bitwise operator, the Left shift:
A = 50 # 110010 print(A << 2) # 11001000
The “<<” bitwise operator moves two digits in the binary number from the right to the left resulting in the value 200.
Python Operators are deeply rooted in Discrete Mathematics and Discrete Structures (Computer Science) concepts.
I will cover both the Walrus Operator and Ternary Operators in separate posts.
Tanner AbrahamData Scientist and Software Engineer with a focus on experimental projects in new budding technologies that incorporate machine learning and quantum computing into web applications.
=> Join the Waitlist for Early Access.