In Python programming, we often encounter situations where we need to make decisions based on the value of certain variables or expressions. One such way to make decisions is by using logical operators, the most common one being the NOT operator. This tutorial will help you understand how to use the not operator in Python effectively.
Understanding the ‘not’ operator
In Python, not is a logical operator that reverses the truth value of an operand. If the given value is True, applying the not operator will make it False and vice versa. This operator is primarily used with conditional statements and loops.
For example,
1 |
not True |
The output for this will be:
False
1 |
not False |
The output for this will be:
True
Using ‘not’ with conditional statements (if)
The ‘not’ operator can be helpful while using conditional statements like if. Let’s take a look at an example.
1 2 3 4 5 6 |
number = 5 if not number < 3: print("The number is greater than 3") else: print("The number is less than or equal to 3") |
The output for this will be:
The number is greater than 3
In this example, the not operator reverses the condition check making it another way of writing if number >= 3:
Using ‘not’ with while loops
While performing loops in Python, we can use the ‘not’ operator to reverse the looping condition. Here’s an example:
1 2 3 4 5 |
counter = 0 while not counter > 3: print("Counter is", counter) counter += 1 |
The output for this will be:
Counter is 0 Counter is 1 Counter is 2 Counter is 3
This example is equivalent to writing while counter <= 3:
Full Code Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
def main(): # Using not with True and False print("not True is ", not True) print("not False is ", not False) # Using not with if statement number = 5 if not number < 3: print("The number is greater than 3") else: print("The number is less than or equal to 3") # Using not with while loop counter = 0 while not counter > 3: print("Counter is", counter) counter += 1 if __name__ == "__main__": main() |
Conclusion
In this tutorial, we have learned the basics of using the not operator with conditional statements (if), and while loops in Python. Understanding how to use this operator will enhance your programming skills and make your code cleaner and more readable.