Consider the "not" keyword in Python. With this keyword we change the meaning of expressions—it changes a true result to false.
With "not" we invert an expression in an elegant and clear way. We use not in if
-statements. Sometimes, we want to flip or invert the value of a boolean variable.
To start, we can use "not" as part of an in
-expression. With the in
-keyword we test for inclusion. We see if a value is in a list or a string
or a dictionary.
string
"red" is not an element of the list, so we print the message.string
"blue" is found in the list, so the "in" operator here returns true, and we print a message again.colors = ["blue", "green"] # Part 1: use not in on a list. if "red" not in colors: print("NOT IN, red") # Part 2: use in operator without not. if "blue" in colors: print("IN, blue")NOT IN, red IN, blue
In this example, we use an "if not" clause to test that a method returns False. So if equals()
returns false, the if
-block is entered.
elif
clause. The not-keyword can be added to the start of any expression.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)False False False
With not, we can change True to False and False to True. This may help with creating a loop that alternates between True and False.
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)True False True
This is something that is not often going to be useful. But we can chain multiple "not" keywords at the start of an expression.
valid = False print(valid) # We can make something "not not." valid = not not valid print(valid)False
Instead of the "!=" operator, we can use not with the "==" operator. It is probably clearer just to use the shorter form.
# 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)1 2
With "not" we write Python code that sounds almost like normal English. It is expressive. It is easy to read and parse for humans.