I'm a software developer with a great interest in data analysis and statistics.
Python supports the following types of operators:
- Arithmetic operators
- Comparison operators
- Assignment operators
- Logical operators
- Bitwise operators
- Membership operators
- Identity operators
Let us learn about each of these operators in detail.
Arithmetic Operators in Python
Almost all operators which are supported in languages like C/C++ or Java are supported in Python. The operators +, -, / , * and % represent addition, subtraction, division, multiplication and modulus respectively. In addition to these, ** performs exponential calculation and // performs floor division. For the sake of the article’s brevity, we will focus more on operators unique to Python.
The following code demonstrates the use of floor operation. In floor division, if the numerator is a positive number, the result is rounded towards zero. If the numerator is negative, the result is rounded away from zero.
Python Comparison Operators
Almost all comparison operators supported by languages like C/C++ or Java are supported by Python. The operators ==, !=. >,<, >= and <= denote equal to, not equal to, greater than, less than, greater than or equal to, and less than or equal to respectively.
Assignment Operators in Python
Equals symbol (=) is used by Python to assign a value on the right-hand side of expression to the variable on the left-hand side. Like other languages like C++ and Java, Python supports Operator-And operations where the result of the operation is assigned to the left.
Like += operation, all other arithmetic operators available in Python can be clubbed with equals symbol to formulate respective Operator-And operators.
AND, OR and NOT are the three basic logical operators supported by Python.
Python supports AND(&), OR(|), XOR(^), One’s compliment or flipping of bits(~), left shift (<<) and right shift(>>) operators. There is a built-in function called bin() which gives the given integer in binary representation. To demonstrate the bitwise operations, we use this while printing the output in the sample code:
Output of the above code will be:
a= 54 : 0b110110 b= 8 : 0b1000 result of AND is 0 : 0b0 result of OR is 62 : 0b111110 result of EXOR is 62 : 0b111110 result of COMPLEMENT is -55 : -0b110111 result of LEFT SHIFT is 216 : 0b11011000 result of RIGHT SHIFT is 13 : 0b1101
In and not in are the two membership operators. These are used to find out if a given value on LHS is present in the construct of RHS.
Output for the above program will be:
Hello is NOT present in firstTuple Welcome is present in firstTuple
Is and is not are the identity operators in Python. These are used to verify if variables on LHS and RHS point to the same object in memory or not.
Output of the above program will be:
1397774624 1397774624 1397774736 var1 and var2 have same location var3 and var2 have different locations
© 2019 Sam Shepards