If not in Python [18 use cases]

In this article, I will explain what is if not in Python. We will see many use cases where we can use if not condition in Python with ease.

What is if not in Python

In Python, the if statement executes a block of code only if a particular condition is True. While, the not keyword is a logical operator that returns True if the operand (the condition following it) is False, and False if the operand is True. Essentially, it inverts the boolean value of the operand.

When combined, the condition if not in Python checks if a certain condition is False, and if so, the code block under the if not statement will be executed.

if not Python Examples

We can use the not operator with the if-else statement to compare various conditions. Some of the examples are mentioned below in the article. These examples will help one to understand how he/she can use the not operator with an if-else statement.

Case 1: Python if not variable

The if not in Python is used to test if a condition is False or if a variable is “falsy” (e.g., None, 0, empty string, empty list, etc.). Here’s an example using the “if not” condition to check if a variable is None or empty:

USA = ""
if not USA:
    print("The variable 'USA' is either empty or have None as value.")
else:
    print("The variable 'USA' has some value:", USA)

Output:

The variable 'USA' is either empty or have None as value.
python if not

Case 2: Python if not value

The if not in Python is used to check if a value is falsy. This can be useful for checking if variables have a None, False, empty string, empty list, or other falsy value. Here’s an example using various scenarios:

#Example 1: Check if a variable is None
California = None
if not California:
    print("The valuen for California is None or False.")

# Example 2: Check if a list is empty
Companies = ['Apple', 'Microsoft']
if not Companies:
    print("The Companies list is empty.")

# Example 3: Check if a variable is False
Texas = False
if not Texas:
    print("The texas is not a Country")

Output: In the first example, we have a Python variable named ‘California‘ which has None as a value. The if not in Python return True and the code in the block gets executed.

In the second one, we have a Python list named ‘Companies‘ which has some data inside it, so, the if not conditions return False and no code is executed.

In the third example, we have again a variable named ‘Texas‘ which has False as a boolean value. The if not in Python return True and the code in the block gets executed.

The valuen for California is None or False.
The texas is not a Country
if not variable python

Case 3: if not statement Python for empty list

The if not in Python is used to test if a condition is False. Suppose we want to check if a Python list is empty and print a message if it is:

States = []
if not States:
    print("The 'States' list is empty!")

Output: The condition notStates‘ as Python list is True when List is empty. If there were items in the Python list, the condition would be False.

The 'States' list is empty!
if not statement in python

Case 4: If is not Python

In Python, the is and is not operators are identity operators. They check if two variables refer to the same object in memory, not whether the contents of those variables are equal.

Checking if a Python variable is not the capital of California.

city = "Los Angeles"
if city is not "Sacramento":
    print(f"{city} is not the capital of California.")

Output: When we use is not or is with a literal (like a string, number, etc.), it can be misleading. The behavior might not be what we expect. For Python strings, due to string interning in Python, sometimes two identical string literals can reference the same object in memory, but relying on this behavior is not recommended.

C:\Users\kumar\PycharmProjects\pythonProject1\main.py:2: SyntaxWarning: "is not" with a literal. Did you mean "!="?
  if city is not "Sacramento":
Los Angeles is not the capital of California.
python if is not

This is Python’s way of alerting us that we might be making a mistake by using identity comparison (is not) with a literal.

Case 5: If not else Python for variable

The “if not” condition in Python is used to check if a condition is false. Otherwise “else” conditions get executed. Here’s a simple example to demonstrate its usage:

name = "Alexander"
if not name:
    print("Name is not provided!")
else:
    print(f"Hello, {name}!")

Output: In the example above, if the name variable is not an empty string (or value that’s considered True in a boolean context).

Hello, Alexander!
if not in python

Case 6: If not in Python

Let us see a simple example of the if not in Python in which the Program will check if the thing is considered as falsy in Python or not.

variable = input('Enter a value:')
if not variable:
    print('True')
else:
    print('False')

Output: In the above example, if the variable in Python is empty, it will satisfy the If-not statement and the True part of the statement will get executed. But, when we executed the above program and didn’t give any input, the True part of the if-else statement worked in Python. When we executed the Python program again with user input, the False part of the Python if-else statement worked.

#case 1
True

#case 2
False
if not variable python
python if not variable

Case 7: Python if not equal to null

In Python, there is None instead of Null. So we have to check whether a Python variable contains a None value. There are different ways to check it.

Example 1:

variable = None
if variable is not None:
    print('Variable does not contain None')
else:
    print('Variable contains None')

Output: In the above code of Python, we are comparing the Python variable with the None value. we have to use the “is not” to check whether the variable contains a None value.

The “if variable is not None” statement is equivalent to a boolean False. As a result, the False part of the if-else statement is executed.

Variable contains None
if not in python
Output when variable contains a None value

Example 2:

variable = None
if not variable:
    print('Variable contains None')
else:
    print('Variable does not contain None')

Output: In the above code of Python, the if-not statement is equivalent to True because the variable does not contain any value and is storing None. As a result, the statements inside the True block of the if statement are executed in Python.

Variable contains None
if not python
Python if-not statement

Alternative methods:

We can also use the Not Equal to operator symbol(!=) instead of the if-not statement in Python. For example:

variable = None
if variable != None:
    print('Variable does not contain None')
else:
    print('Variable contains None')

Output: In the above Python code the if statement is equivalent to False.

Variable contains None
python if not value

Another alternative is to use the if statement without using the Not operator in Python. Look at the Python code below:

variable = None
if variable:
    print('Variable does not contain None')
else:
    print('Variable contains None')

Output: The if statement in Python checks whether the Python variable is strong in any value or not. The Python variable is not storing any value i.e., it is equivalent to None. Therefore, the if statement is returning False.

Variable contains None
if not statement python

Case 8: Python if not true

The if not True statement in Python is equivalent to if False. Therefore, we should use the if False instead of if not True in Python. However, we can use the if not True statement as shown in the below code:

variable = False
if variable is not True:
    print('Variable stores False')
else:
    print('Variable stores True')

Output:

Variable stores False
python if not true

Alternative method: We can use if False instead of if not True in Python. The result will be the same.

variable = False
if variable is False:
    print('Variable stores False')
else:
    print('Variable stores True')

Output:

Variable stores False
if not true python
Python if False

Case 9: Python if not alphabet

In this section, we will see an example where we will use the if not in Python statement to verify if a Python variable is storing an alphabet or not.

In the below Python example, if the user enters Y as the input, the user will be asked to enter two numbers and the sum of the two numbers will be printed. If any other input value is given, the Python program will be terminated.

choice = input('Enter Y to find the sum of numbers: ')
if choice != 'Y':
    exit()
else:
    num1 = float(input('Enter first number: '))
    num2 = float(input('Enter second number: '))
    print('Sum is: ', num1 + num2)

Output:

Enter Y to find the sum of numbers: Y
Enter first number: 22
Enter second number: 10
Sum is:  32.0
python if not
Validation of an alphabet using if not

In this way, we can validate an alphabet using if not in Python.

Case 10: Python if not equal to string

In this section, we will learn how we can compare two strings to an if-else in Python.

If we want to validate if a Python variable is storing a string data type value or not, we can use the type() function to get the data type of the variable in Python. For example:

str1 = 'Hello'
if str1 != 'Hello':
    print('invalid message')
else:
    print('valid message')

Output:

valid message
if is not python
Comparing a string using not equal to operator

Using is not:

We can also use “is not” with an if-else statement instead of a not equal operator in Python. For example, the above Python code can be rewritten as:

str1 = 'Hello'
if str1 is not 'Hello':
    print('invalid message')
else:
    print('valid message')

Case 11: Python if not empty string

Let us see an example where we can validate if a Python variable contains an empty string or not using the not operator in an if-else statement in Python.

string = input('Enter a username:')
if not string:
    print('Username cannot be empty! Try again')
else:
    print('A valid username')

Output: We have executed the Python code for both test cases. We can see the output for both the test cases i.e. an empty string and a non-empty string in Python.

In this case, also, we can also use the not equal to the not equal operator(!=) in Python.

#case 1
Username cannot be empty! Try again

#case 2
Enter a username:David
A valid username
if not statement in python
python if without condition

In this way, we can validate an empty string using the if not in Python.

Case 12: Python if not equal to two values

If we want to check if a value stored in a Python variable is not equal to one of the two specified values, we can use the logical and or logical or operators in Python, depending upon our requirements.

For example:

username = input('Enter the username: ')
password = input('Enter password : ')
if username != 'admin' or password != 'admin123':
    print('Username and password combination is wrong')
else:
    print('Correct username and password combination')

Output: In the above code, the if statement with the not equal to operator(!=) to compare the username and password variables in Python.

Enter the username: admin
Enter password : admin123
Correct username and password combination
python if not condition
Python if not equal to two values

Case 13: Python if not equal to multiple values

We can also use the if not equal to statement for comparing a variable with more than two values in Python:

For example:

grade= input('Enter a grade: ')
if grade != 'A' and grade != 'B' and grade != 'C' and grade != 'D' and grade != 'E':
    print('Fail')
else:
    print('Pass')

Output: In the above code, the if not statement compares the value in the grade variable with multiple values with the help of logical and operator in Python.

#Case 1
Enter a grade:  F
Fail

#Case 2:
Enter a grade:  B
Pass
what is if not in python
Python if not equal to multiple values

Case 14: Python if not equal to integer

We can use the not equal to operator(!=) to compare two integers. For example, the below Python code snippet checks if a number is even or odd.

number = int(input('Enter a number: '))
if number % 2 != 0:
    print('The number is odd')
else:
    print('The number is even')

Output:

#Case 1:
Enter a number: 34
The number is even

#Case 2:
Enter a number: 37
The number is odd
Python if not equal to integer
Python if not equal to for integers

This way, we can use the not equal to operator to compare the integers in Python.

If we want to use the not operator with if not in Python, the above code becomes:

number = int(input('Enter a number: '))
if number % 2 is not 0:
    print('The number is odd')
else:
    print('The number is even')

Case 15: Python if not in list

In this section, we will check if an item is stored in a list or not in Python. We will use the “not in” operator for the list to check if an item is present in a list or not.

For example, look at the Python code below:

list1=['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
letter = input('Enter an alphabet: ')
if letter not in list1:
    print('The entered alphabet is a consonant')
else:
    print('The entered alphabet is a vowel')

Output:

  • The above program will take an alphabet as an input and return the output telling if the entered alphabet is a vowel or a consonant.
  • The list stores all the vowels. The entered alphabet is compared with the vowels in the list and the result is returned accordingly.
#Case 1
Enter an alphabet:  B
The entered alphabet is a consonant

#Case 2
Enter an alphabet:  C
The entered alphabet is a consonant

#Case 3
Enter an alphabet:  A
The entered alphabet is a vowel
if not function in python
if not in list validation in python

In this way, we can use the “not in” operator with the if-else statement in Python to validate an element in a list.

Case 16: Python list add if not present

Let’s learn how to add an item to a Python list if it is not already present in it. We may need this functionality when we want to have only unique elements in the Python list.

Look at the code below:

list1 = ['1201', '1202', '1203', '1204', '1205', '1206', '1207']
element = input('Enter the employee ID: ')
if element not in list1:
    list1.append(element)
    print('Employee ID added')
else:
    print('Employee ID already exists')
print(list1)

Output:

  • The list contains some unique elements.
  • When the new element is read from the console, firstly, it is searched in the list.
  • Only if it does not exist in the list, it is added to the list.
  • As a result, the list will always contain unique elements.
#Case 1
Enter the employee ID: 1206
Employee ID already exists
['1201', '1202', '1203', '1204', '1205', '1206', '1207']

#Case 2
Enter the employee ID: 1208
Employee ID added
['1201', '1202', '1203', '1204', '1205', '1206', '1207', '1208']
python not equal
Add element in the list if not present

Case 17: Python raise error if not in list

We can also raise an error when an element is not found in the list using the raise keyword in Python. Have a look at the below example:

list1= ['Adams', 'Eva', 'Rose', 'Mary', 'John']
element = input('Enter a name to search in the list: ')
if element not in list1:
    raise Exception('Element not found in the list')
else:
    print('Element found in the list')
  • In the above code, an element is taken as the user input and is searched in the list.
  • If the element is not found in the list, an error is raised with a custom message. Otherwise, if the element is found in the list, the program will execute without any error.
python if not in
Raise an error if the element is not in list

An exception is raised when the supplied value is not found in the list in Python.

Case 18: Python if not do nothing

We may face a situation when we want to use an if-else statement in Python, but don’t want to execute any code inside the if or else block. In such situations, we can use the pass statement.

The pass statement is a null statement. When the interpreter reads this, it performs no operation.

This statement is generally used when we do not want to write any part of the code in Python. For example, defining the Python function and writing its functionality later.

Now let us see how to use it with the if not in Python statement. Consider the example that we discussed in the above section.

list1 = ['1201', '1202', '1203', '1204', '1205', '1206', '1207']
element = input('Enter the employee ID: ')
if element not in list1:
    if not element:
        pass
    else:
        list1.append(element)
        print('Employee ID added')
else:
    print('Employee ID already exists')
print(list1)

Output: The first validation is to check if the element is already present in the list.

Now We have added a second validation that will check if the new element is empty or not. If the new element is empty, it should not be added. Therefore, We have used the pass statement in the Python Code.

If the new element is empty, the pass statement will get executed and the True part of the if-block will not do any operation and the control will move to the next line.

python if is not
Execution of the pass statement

In this way, we can use the pass statement to skip any code block.

Conclusion

This article explains what the if not in Python is with eighteen different use cases, where we have used other different methods present in Python. Additionally, we have also seen what is the is, != operator, pass, etc in Python.

You may like the following Python tutorials to read: