Python If Not Operator

Python “not in” operator is “used to negate the output of an if statement and check if an iterable is not empty.”

To check if a particular condition is not met, you can use the “if not” operator in Python.

The “not” is a logical operator that “negates the truth value of a given expression or condition.” You can use the “not operator” with “if” statements to “check if a condition is false”.

The not operator can be used with any expression that evaluates to a boolean value (True or False).

Syntax

if not value:
  statement(s)

Parameters

value: It could be of type boolean, string, list, dict, set, etc.

Example 1: How to use if not operator

data = 5

if not data > 10:
  print("data is not greater than 10")

Output

data is not greater than 10

In this example, the “not operator” negates the expression “data > 10”, which evaluates to False because 5 is not greater than 10. The not operator turns this into True, so the print() statement inside the if block is executed.

Example 2: Python if not with logical operators

The not operator can also be used with logical operators like “and” and “or” to create more complex conditions.

age = 20
is_student = False

if not (age > 25 or is_student):
  print("You are not eligible for the discount.")

Output

You are not eligible for the discount.

In this code, the expression age > 25 or is_student evaluates to True because the is_student variable is True. However, the not operator negates this result, making the entire condition False, so the print() statement inside the if block is not executed.

Example 3: if not with String

str = ""

if not str:
  print('String is empty.')
else:
  print(str)

Output

String is empty.

Example 4: if not with the List

lst = []

if not lst:
  print('List is empty.')
else:
  print(lst)

Output

List is empty.

Example 5: if not with Dictionary

dct = dict({})

if not dct:
  print('Dictionary is empty.')
else:
  print(dct)

Output

Dictionary is empty.

Example 6: if not with Set

st = set({})

if not st:
  print('Set is empty.')
else:
  print(st)

Output

Dictionary is empty.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.