In Python, operators are special symbols which are used to perform computations, either mathematical or logical. Operands use Operators to perform Operations. Types of operators are explained in detail on python.org and on many web resources. Here, I have compiled operators from many sources and tried to explain in a lucid manner. Letβs start.
Arithmetic operators
Arithmetic operators perform arithmetic operations between two operands. It includes + (addition), – (subtraction), *(multiplication), /(divide), %(reminder), //(floor division), and exponent (**)

Letβs discuss an important topic before moving on. Can I convert one data type to another? I mean can I convert i = 5 into a string or i = β5β into an integer or float? The answer is, YES. When we write i = 5, Python automatically understands that it is an integer. We donβt have to mention or write like int i = 5. This is termed as Dynamically Typed Language. If you are familiar with languages like C, C++ or Java, we have to write like this, int i = 5, and hence they are called Statically Typed Languages. Letβs add an integer and a string.

OOPS!! An error. Our first operation and an error occurred. What should I do? Before losing hope and deleting Python software, letβs just read the error. It says that for + sign the two operands int and str are unsupported. Think for yourself, can you add an apple with number 5? I can add 5 with 5, I can add an apple with another apple making it two apples, but I can’t add a number with a character. Here comes the Type Conversion. The process of converting one datatype to another is called Type Conversion or Type Casting. Simply by writing int or str with variable name inside brackets will convert the data type. Letβs see some examples.



I think itβs clear how and why to perform type conversion. Letβs see some examples of arithmetic operations.

We can make our output meaningful. If we write anything in quotes, it will be displayed as it is, of course, without type conversion. Letβs make the output of the above code more meaningful to read.

Comparison operator
Comparison operators compare the value of the two operands and returns Boolean true or false accordingly.

Assignment operators
The assignment operator assigns the value of the right expression to the left operand.

Bitwise operator
The bitwise operator performs bit by bit operation on the values of the two operands.

Logical Operators
The logical operators are used to make a decision by evaluating expression.

Membership Operators
Membership operators check the membership of value inside a Python data structure. If the value is present, then the resulting value is true otherwise it returns false.

Identity Operators
Identity operators determine whether the given operands have the same identityβthat is, if they refer to the same object. This operator is different from the equality operator, which means the two operands refer to objects that contain the same data but are not necessarily the same object.
Identity operators may look confusing to read though, itβs not confusing after going through the following example.

Here, a and b both refer to objects whose value is 1001. They are equal. But they do not reference the same object. Thatβs why itβs showing False for a is b. When you make an assignment like a = b, Python creates a second reference to the same object. This can be verified using the id () function. To see the output print () function is used. Also if you observe, in the first line, I have written a statement within three single quotes. In python, if we write anything within three single or double quotes, it becomes multi- line comment. For single line comment # is used. A comment is a non-executable statement which is ignored by the compiler during compilation. Comments are only written by the programmers to make themselves and others understand what the code is doing. A docstring is a multi-line string, and itβs not assigned to anything. It is specified in source code and is used to document a specific segment of code.

Letβs do one more check.

Thatβs great. One final check to get confidence.

Before moving on by simply reading the code and output and feeling OK, just compare the code with the code having a = 1001 and b = 1000 + 1. So, what happened here? Why here itβs True and there itβs False? Well, this is an interesting thing. Python feels that 1st 256 numbers are very commonly and frequently used. So till number 256, python don’t waste memory in creating another variable with same value. Both variables point to the same memory location. But after 256, the situation changes.

I think it’s clear now. Let’s have a look though. The id() is an inbuilt function in Python. It is used to return the identity of an object. This identity has to be unique and constant for this object during the lifetime. Two objects with non-overlapping lifetimes may have the same id() value. It is similar to the memory allocation in C programming.
What does this word lifetime mean?
As earlier mentioned, when an object is assigned to a variable, that object is referred to by its name. But the data itself is still contained within the object. For example, when we write a = 100, this assignment creates an integer object with the value 100 and assigns the variable a to point to that object.

When this variable is assigned to another variable, like a = b, another object is not created but instead a new variable or reference is created pointing towards the same object.

When the same object is assigned to another variable but writing like this: b = 100. Then, another reference pointing to another object is created.

But when this variable a is assigned with some another object, a = 101 then it looks like this,

There is now no reference for object 100 and no way to access it. This is technically called an Orphaned object. An object is alive, as long as there is at least one reference to it. When the reference is zero, the accessibility becomes zero. This time period is called the lifetime of any object. Python notices that it is inaccessible and reclaim that allocated memory so it can be used for something else. In computer language, this is referred to as garbage collection.
In Python, every object when created is given a number that uniquely identifies it. It has to be ensured that no two objects will have the same identifier during any period in which their lifetimes overlap. But when it fails, as you just observed, you may end up with undesired results. But itβs not your fault. Thankfully, interpreters are intelligent enough. So, if you feel that your code is correct but itβs behaving differently, like in the above example, check its identity.
Augmented Assignment Operators
A single equal sign (=) is used to assign a value to a variable. Augmented Assignment Operators are used as shorthand notation to represent arithmetic and bitwise operators.

Operator Precedence
By operator precedence it means which operator should be evaluated first. When two operators share an operand, the operator with the higher precedence will operate first. Python follows the standard precedence rule of PEMDAS (Parenthesis- Exponents- Multiplication- Division- Addition- Subtraction), with Parenthesis having the highest and Subtraction having the lowest priority.
But what if, when two operators share an operand and the operators have the same precedence? For example, how a ** b ** c should be evaluated? (a ** b) ** c or a ** (b ** c)?


This is called Operatorβs Associativity. The order of evaluation is usually from left to right in function arguments. Assignment and Comparison operators are non- associative.
Python also uses short circuiting when it evaluates expressions involving the and or or operators. When these operators are involved, Python does not evaluate the second operand unless it is necessary to resolve the result.
Sometimes, operatorβs precedence doesnβt follow the standard mathematical norms. In mathematics, -1^2 will evaluate the result as 1. It is evaluated as (-1)^2, and not as -(1^2). This rule agrees with mathematical conventions for all C operators (where unary operators have higher priority than binary operators), but fails with the addition of the exponentiation operator. Geeks term it has βDesign Choiceβ. Nothing to worry about!! Practice makes Programmers perfect.
Escape Sequences in Python
In Python strings, the backslash \ is a special character, also called the escape character. It is used in representing certain whitespace characters: \t is a tab, \n is a newline, and \r is a carriage return. Conversely, prefixing a special character with \ turns it into an ordinary character.
When an βrβ or βRβ prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string. We will use these in strings later, but here, we will have some overview of how they work. The valid escape characters in Python are,

Letβs see how to use these escape sequences.

\n means new line. So, itβll break the string into new lines. Anything written after \n will appear in new lines. Another escape character which is widely used is \t. It will generate a tab space between words when used.

You can express any character by its numerical ASCII code by writing a backslash character \ followed by the ASCII code expressed as an octal (base-8) or hexadecimal (base-16) number. In octal the digits must immediately follow the backslash, in hexadecimal, an x character must be written before the digits themselves.
Letβs print ABC in octal.

Now in hexadecimal,

Likewise, you can use these escape characters when needed.
That’s all for operators in python up to version 3.7. In the next section we’ll see the new operator introduced in version 3.8.
We will practice to use these these operators in codes straightaway later. For the time being, understanding them through the tables is sufficient.
(I am very lazy in making tables. The above tables used in operators have been taken from brainkart.com and the table of escape sequence is from stackoverflow)
