🐍 Operators.exe

Santwan PathakSantwan Pathak
10 min read

Operators in Python are symbols that perform operations on variables and values. Whether it’s simple math, comparing two values, or combining conditions — Python operators are everywhere.

Let’s explore all types of operators one by one:


🔹 1. Arithmetic Operators

Used to perform mathematical operations.

OperatorDescriptionExampleResult
+Addition5 + 38
-Subtraction10 - 28
*Multiplication4 * 28
/Division16 / 28.0 ( always return a float type)
//Floor Division17 // 28 (always return a int type)
%Modulus (Remainder)17 % 21
**Exponentiation2 ** 38

🧪 Code Examples of Arithmetic Operators

Here are extended examples demonstrating each arithmetic operator in Python, designed to help solidify your understanding through hands-on practice.

# Demonstrating addition with integers and floats
x = 5 + 3
print("Addition (5 + 3):", x)

x_float = 5.5 + 2.5
print("Addition with floats (5.5 + 2.5):", x_float)

# Demonstrating subtraction with positive and negative numbers
y = 10 - 2
print("Subtraction (10 - 2):", y)

neg_sub = -10 - 5
print("Subtraction with negatives (-10 - 5):", neg_sub)

# Demonstrating multiplication with integers and zero
z = 4 * 2
print("Multiplication (4 * 2):", z)

zero_mult = 4 * 0
print("Multiplication with zero (4 * 0):", zero_mult)

# Demonstrating division and float result
a = 16 / 2
print("Division (16 / 2):", a)

# Demonstrating floor division with different outcomes
b = 17 // 2
print("Floor Division (17 // 2):", b)

b_neg = -17 // 2
print("Floor Division with negative (-17 // 2):", b_neg)

# Demonstrating modulus operation with positive and negative numbers
c = 17 % 2
print("Modulus (17 % 2):", c)

c_neg = -17 % 2
print("Modulus with negative (-17 % 2):", c_neg)

# Demonstrating exponentiation with positive and fractional exponents
d = 2 ** 3
print("Exponentiation (2 ** 3):", d)

d_fractional = 9 ** 0.5
print("Exponentiation with fractional (9 ** 0.5):", d_fractional)

When working with arithmetic operators in Python, here are a few things to be careful about:

  1. Data Types: Ensure that the operands you are using with arithmetic operators are of compatible data types. Trying to perform arithmetic operations on incompatible types (like adding an integer and a string) will result in a TypeError.

    •         a = 10 + "45"
      
              ---------------------------------------------------------------------------
              TypeError                                 Traceback (most recent call last)
              /tmp/ipython-input-2-3905256980.py in <cell line: 0>()
              ----> 1 a = 10 + "45"
      
              TypeError: unsupported operand type(s) for +: 'int' and 'str'
              ---------------------------------------------------------------------------
      

      same will happen for the a = “45” + 10

  2. Division by Zero:

    • Division by zero is undefined and will cause a ZeroDivisionError. Always make sure the denominator is not zero when performing division.

    •         a = 10
              b = 10/0
              ---------------------------------------------------------------------------
              ZeroDivisionError                         Traceback (most recent call last)
              /tmp/ipython-input-3-2840989168.py in <cell line: 0>()
                    1 a = 10
              ----> 2 b = 10/0
      
              ZeroDivisionError: division by zero
              ---------------------------------------------------------------------------
      
  3. Integer vs. Float Division:

    • Remember the difference between standard division (/) which always returns a float, and floor division (//) which performs division and discards the fractional part, resulting in an integer.
  4. Operator Precedence:

    • Be mindful of the order in which operations are performed. Use parentheses () to explicitly control the order of operations if needed.
  5. Modulus Operator:

    • The modulus operator (%) gives you the remainder of a division. Be careful with negative numbers, as the result can sometimes be unexpected depending on the sign of the operands.

These are some common points to keep in mind to avoid errors and ensure your arithmetic operations behave as expected.


🔹 2. Comparison (Relational) Operators

Used to compare two values.

OperatorDescriptionExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than7 > 3True
<Less than3 < 5True
>=Greater than or equal5 >= 5True
<=Less than or equal4 <= 5True

🔹 3. Assignment Operators

Used to assign values to variables.

OperatorExampleEquivalent to
=a = 10Assigns 10 to a
+=a += 5a = a + 5
-=a -= 3a = a - 3
*=a *= 2a = a * 2
/=a /= 4a = a / 4
//=a //= 3a = a // 3
%=a %= 2a = a % 2
**=a **= 2a = a ** 2

🔹 4. Logical Operators

Used to combine conditional statements.

OperatorDescriptionExampleResult
andReturns True if both are TrueTrue and TrueTrue
orReturns True if any is TrueTrue or FalseTrue
notReverses the conditionnot FalseTrue

🔹 5. Identity Operators

Check whether two variables refer to the same object in memory.

OperatorDescriptionExampleResult
isSame object?x is yTrue/False
is notNot same object?x is not yTrue/False

🔹 6. Membership Operators

Test for membership in a sequence (list, tuple, string).

OperatorDescriptionExampleResult
inPresent in sequence?'a' in 'apple'True
not inNot present?'z' not in 'apple'True

🔹 7. Bitwise Operators

OperatorDescriptionExampleResult
&AND5 & 31
``OR`53`7
^XOR5 ^ 36
~NOT~5-6
<<Left shift5 << 110
>>Right shift5 >> 12

Bitwise operators allow you to directly manipulate individual bits within an integer’s binary representation. These operations are powerful, fast, and commonly used in areas like system programming, encryption, compression, and competitive coding.

🔧 What Is Bitwise Operation?

Every integer is stored in memory as a sequence of bits — 0s and 1s. Bitwise operators perform logical operations bit by bit between two integers (or invert a single one). To understand them, you need to first understand how numbers are represented in binary.

For example:

pythonCopyEdita = 5      # binary:  0101
b = 3      # binary:  0011

Let’s now explore each bitwise operator in detail:


1. & (Bitwise AND)

The AND operator compares each corresponding bit of two numbers.

  • If both bits are 1, the result is 1.

  • Otherwise, the result is 0.

Example:

a = 5      # 0101
b = 3      # 0011
result = a & b  # 0001 → decimal 1
print(result)   # Output: 1

This is useful when you want to check if specific bits are set in a number — commonly used in bitmasking.

2. | (Bitwise OR)

The OR operator compares each bit of two numbers.

  • If either bit is 1, the result is 1.

  • Otherwise, it’s 0.

Example:

a = 5      # 0101
b = 3      # 0011
result = a | b  # 0111 → decimal 7
print(result)   # Output: 7

This is used to force certain bits ON in a value.


3. ^ (Bitwise XOR)

The XOR (exclusive OR) operator returns 1 when the two bits are different.

  • If both are the same (0 and 0 or 1 and 1), the result is 0.

  • If different, it’s 1.

Example:

a = 5      # 0101
b = 3      # 0011
result = a ^ b  # 0110 → decimal 6
print(result)   # Output: 6

XOR is useful for:

  • Swapping values without a temp variable

  • Toggle bits

  • Detecting differences


4. ~ (Bitwise NOT)

This is a unary operator, meaning it operates on only one number. It inverts all bits:

  • 0 becomes 1

  • 1 becomes 0

In Python, integers use two's complement for negative numbers. So, ~x returns -(x + 1).

Example:

a = 5      # 0101
result = ~a   # 1010 → two’s complement = -6
print(result) # Output: -6

Understanding two's complement:

  • Start with 5 → 00000101

  • Invert → 11111010 = -6 in decimal


5. << (Left Shift)

This shifts all bits to the left by the specified number of positions. It’s like multiplying by powers of two.

Example:

a = 5      # 0101
result = a << 1  # 1010 → decimal 10
print(result)    # Output: 10

So:

  • a << 1a * 2

  • a << 2a * 4, and so on...

This is useful for:

  • Fast multiplication

  • Constructing bitmasks


6. >> (Right Shift)

This shifts all bits to the right. It’s like dividing the number by powers of two, but flooring the result.

Example:

a = 5      # 0101
result = a >> 1  # 0010 → decimal 2
print(result)    # Output: 2

So:

  • a >> 1a // 2

  • a >> 2a // 4

Right shift is often used for quick division and for parsing individual bits in sequences.


⚠️ Note on Signed Numbers and Bitwise NOT (~)

Python handles negative numbers using infinite precision and two's complement, so the results of ~x might seem confusing. For example:

pythonCopyEditx = 0
print(~x)  # Output: -1

x = -1
print(~x)  # Output: 0

Because:

  • ~x = -(x + 1)

  • So ~5 = -(5 + 1) = -6

This is not “just flipped bits” — it's a representation inversion based on Python’s integer model.


🧪 Mini Applications of Bitwise Operators

1. Check if a number is even

n = 10
print((n & 1) == 0)  # True if even, False if odd

2. Toggle a bit at a position k

x = 10      # 1010
k = 1
x ^= (1 << k)
print(x)    # toggles the second bit (from right)

3. Set a bit at position k

x = 8       # 1000
k = 1
x |= (1 << k)  # sets 2nd bit: becomes 1010
print(x)       # Output: 10

4. Clear a bit at position k

x = 10      # 1010
k = 3
x &= ~(1 << k)
print(x)    # Clears the 4th bit

Bitwise operations provide fine-grained control over data at the bit level. They’re powerful tools for optimization and systems programming.


Wrapping Up

Python provides a wide range of operators to handle everything from basic math to advanced logic and memory checks. Mastering them is the first step to writing efficient Python code.

Stay tuned for the next post in the Python Blog Series!

0
Subscribe to my newsletter

Read articles from Santwan Pathak directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Santwan Pathak
Santwan Pathak

"A beginner in tech with big aspirations. Passionate about web development, AI, and creating impactful solutions. Always learning, always growing."