Python If with NOT Operator

Python if not

In python, we use conditional statements to implement logic in our program. For this, we use boolean expressions with if statements. In this article, we will see how we can use the if statement with the not operator in our python program to implement logical decisions. 

NOT Operator and IF Statement in Python

The syntax for the if statement in python is as follows.

Whenever the boolean_expression evaluates to True, the statements inside the if block is executed.

The not operator in python is used to negate the output of a boolean expression. In other words, if a boolean expression evaluates to True, we can use the not operator with it to make the output False as follows.

Output:

Here you can see that the number 10 is not greater than 20. So, the condition number>20 evaluates to False. Therefore, we have used the not operator to negate the output of the condition. Hence the expression not number > 20 becomes True.

We can use the not operator inside the if statement to conditionally execute a block of statements only if the boolean expression inside the if statement evaluates to False or is a None or empty object.

There are various operations of the if statement with the not operator in python. We will discuss them in the following section.

Applications of the if statement with not operator in python

We can use the if statement with the not operator to check if a list is empty or not. In python, an empty list, when used as a boolean expression, evaluates to False. So, using the not operator helps us to check if the list is None as the entire expression will become True if the list is empty.

For example, if we have to pop out an element from a list and the list happens to be empty, the program will run into an error as shown below.

Output:

To avoid the error, we can use the if statement in python as shown below to check if the list is empty before using the pop() method. Here, the empty list will evaluate to False and the pop() method will not be executed.

Alternatively, we can use the if not statement to notify the user that the list is empty and the element cannot be popped out as follows.

Output:

Similar to lists, we can also check for a dictionary, tuple, or set if they are empty or not using the if not statement in python.

Conclusion

In this article, we have discussed the if not statement in python. We have also discussed the application of the if not statement in python and saw how they are used to negate the output of the if statement in python.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *