C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: We can invert our boolean value with not—we apply "not" to get the inverse of our boolean.
In: Not can be used with the in-keyword. We often make "not in" tests with an if-statement in Python.
InElif: We can also use "not" inside an elif clause. The not-keyword can be added to the start of any expression.
Here: The 3 "false" values are printed, as the 3 print statements are reached when this program executes in the Python interpreter.
Python program that uses not method call
def equals(first, second):
# Return true if the two ints are equal.
return first == second
value = 10
value2 = 100
if value != value2:
# This is reached.
print(False)
if not equals(value, value2):
# This is reached.
print(False)
if value == 0:
print(0)
elif not equals(value, value2):
# This is reached.
print(False)
Output
False
False
False
Python program that uses not to invert booleans
value = True
print(value)
# Change True to False with not.
value = not value
print(value)
# Invert the value back to True.
value = not value
print(value)
Output
True
False
True
Python program that uses not in
colors = ["blue", "green"]
# Use not in on a list.
if "red" not in colors:
print(True)
Output
True
Syntax: This example tells us about how the not-operator is parsed in the language. It modifies the following expression.
Python program that uses not not
valid = False
print(valid)
# We can make something "not not."
valid = not not valid
print(valid)
Output
False
Python program that uses not equals
# Initial animal values.
animal1 = "bird"
animal2 = "bird"
# Compare two strings.
if animal1 == animal2:
print(1)
# Change our animals.
animal1 = "lizard"
animal2 = "fish"
# We can use "not" in front of an equals expression.
if not animal1 == animal2:
print(2)
Output
1
2