Python Operators
One of the fundamental concepts in Python, and indeed in any programming language, are operators. In Python, operators are special symbols that carry out arithmetic or logical computation. The value that the operator operates on is called the operand.
Operators are the building blocks of any programming language, allowing us to perform operations on our data. In Python, these operators are diverse and flexible, enabling us to write code that’s efficient and easy to understand.
Table of Contents
What are Python Operators?
Python operators are special symbols that carry out arithmetic or logical computation. They’re the heart of our Python expressions, allowing us to manipulate our data in a variety of ways. The value that the operator operates on is called the operand.
Types of Python Operators
Python has seven types of operators:
- Arithmetic Operators
- Comparison (Relational) Operators
- Assignment Operators
- Logical Operators
- Bitwise Operators
- Identity Operators
- Membership Operators
Let’s dive into each of these operator classes and see how Python uses them to perform operations.
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc. Here are the arithmetic operators in Python:
- Addition (+): Adds values on either side of the operator. For example,
a + b
will give us the sum ofa
andb
. - Subtraction (-): Subtracts right-hand operand from left-hand operand. For example,
a - b
will give us the result ofa
minusb
. - Multiplication (*): Multiplies values on either side of the operator. For example,
a * b
will give us the product ofa
andb
. - Division (/): Divides left-hand operand by right-hand operand. For example,
a / b
will give us the result ofa
divided byb
. - Floor Division (//): The division of operands where the result is the quotient in which the digits after the decimal point are removed. For example,
9 // 2
will give us4
. - Modulus (%): Divides left-hand operand by right-hand operand and returns the remainder. For example,
10 % 3
will give us1
, because that’s the remainder when10
is divided by3
. - Exponent (**): Performs exponential (power) calculation on operators. For example,
2 ** 3
will give us8
, because that’s2
to the power of3
.
# Examples of Arithmetic Operators
a = 10
b = 7
print('a + b =',a+b) # Addition
print('a - b =',a-b) # Subtraction
print('a * b =',a*b) # Multiplication
print('a / b =',a/b) # Division
print('a % b =',a%b) # Modulus
print('a ** b =',a**b) # Exponentiation
print('a // b =',a//b) # Floor Division
PythonComparison Operators
Comparison operators are used to compare values. It either returns True or False according to the condition.
- Equal (==): If the values of two operands are equal, then the condition becomes true. For example,
a == b
returns True ifa
is equal tob
. - Not Equal (!=): If values of two operands are not equal, then condition becomes true. For example,
a != b
returns True ifa
is not equal tob
. - Greater Than (>): If the value of the left operand is greater than the value of the right operand, then the condition becomes true. For example,
a > b
returns True ifa
is greater thanb
. - Less Than (<): If the value of the left operand is less than the value of the right operand, then the condition becomes true. For example,
a < b
returns True ifa
is less thanb
. - Greater Than or Equal To (>=): If the value of the left operand is greater than or equal to the value of the right operand, then the condition becomes true. For example,
a >= b
returns True ifa
is greater than or equal tob
. - Less Than or Equal To (<=): If the value of the left operand is less than or equal to the value of the right operand, then the condition becomes true. For example,
a <= b
returns True ifa
is less than or equal tob
.
# Examples of Comparison Operators
a = 10
b = 7
print('a > b is',a>b) # Greater than
print('a < b is',a<b) # Less than
print('a == b is',a==b) # Equal to
print('a != b is',a!=b) # Not equal to
print('a >= b is',a>=b) # Greater than or equal to
print('a <= b is',a<=b) # Less than or equal to
PythonAssignment OperatorsAssignment operators are used in Python to assign values to variables.
- Assign (=): Assigns values from right side operands to left side operand. For example,
a = b
assigns the value ofb
toa
. - Add AND (+=): It adds right operand to the left operand and assign the result to left operand. For example,
a += b
is equivalent toa = a + b
. - Subtract AND (-=): It subtracts right operand from the left operand and assign the result to left operand. For example,
a -= b
is equivalent toa = a - b
. - Multiply AND (*=): It multiplies right operand with the left operand and assign the result to left operand. For example,
a *= b
is equivalent toa = a * b
. - Divide AND (/=): It divides left operand with the right operand and assign the result to left operand. For example,
a /= b
is equivalent toa = a / b
. - Modulus AND (%=): Takes modulus using two operands and assign the result to left operand. For example,
a %= b
is equivalent toa = a % b
. - Exponent AND (**=): Performs exponential (power) computation on operators and assign value to the left operand. For example,
a **= b
is equivalent toa = a ** b
. - Floor Division (//=): It performs floor division on operators and assign value to the left operand. For example,
a //= b
is equivalent toa = a // b
.
# Examples of Logical Operators
a = True
b = False
print('a and b is',a and b) # and
print('a or b is',a or b) # or
print('not a is',not a) # not
PythonLogical Operators
Logical operators in Python are used for conditional statements are true or false. Logical operators in Python: AND, OR, and NOT.
- AND: If both the operands are true then condition becomes true. For example,
a and b
returnsa
ifa
is False, else it returnsb
. - OR: If any of the two operands are non-zero then condition becomes true. For example,
a or b
returnsa
ifa
is True, else it returnsb
. - NOT: Used to reverse the logical state of its operand. For example,
not a
returns False ifa
is True, else it returns True.
# Examples of Logical Operators
a = True
b = False
print('a and b is',a and b) # and
print('a or b is',a or b) # or
print('not a is',not a) # not
PythonBitwise Operators
Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit.
- AND (&): Operator copies a bit to the result if it exists in both operands. For example,
(a & b)
gives you the bits that are turned on in botha
andb
. - OR (|): It copies a bit if it exists in either operand. For example,
(a | b)
gives you the bits that are turned on ina
orb
or both. - XOR (^): It copies the bit if it is set in one operand but not both. For example,
(a ^ b)
gives you the bits that are turned on ina
orb
but not both. - NOT (~): It is unary and has the effect of ‘flipping’ bits. For example,
(~a )
gives you the complement ofa
. - Left shift (<<): The left operands value is moved left by the number of bits specified by the right operand. For example,
a << 2
givesa
shifted left by 2 bits. - Right shift (>>): The left operands value is moved right by the number of bits specified by the right operand. For example,
a >> 2
givesa
shifted right by 2 bits.
# Examples of Bitwise Operators
a = 10 # binary: 1010
b = 4 # binary: 0100
print('a & b =',a & b) # Bitwise AND
print('a | b =',a | b) # Bitwise OR
print('a ^ b =',a ^ b) # Bitwise XOR
print('~a =',~a) # Bitwise NOT
print('a << 1 =',a << 1) # Bitwise left shift
print('a >> 1 =',a >> 1) # Bitwise right shift
PythonIdentity Operators
Identity operators are used to compare the memory locations oftwo objects. Identity operators in Python: is and is not.
- is: Returns true if both variables are the same object. For example,
x is y
, hereis
results in1
ifid(x)
equalsid(y)
. - is not: Returns true if both variables are not the same object. For example,
x is not y
, hereis not
results in1
ifid(x)
is not equal toid(y)
.
# Examples of Identity Operators
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
print('list1 is list2:', list1 is list2) # False because list1 and list2 are not the same object
print('list1 is not list2:', list1 is not list2) # True
print('list1 is list3:', list1 is list3) # True because list1 and list3 are the same object
PythonMembership Operators
Membership operators are used to test whether a value or variable is found in a sequence (string, list, tuple, set, and dictionary).
- in: Evaluates to true if it finds a variable in the specified sequence and false otherwise. For example,
x in y
, herein
results in a1
ifx
is a member of sequencey
. - not in: Evaluates to true if it does not find a variable in the specified sequence and false otherwise. For example,
x not in y
, herenot in
results in a1
ifx
is not a member of sequencey
.
# Examples of Membership Operators
list4 = ['apple', 'banana', 'cherry']
print("'apple' in list4:", 'apple' in list4) # True because 'apple' is in list4
print("'grape' not in list4:", 'grape' not in list4) # True because 'grape' is not in list4
PythonWrapping Up
Understanding Python operators is crucial for programming in Python. They form the foundation upon which we build our data structures and write our algorithms. So, keep practicing and experimenting with different operators. Remember, practice makes perfect!
Frequently Asked Questions (FAQ)
-
What are Python operators?
Python operators are special symbols that carry out arithmetic or logical computation. The value that the operator operates on is called the operand.
-
What are the different types of operators in Python?
Python has seven types of operators: Arithmetic Operators, Comparison (Relational) Operators, Assignment Operators, Logical Operators, Bitwise Operators, Identity Operators, and Membership Operators.
-
What are Arithmetic Operators in Python?
Arithmetic operators are used to perform mathematical operations like addition (+), subtraction (-), multiplication (*), division (/), modulus (%), exponent (**), and floor division (//).
-
What are Comparison Operators in Python?
Comparison operators are used to compare values. It either returns True or False according to the condition. These include equal (==), not equal (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=).
-
What are Assignment Operators in Python?
Assignment operators are used in Python to assign values to variables. This includes assign (=), add and assign (+=), subtract and assign (-=), multiply and assign (*=), divide and assign (/=), modulus and assign (%=), exponent and assign (**=), and floor division and assign (//=).
-
What are Logical Operators in Python?
Logical operators in Python are used for conditional statements are true or false. Logical operators in Python: AND, OR, and NOT.
-
What are Bitwise Operators in Python?
Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence the name.
-
What are Identity Operators in Python?
Identity operators are used to compare the memory locations of two objects. Identity operators in Python: is and is not.
-
What are Membership Operators in Python?
Membership operators are used to test whether a value or variable is found in a sequence (string, list, tuple, set, and dictionary). Membership operators in Python: in and not in.
-
Can you give some examples of using Python operators?
Yes, you can find examples of using Python operators in the main content of this article.