G-Fact 19 (Logical and Bitwise Not Operators on Boolean)

Boolean operators are the foundation of logic in computer science. They are used to perform logical and bitwise operations on binary data. In Python, the logical not operator is used to negate a boolean expression while the bitwise not operator is used to invert the bits in a number.

Boolean Operators Overview

The Boolean operators in Python are and, or, and not. The and operator returns True if both operands are True, otherwise False. The or operator returns True if at least one operand is True. The not operator produces the opposite of the operand's truth value.

Here is the truth table for the and and or operators ?

Operand 1 Operand 2 "and" "or"
True True True True
True False False True
False True False True
False False False False

The not operator has only one operand and its truth table is ?

Operand "not"
True False
False True

Logical Not Operator

The logical not operator returns the opposite of a boolean expression. Here's how it works ?

x = True
y = not x
print(f"x = {x}, not x = {y}")

z = False
w = not z
print(f"z = {z}, not z = {w}")

# With expressions
result = not (5 > 3)
print(f"not (5 > 3) = {result}")
x = True, not x = False
z = False, not z = True
not (5 > 3) = False

Bitwise Not Operator

The bitwise ~ operator inverts all bits in a number. It uses two's complement representation, where ~n = -(n+1) ?

x = 5  # Binary: 101
y = ~x  # Bitwise NOT
print(f"x = {x}, ~x = {y}")

# Another example
a = 7  # Binary: 111  
b = ~a  # Bitwise NOT
print(f"a = {a}, ~a = {b}")

# Binary representation
print(f"Binary of 5: {bin(5)}")
print(f"Binary of ~5: {bin(~5)}")
x = 5, ~x = -6
a = 7, ~a = -8
Binary of 5: 0b101
Binary of ~5: -0b110

Combining Logical and Bitwise Not

You can combine both operators in complex expressions ?

x = 7
logical_not = not x  # Logical NOT (False because 7 is truthy)
bitwise_not = ~x     # Bitwise NOT (-8)
combined = not(bitwise_not > 0)  # True because -8 is not > 0

print(f"x = {x}")
print(f"not x = {logical_not}")
print(f"~x = {bitwise_not}")
print(f"not(~x > 0) = {combined}")
x = 7
not x = False
~x = -8
not(~x > 0) = True

Comparison

Operator Symbol Operation Example Result
Logical NOT not Negates boolean value not True False
Bitwise NOT ~ Inverts all bits ~5 -6

Common Applications

Logical NOT: Used in boolean logic, conditional statements, and control flow.

Bitwise NOT: Used in bit manipulation, cryptography, and low-level programming for flipping bits.

Conclusion

The logical not operator negates boolean expressions, while the bitwise ~ operator inverts all bits in a number. Understanding both operators is essential for boolean logic and bit manipulation in Python programming.

Updated on: 2026-03-27T13:14:50+05:30

454 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements