How To Use “Not” In Python

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,

The output for this will be:

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.

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:

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

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.