In this Article, we’ll go through the various types of Operators in Python and their uses.
Arithmetic operators are used with numerical values to perform different mathematical operations. Listed below are Python Arithmetic Operators with examples.
|Addition||+||Sum of two numbers.|
|Subtraction||–||Difference of two numbers.|
|Multiplication||*||Product of two numbers.|
|Division||/||Division of two numbers.|
|Modulus||%||Remainder of the division of two numbers.|
|Exponent||**||Exponential of a number.|
>>> 5 + 3 8 >>> 5 - 3 2 >>> 5 * 3 15 >>> 5 / 2 2.5 >>> 5 ** 3 125
Assignment Operators are used assign new values to variables. Many Assignment Operators are in fact, short cuts for certain Arithmetic Operations.
Comparison Operators compare the contents of a variable to another. If the Comparison held true, then the Boolean value “True” is returned. However if the comparison was false, then the Boolean value “False” is returned.
- Equals to:
- Not Equal to:
- Greater than:
- Greater than or equals to:
- Less than:
- Less than or equals to:
x = 5 y = 3
if x == y: print("X is equal to Y")
if x != y: print("X is not equal to Y")
if x > y: print("X is greater than Y")
if x < y: print("X is less than Y")
if x >= y: print("X is greater or equal to Y")
if x <= y: print("X is less than or equal to Y")
Used to conduct Logical Operations between conditional statements, linking several conditions together to form a more complex condition.
|and||Returns True if both of the two statements was True.|
|or||Returns True if one of the two statements was True.|
|not||Inverses the result.|
if 5 > 2 and 3 > 2: print("5 and 3 are larger than 2")
x = 5 y = 3 if x > 3 and y > 3: print("Either x or y is greater than 3")
x = False print(x) #Value of x is now False x = not(x) print(x) #Value of x is now True
Python bit-wise operators can only be used between Binary numbers, like 01000101. These operators are performed on two Binary numbers.
|&||If both bits are 1, sets the bit to 1|
||||If either bit is 1, sets the bit to 1.|
|^||If only one of the two bits is 1, sets the bit to 1.|
|~||Inverts the bit. (0 to 1 and vice versa)|
Due to their close relationship, you should also read through the Python Data types article.
This marks the end of the Python Operators Article. Any suggestions or contributions for CodersLegacy are more than welcome. Any questions can be asked in the comments below.