Introduction to Python Operators

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:

  • Greater Than (>): Checks if the value on the left is greater than the value on the right.
  • Less Than (<): Check if the value on the left is less than the value on the right.
  • Equal To (==): Checks if both values are equal.
  • Not Equal To (!=): Checks if both values are not equal.
  • Greater Than or Equal To (>=): Check if the value on the left is greater than or equal to the value on the right.
  • Less Than or Equal To (<=): Check if the value on the left is less than or equal to the value on the right.

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.

  • and: Returns True if both operands are True; otherwise, it returns False.
  • or: Returns True if at least one of the operands is True; returns False only if both are False.
  • not: Negates the boolean value; if the value is True, it returns False, and vice versa.

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.

  • & (AND): Compares each bit of two numbers. If both bits are 1, the result is 1. Otherwise, it's 0.
  • | (OR): Compares each bit of two numbers. If at least one bit is 1, the result is 1. If both are 0, the result is 0.
  • ^ (XOR): Compares each bit of two numbers. If the bits are different, the result is 1. If they are the same, the result is 0.
  • ~ (NOT): Flips all the bits of a number, turning 1s into 0s and 0s into 1s.
  • << (Left Shift): Shifts the bits of a number to the left by a specified number of positions, effectively multiplying the number by powers of two.
  • >> (Right Shift): Shifts the bits of a number to the right by a specified number of positions, effectively dividing the number by powers of two.

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.

  • in: This operator checks if a value exists in a sequence. If the value is found, it returns True; otherwise, it returns False.
  • not in: This operator checks if a value does not exist in a sequence. If the value is not found, it returns True; otherwise, it returns False.

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.

  • is: This operator returns True if two variables point to the same object in memory, meaning they are identical.
  • is not: This operator returns True if two variables do not point to the same object in memory, meaning they are not identical.

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.

  • Customizing Operators: You can change how operators like +, -, and == behave when used with your objects by defining special methods in your class.
  • Make Objects Behave Like Built-in Types: This allows your objects to interact with operators in a way that feels natural, just like numbers or strings do.
  • Simplifies Complex Data Structures: It is helpful for creating more intuitive code when working with complex objects like matrices, vectors, or custom data types.

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.


Similar Articles