Python if not

In this short post, we see if with not operator in Python.

In Python, the not operator is a logical operator that performs boolean negation. It takes a single boolean operand and returns the opposite boolean value.

You can use the not operator in an if statement to check if a given condition is not met. To make an if statement test if something didn’t happen, you can put the not operator in front of the condition at hand. Since the not operator returns the negated result, something true becomes False and vice versa.

Let’s see this:

Python Not operator

The not in Python is considered one of the basic operators used in Python, along with AND and OR operators. Its function is similar to the inverter gate used in Digital Electronics.

x = True
y = not x
print(y)
Output: False

In the above example, the not operator is used to negate the boolean value of x. Since x is True, not x evaluates to False and is assigned to y.

Truth Table of Not operator

InputOutput
TRUEFALSE
FALSETRUE

Python if with not operator

In Python, you can use the not operator with an if statement to check if a condition is not true. Here’s an example:

a = 50
b = 70
if not a > b:
  print("a is smaller than b")
Output: a is smaller than b

In this example, the not operator is used to negate the boolean expression a > b. Since a is smaller than b, the print statement is executed and the output is “a is smaller than b”.

If not in string

name = "Alice"
if not name == "Bob":
    print("This person is not Bob")
Output: This person is not bob

In this example, the not operator is used to negate the boolean expression name == "Bob". Since name is not equal to "Bob", the print statement is executed and the output is “This person is not Bob”.

Related:

Python Basics
List, Set, Tuple, and Dictionary in Python
Python Reverse List items
Python Round() Function
Python Multiline comment
Power in Python | Python pow()
Python range() Function
Square Root in Python
Python for i in range
Python Exception Handling