What is Python equivalent of the ! operator?


In some languages like C / C++ the "!" symbol is used as a logical NOT operator. !x it returns true if x is false else returns false. The equivalent of this "!" operator in python is logical NOT, It also returns true if the operand is false and vice versa.

Example

In the Following example the variable operand_X holds a boolean value True, after applying the not operator it returns False.

operand_X = True
print("Input: ", operand_X)

result = not(operand_X)
print('Result: ', result)

Output

Input:  True
Result:  False

Example

For False value the not operator returned True to this example.

operand_X = False
print("Input: ", operand_X)

result = not(operand_X)
print('Result: ', result)

Output

Input:  False
Result:  True

Example

In this example we have applied the not operator to the string object X, and the operator returns False.

X = "python"
print("Input: ", X)

result = not(X)
print('Result: ', result)

Output

Input:  python
Result:  False

Example

The empty list is treated as False in python, due to this the not operator returned True for the empty list object.

li  = []
print("Input: ", li)

result = not(li)
print('Result: ', result)

Output

Input:  []
Result:  True

Example

Following is another example

print("not(10 < 20): ",not(10 < 20))
print("not(10 > 20): ",not(10 > 20))
print("not(True = True): ",not(True == True))

Output

not(10 < 20):  False
not(10 > 20):  True
not(True = True):  False

Updated on: 09-Sep-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements