Python If Not Operator

The if not operator in Python is used to negate a boolean condition. It is essentially the opposite of an if statement.

You can use the not operator with if statements to check if a condition is false.

Checking for a Zero Value using if not operator

Syntax

if not value:
  statement(s)

Example 1: Checking for a Zero Value

number = 0

if not number:
 print("number is zero")
else:
 print("number is not zero")

Output

number is zero

Example 2: Checking for an Empty String

An empty string is considered False, so the condition becomes True when the string is empty.

Checking for an Empty String

sample_string = ""

if not sample_string:
 print("The string is empty.")
else:
 print("The string is not empty.")

Output

The string is empty.

Example 3: Using with a Function Return

def is_even(num):
 return num % 2 == 0

if not is_even(3):
 print("The number is odd.")
else:
 print("The number is not odd.")

Output

The number is odd.

The function is_even returns True for even numbers, so if not is_even(3) becomes True because 3 is odd.

Example 4: Checking if an Item is Not in a List

Checking if an Item is Not in a List

fruits = ["apple", "banana", "mango"]

if not "mango" in fruits:
 print("Mango is not in the fruits list.")
else: 
 print("Mango is in the fruits list.")

Output

Mango is in the fruits list.

Example 5: Checking for an Empty Dictionary

dct = dict({})

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

Output

Dictionary is empty.

Example 6: Checking for an Empty Set

Checking for an Empty Set

sample_set = {2, 12, 22}

if not sample_set:
 print("The set is empty.")
else:
 print("The set is not empty.")

Output

The set is not empty.

Example 7: Validating User Input

user_input = input("Enter a name: ")

if not user_input.strip():
 print("No name was entered.")
else:
 print(f"You entered: {user_input}")

Output

Output_of_Validating User Input

Leave a Comment

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