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.
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.
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
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
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
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.