This tutorial provides an in-depth overview of Python operators. There are various kinds of operators in Python including Arithmetic, Comparison, Assignment, Logical, Bitwise, Identity, and Membership operators. Here, you’ll learn their syntax and practice with numerous examples. You must clearly understand their meaning in Python in order to write better programs. Let’s explore what are they, what purpose they cater to, and how to use them.
What is an operator in Python?
Python operator is a symbol represented by a special character, gets the input from one or more operands, and performs a specific task.
Like many programming languages, Python reserves some special characters for acting as operators. Every operator carries out some operations such as addition, and multiplication to manipulate data and variables. The variables passed as input to an operator are known as operands.
>>> 7%4 3
In the above case, ‘%’ is the modulus operator that calculates the remainder of the division. The numbers ‘7’ and ‘4’ passed as input are the operands, whereas the number ‘3’ is the result of the action performed. We also recommend you read about keywords in Python.
Arithmetic operators
With arithmetic operators, we can do various arithmetic operations like addition, subtraction, multiplication, division, modulus, exponent, etc. Python provides multiple ways for arithmetic calculations like eval function, declare variable & calculate, or call functions. The table below outlines the built-in arithmetic operators in Python.
Operator | Usage | Purpose |
---|---|---|
+ | a + b | Addition – Sum of two operands |
– | a – b | Subtraction – Difference between the two operands |
* | a * b | Multiplication – Product of the two operands |
/ | a / b | Float Division – Quotient of the two operands |
// | a // b | Floor Division – Quotient of the two operands (Without fractional part) |
% | a % b | Modulus – Integer remainder after division of ‘a’ by ‘b.’ Note: It is also known as the percent operator. |
** | a ** b | Exponent – Product of ‘a’ by itself ‘b’ times (a to the power of b) Note: It is also known as the exponentiation operator. |
Example-
a=7 b=4 print('Sum : ', a+b) print('Subtraction : ', a-b) print('Multiplication : ', a*b) print('Division (float) : ', a/b) print('Division (floor) : ', a//b) print('Modulus : ', a%b) print('Exponent : ', a**b)
Output-
Sum : 11 Subtraction : 3 Multiplication : 28 Division (float) : 1.75 Division (floor) : 1 Modulus : 3 Exponent : 2401
Arithmetic operator’s FAQs
The modulus operation is the meaning of the % sign in Python. It takes two operands and returns the remainder of the two.
The %= operator is an augmented form of the modulo or modulus operator. It first performs the modulus operation and then assigns the output to the left operand or the variable.
Comparison operators
In Python programming, comparison operators allow us to determine whether two values are equal or if one is higher than the other and then make a decision based on the result. The table below outlines the built-in comparison operators in Python.
Operator | Usage | Purpose |
---|---|---|
> | a > b | Greater than – if the left operand is greater, then it returns true. |
< | a < b | Less than – if the left operand is less, then it returns true. |
== | a == b | Equal to – if two operands are equal, then it returns true. |
!= | a != b | Not equal to – if two operands are not equal, then it returns true. |
>= | a >= b | Greater than or equal – True if the left operand is greater or equal. |
<= | a <= b | Less than or equal – True if the left operand is less than or equal. |
Example-
a=7 b=4 print('a > b is',a>b) print('a < b is',a<b) print('a == b is',a==b) print('a != b is',a!=b) print('a >= b is',a>=b) print('a <= b is',a<=b)
Output-
a > b is True a < b is False a == b is False a != b is True a >= b is True a <= b is False
Some FAQs on comparison operators
The != operator in Python means to compare two values that should not match. It checks for the inequality of two variables. It returns True if the values don’t match and False otherwise.
The meaning of the “=” symbol in Python is assigning some value to a variable. Whereas, the “==” symbol means to match two values for equality.
Logical operators
Logical Python operators enable us to make decisions based on multiple conditions. The operands act as conditions that can result in a true or false value. The outcome of such an operation is either true or false (i.e., a Boolean value).
However, not all of these operators return a boolean result. The ‘and’ and ‘or’ operators do return one of their operands instead of a pure boolean value. Whereas the ‘not’ operator always gives a real boolean outcome. Check the table and the example to know how these operators work in Python.
Operator | Usage | Purpose |
---|---|---|
and | a and b | if ‘a’ is false, then ‘a’, else ‘b’ |
or | a or b | if ‘a’ is false, then ‘b’, else ‘a’ |
not | not a | if ‘a’ is false, then True, else False |
Example-
a=7 b=4 # Result: a and b is 4 print('a and b is',a and b) # Result: a or b is 7 print('a or b is',a or b) # Result: not a is False print('not a is',not a)
Output-
a and b is 4 a or b is 7 not a is False
Bitwise operators
Bitwise Python operators process the individual bits of integer values. They treat them as sequences of binary bits.
We can use bitwise operators to check whether a particular bit is set. For example, IoT applications read data from the sensors based on whether a specific bit is set or not. In such a situation, these operators can help.
Operator | Usage | Purpose |
---|---|---|
& | a & b | Bitwise AND – compares two operands on a bit level. It returns 1 if both the corresponding bits are 1 |
| | a | b | Bitwise OR – compares two operands on a bit level. It returns 1 if any of the corresponding bits is 1 |
~ | ~a | Bitwise NOT – inverts all of the bits in a single operand. |
^ | a ^ b | Bitwise XOR – compares two operands on a bit level. It returns 1 if any of the corresponding bits is 1, but not both |
>> | a >> b | Right shift – shifts the bits of ‘a’ to the right by ‘b’ no. of times. |
<< | a << b | Left shift – shifts the bits of ‘a’ to the left by ‘b’ no. of times. |
Out of the above bitwise operators, Python xor has various applications such as swapping two numbers, in cryptography to generate checksum and hash.
Example-
Let’s consider the numbers 4 and 6 whose binary representations are ‘00000100’ and ‘00000110’. Now, we’ll perform the AND operation on these numbers.
a=4 b=6 #Bitwise AND: The result of 'a & b' is 4 print('a & b is',a & b)
Output-
a & b is 4
The above result is the outcome of the following AND (‘&’) operation.
0 0 0 0 0 1 0 0 & 0 0 0 0 0 1 1 0 ------------------ 0 0 0 0 0 1 0 0 (the binary representation of the number 4)
Some FAQs on bitwise operators
The << is one of the bitwise operators in Python that shifts the specified number of bytes to the left. It is useful in optimizing calculations such as quickly multiplying a number by a power of 2.
In Python, the >> symbol means to move the bits from left to right. It is a special operator that not only extracts bits from a binary number but also has a use in basic encoding and decoding operations. For example, you can use it to encode an ASCII character into a binary number and then << to reverse the same.
Assignment operators
In Python, we can use assignment operators to set values into variables. The instruction a = 4 uses a primitive assignment operator that assigns the value 4 to the left operand.
Below is the list of available compound operators in Python. For example, the statement a += 4 adds to the variable and then assigns the same. It will evaluate to a = a + 4.
Operator | Example | Similar to |
---|---|---|
= | a = 4 | a = 4 |
+= | a += 4 | a = a + 4 |
-= | a -= 4 | a = a – 4 |
*= | a *= 4 | a = a * 4 |
/= | a /= 4 | a = a / 4 |
%= | a %= 4 | a = a % 4 |
**= | a **= 4 | a = a ** 4 |
&= | a &= 4 | a = a & 4 |
|= | a |= 4 | a = a | 4 |
^= | a ^= 4 | a = a ^ 4 |
>>= | a >>= 4 | a = a >> 4 |
<<= | a <<= 4 | a = a << 4 |
Assignment operator FAQ
The a &= b is a Python expression that uses two operands a and b joined by the &= operator. The meaning of such a statement is doing a bitwise AND operation between the corresponding bits of the two operands,i.e., a and b.
Advanced Python operators
Python also bundles a few operators for special purposes. These are known as advanced Python operators like the identity operator or the membership operator.
Identity operators
These operators enable us to compare the memory locations of two Python objects/variables. They can let us find if the objects share the same memory address. The variables holding equal values are not necessarily identical.
Alternatively, we can use these operators to determine whether a value is of a specific class or type. Refer to the below table to understand more about them.
Operator | Purpose | Usage |
---|---|---|
is | True – if both the operands refer to the same object, else returns False | a is b (True if id(a) and id(b) are the same) |
is not | True – if the operands refer to different objects, False otherwise | a is not b (True if id(a) and id(b) are different) |
Example-
# Using 'is' identity operator a = 7 if (type(a) is int): print("true") else: print("false") # Using 'is not' identity operator b = 7.5 if (type(b) is not int): print("true") else: print("false")
Output-
true true
Membership operators
Membership operators enable us to test whether a value is a member of other Python objects such as strings, lists, or tuples.
In C, a membership test requires iterating through a sequence and checking each value. But Python makes it very easy to establish membership as compared to C.
Also, note that this operator can also test against a Python dictionary but only for the key, not the value.
Operator | Purpose | Usage |
---|---|---|
in | True – if the value exists in the sequence | 7 in [3, 7, 9] |
not in | True – if the value doesn’t found in the sequence | 7 not in [3, 5, 9] |
Example-
# Using Membership operator str = 'Python operators' dict = {6:'June',12:'Dec'} print('P' in str) print('Python' in str) print('python' not in str) print(6 in dict) print('Dec' in dict)
Output-
True True True True False
Conclusion – Python operators
This tutorial covered various Python operators, and their syntax, and described their operation with examples. Hence, it should now be easier for you to use operators in Python.
If you find something new to learn today, then do share it with others. And, follow us on our social media accounts to get notified of more such tutorials.
Best,
TechBeamers