What is the ‘not’ operator in Python?
- The ‘not’ is a Logical operator in Python that returns True if the expression is False.
- The ‘not’ operator is used in the if statements.
For example:
- If x is True, then not will be evaluated as False, otherwise, True.
I will show you a few examples to make things clearer regarding how to use the not operator in the coming section.
Python not operator example with if statement
In the following example, a variable x is assigned a value 10. The ‘not’ is used in the if statement as follows:
See the code and result.
#A demo of Python 'not' operator x = 10 if not x > 10: print("not retured True") else: print("not retured False")
Output:
As x>10 is False, so ‘not’ operator is evaluated as True, thus the if statement is True, and the code inside the if statement is executed.
See the next example that will make things even clearer.
How not operator works?
In this demo, the x is used as follows with ‘not’ operator.
Python program:
#A demo of Python 'not' operator x = 10 if not x: print("Evaluated True") else: print("Evaluated False")
Result:
The expression not x means if x is True or False.
In that case, as x = 10, it is True. As x is True, so ‘not’ operator is evaluated as False, and the else part is executed.
See the same example below where the value of x = 0.
x = 10 if not x: print("Evaluated True") else: print("Evaluated False")
Result:
A Python not with ‘in’ example
In this example, I will show you how to use the ‘not’ operator with ‘in’.
For that, a numeric list of six items is created. This is followed by using a for loop to iterate through the list elements and display their values.
After that, an if statement is used to omit certain numbers to be displayed. There, the not operator is used with the ‘in’ as follows:
#A demo of Python 'not' with 'in' operator a_List = [5, 10, 15, 20, 25, 30] for a in a_List: if not a in (10,25): print ("List Item: " ,a)
Output:
List Item: 15
List Item: 20
List Item: 30
You see, the items that evaluated False as using ‘not’ did not display.