In Python, operators are symbols that tell the program to perform specific operations on values or variables. They help you add numbers, compare values, or manipulate data. There are different types of operators, like those for math, comparing things, working with bits, and even creating custom actions. In this guide, we'll break down these operators into simple explanations so you can easily understand how they work.

Python Arithmetic Operators

Arithmetic operators provide a set of operators to perform basic mathematical operations:

  1. Addition (+): This operator adds two values together.
  2. Subtraction (-): Subtracts one value from another.
  3. Multiplication (*): Multiplies two values.
  4. Division (/): Divides one value by another, resulting in a floating-point number.
  5. Floor Division (//): Divides two values and returns the largest integer less than or equal to the result.
  6. Exponentiation (**): Raises one value to the power of another.
  7. Modulus (%): Returns the remainder after dividing one value by another.

Example

x = 5
y = 4

print('x + y =', x + y)   # Addition
print('x - y =', x - y)   # Subtraction
print('x * y =', x * y)   # Multiplication
print('x / y =', x / y)   # Division
print('x // y =', x // y) # Floor Division
print('x ** y =', x ** y) # Exponent

Output

Python Arithmetic Operators Output

Python Comparison Operators

Comparison operators help compare values and return either True or False. These operators include:

Comparison operators are vital for controlling program flow, particularly in decision-making scenarios like if statements and loops.

Example

x = 101
y = 121

print('x > y is', x > y)   # Greater than
print('x < y is', x < y)   # Less than
print('x == y is', x == y) # Equal to
print('x != y is', x != y) # Not Equal to
print('x >= y is', x >= y) # Greater than or equal to
print('x <= y is', x <= y) # Less than or equal to

Output

Python Comparison Operators

Python Logical Operators

Python logical operators are used to perform logical operations on boolean values, returning either True or False. They are primarily used in conditional statements to combine or negate conditions.

Logical operators are used to create complex conditions, enabling more flexible and sophisticated decision-making in programs.

Example

x = True
y = False

print('x and y is', x and y)  # True if both x and y are true
print('x or y is', x or y)    # True if either x or y is true
print('not x is', not x)      # Negates x

Output

Python Logical Operators

Python Bitwise Operators

Bitwise operators in Python work at the bit level, meaning they perform operations on the binary representation of numbers. These operators manipulate individual bits of data, which can be useful for low-level programming tasks like handling binary data or optimizing performance.

Bitwise operators are often used in scenarios where performance and memory efficiency are critical, such as in systems programming, cryptography, or data compression.

Example

a = 6   # Binary: 110
b = 3   # Binary: 011

print("a & b =", a & b)    # AND
print("a | b =", a | b)    # OR
print("a ^ b =", a ^ b)    # XOR
print("~a =", ~a)          # Complement
print("a << 2 =", a << 2)  # Left Shift
print("a >> 2 =", a >> 2)  # Right Shift

Output

Python Bitwise Operators

Python Membership Operators

Membership operators in Python are used to check if a value is part of a sequence, such as a list, tuple, string, or set. These operators help determine whether a particular item exists within a collection.

Membership operators are commonly used in conditions or loops to verify the presence or absence of elements in data structures like lists, strings, or dictionaries. For example, you might check if a user’s input exists in a predefined list of valid options.

Example

a = 5
b = 10
lst = [1, 2, 3, 4, 5]

if a in lst:
    print("a is in the list")
if b not in lst:
    print("b is not in the list")

Output

Python Membership Operators

Python Identity Operators

Identity operators in Python are used to compare the memory locations of two objects. They check whether two variables refer to the same object in memory, rather than just having equal values.

Identity operators are helpful when you need to check if two variables reference the same object, particularly when dealing with mutable objects like lists or dictionaries. For instance, in cases where you want to avoid unintentional modifications to a shared object.

Example

a = 10
b = 10

if a is b:
    print("a and b have the same identity")

Output

Python Identity Operators

Operator overloading in Python allows you to change how operators like +, -, and * work with your custom objects. Normally, these operators work with basic data types like numbers, but with operator overloading, you can define what they do when applied to your objects.

Example 1

class A:
    def __init__(self, a):
        self.a = a

    def __add__(self, other):
        return self.a + other.a

ob1 = A(1)
ob2 = A(2)

print(ob1 + ob2)  

# Output: 3

Example 2

class A:
    def __init__(self, a):
        self.a = a

    def __gt__(self, other):
        return self.a > other.a

ob1 = A(2)
ob2 = A(3)

if ob1 > ob2:
    print("ob1 is greater than ob2")
else:
    print("ob2 is greater than ob1")

Output

Python Operator Overloading Example 2 Output

Conclusion

To write effective Python code, it's important to understand different operators, like those for math, logic, bitwise operations, checking membership, and comparing identity. Python also lets you extend these operators to work with custom objects, making the language more powerful. Whether you're doing calculations or comparing items, operators are a key part of Python that you'll use often.