What are Python Operators
Arithmetic, Logical, Comparison, Assignment, Bitwise & Precedence
Python operators are used for performing mathematical operations like addition, subtraction, division multiplication and many more.
There are 4 main arithmetic operators in Python.
- Addition (+)
They work the same as in maths. Let us perform some arithmetic operations.
There are three main logical operators in Python.
“And” operator compares two values and check whether both are true? If anyone of the values is false then it returns false. Let’s take a look at code.
IF we make ‘b’ or ‘a’ or both as false it will return false.
‘Or’ operator returns true if any one of the values given to it is true otherwise false.
If both are false then it will return false.
‘Not’ operator returns false if the value is true and true if the value is false.
As the name shows comparison operators are used for comparing values. Major comparison operators are listed below.
- Equal to (==)
- Not equal to (!=)
- Greater than (>)
- Less than (<)
- Greater than or equal to (>=)
- Less than or equal to (<=)
Let’s take a look at an example of ‘equal to’ and ‘not equal to’.
Another example of ‘greater than’ and ‘less than’.
Assignment operators are used for assigning some value to the variable. The most common assignment operator that we are using from the start is “=” operator. Some of the most used assignment operators are listed below.
“a += b” is the same as “a = a + b” Let’s take a look at an example.
Same for “a *= b” and “a /= b”.
When we use bitwise operators it first converts the values into binary numbers and then performs the bitwise operation on them. Listed below are some most used bitwise operations.
- And ( & )
- Or ( | )
- Not ( ~ )
- XOR ( ^ )
- Right shift ( >> )
- Left shift ( << )
Let’s perform these operations in our code.
Precedence in Python
Precedence is how the language is going to interpret the equation. For example, what will be the answer of “3 + 2 * 5”? Is it going to be 25 or 13? Let’s see in which order Python executes the equations.
Python first looks for parentheses. If there exist any parentheses then it will execute that part first. Next it looks for “**” exponents. Then further moving toward + and – etc. Given below is the list with top elements as highest precedence.
- Parentheses ()
- Exponents “**”
- Unary operators
- multiplication , division, Reminder (*,/,%)
- Addition, subtraction ( + , – )
Now let’s execute the “3 + 2 * 5” equation. The following is the output.
We can always change the precedence using parentheses.