Python — Operators
Python Operators
Operators are used to perform operations on variables and values.
Here, in the example below, we use the + operator to add (sum) together two values:
print(2 + 3) # 5Python divides the operators in the following groups:
- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical operators
- Identity operators
- Membership operators
- Bitwise operators
Python Comparison Operators
Comparison operators are used to compare two values:
Python Logical Operators
Logical operators are used to combine conditional statements:
Python Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:
Python Membership Operators
Membership operators are used to test if a sequence is presented in an object:
Python Bitwise Operators
Bitwise operators are used to compare (binary) numbers:
Operator Precedence
Operator precedence describes the order in which operations are performed.
Get Sithila Sihan Somaratne’s stories in your inbox
Join Medium for free to get updates from this writer.
PEMDAS is the operator precedence rule in Python, helping us remember the order of operations to be performed. The PEMDAS rule stands for Parentheses, Exponents, Multiplication, Division, Addition, and Subtraction.
Here’s an example to demonstrate this rule:
operation = (8 * 4 + 7 - 6 / 2)**3 - (3 ** 2 + 2 * 5)
print(operation) # 46637.0As you can see, this operation gives us as output 46337. To know why, let’s break this down using the PEMDAS rule.
Parentheses
First, we solve the operations inside the parentheses: (8 * 4 + 7 - 6 / 2) and (3² + 2 * 5).
For the first parentheses:
1. Multiplication and Division first: 8 * 4 = 32 and 6 / 2= 3.
2. Then Addition and Subtraction: 32 + 7 - 3 = 36.
For the second parentheses:
1. Exponents first: 3² = 9.
2. Then Multiplication: 2 * 5 = 10.
3. Then Addition: 9 + 10 = 19.
Exponents
Now we apply exponents outside the parentheses: 36³ = 46656.
Subtraction
Finally, subtract the results of the parentheses: 46656–19 = 46637.
Therefore, the final result is 46637.0 (Python gives us this result with a decimal point because of the division).
Boy! This blog has become an Algebric lesson, rather than a Python lesson!
The precedence order is described in the table below, starting with the highest precedence at the top:
If two operators have the same precedence, the expression is evaluated from left to right.




