If not condition in Python

In this Python blog, you will see a number of use cases of the if not condition in Python.

You can use the not operator with the if-else statement to compare various conditions. Some of the examples are listed below. These examples will help you to understand how you can use the not operator with an if-else statement.

  • Python if not condition example
  • Python if not equal to null
  • Python if not true
  • Python if not alphabet
  • Python if not equal to string
  • Python if not empty string
  • Python if not equal to two values
  • Python if not equal to multiple values
  • Python if not equal to integer
  • Python if not in list
  • Python list add if not present
  • Python raise error if not in list
  • Python if not do nothing
  • Python if not startswith
  • Python if not file exists
  • Python if not file exists create

Python if not condition example

Let us see a simple example of the if not condition in Python.

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

In the above example, if the variable is empty, it will satisfy the If-not statement and the True part of the statement will get executed.

Therefore, when I executed the above program and didn’t give any input, the True part of the if-else statement worked.

And when I executed the program again with a user input, the False part of the if-else statement worked.

Also, check: Download zip file from URL using python

Python if not equal to null

In Python, there is None instead of Null. So we have to check if a variable contains a None value or not. 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')

In the above code, we are comparing the variable with the None value. I have used “is not” to check if the variable contains a None value or not.

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

if not condition 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')

In the above code, 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 is executed.

python if not condition
Python if-not statement

Alternative methods:

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

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

In the above code the if statement is equivalent to False.

python if not null
Python Not Equal to operator

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

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

The if statement is simply checking whether the variable is strong any value or not. The variable is not storing any value i.e it is equivalent to None. Therefore, the if statement is returning False.

Read: Python Return Function

Python if not true

The if not True statement is equivalent to if False. Therefore, you should use the if False instead of if not True. However, you 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')
python if not true
Python if not True

Alternative method: You can use if False instead of if Not True. The result will be the same.

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

Read: Python find index of element in list

Python if not alphabet

In this section, you will see an example where I have used the if not statement to verify if a variable is storing an alphabet or not.

In the below 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 program will terminate.

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)
Python if not alphabet
Validation of an alphabet using if not

In this way, you can validate an alphabet using if not statement.

Read: Python find number in String

Python if not equal to string

In this section, you will learn how you can compare a string in an if-else statement in Python.

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

str1 = 'Hello'
if str1 != 'Hello':
    print('invalid message')
else:
    print('valid message')
Python if not equal to string
Comparing a string using not equal to operator

Using is not:

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

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

Python if not empty string

Let us see an example where we can validate if a 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')
Python if not empty string
Python if not for validating an empty string

I have executed the code for both test cases. You can see the output for both the test cases i.e. an empty string and a non-empty string.

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

In this way, you can validate an empty string using the not operator in an if-else statement.

Read: Python find number in String

Python if not equal to two values

If you want to check if a value stored in a variable is not equal to one of the two specified values, you can use the logical and or logical or operators, depending upon your 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')

In the above code, I have used the if statement with the not equal to operator(!=) to compare the username and password variables.

Python if not equal to multiple values
Python if not equal to two values

Read: Python convert binary to decimal 

Python if not equal to multiple values

You 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')

In the above code, I have written the if not statement to compare the value in the grade variable with multiple values with the help of logical and operator.

Python if not equal to two values
Python if not equal to multiple values

Read: Python Count Words in File

Python if not equal to integer

You can use the not equal to operator(!=) to compare two integers also. 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')
Python if not equal to integer
Python if not equal to for integers

In this way, you can use the not equal to operator to compare the integers.

If you want to use the not operator with if-else, the above becomes:

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

Python if not in list

In this section, I will explain how you can check if an item is stored in a list or not in Python.

You can 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')
  • 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.
  • I have defined a list to store all the vowels. The entered alphabet is compared with the vowels in the list and the result is returned accordingly.
Python if not in list
if not in list validation in python

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

Also, check: Case statement in Python

Python list add if not present

Now let us learn how to add an item to a list if it is not already present in it. You may need this functionality when you want to have only unique elements in the 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)
  • 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.
Python list add if not present
Add element in the list if not present

Read: How to Reverse a List in Python

Python raise error if not in list

You 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 raise error if not in list
Raise an error if the element is not in list

As you can see in the output, an exception is raised when the supplied value is not found in the list.

Read: Get index Pandas Python

Python if not do nothing

You may face a situation when you want to use an if-else statement, but don’t want to execute any code inside the if or else block. In such situations, you 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 you do not want to write any part of the code. For example, defining the function and writing its functionality later.

Now let us see how to use it with the if-else statement. Consider the example that we discussed in the above section. I have done a small change to it.

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)

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

Now I have added 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, I have used the pass statement.

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 not do nothing
Execution of the pass statement

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

Read: Get First Key in dictionary Python

Python if not startswith

The startwith() function is a string function that checks if a string starts with a specified string value or not.

In this section, I will show you an example of how you can use this function with the not operator in an if-else statement.

string1= input('Enter a name that starts with "A": ')
if not string1.startswith('A'):
    print('Invalid Name')
else:
    print('The name is: ', string1)

In the above example, the name is valid only if it starts with “A”, otherwise the name is not accepted.

Python if not startswith
Using the startswith() function

In this way, you can use the startswith() function for string validation in a Python program.

Read Python print without newline

Python if not file exists

To check if a file exists in the local file system or not, you need to use the os module in Python. This module contains libraries that are used to interact with the local operating system.

You can use the os.path.isfile() function to check if the file exists in the local file system or not. You just need to specify the path to the file in the function.

For example, I have a text file named zipfiles.txt in the location “C:\Users\Blades\Documents\zipfiles.txt“. I have written the below Python code snippet that will check if this file exists in the specified path.

import os
if not os.path.isfile(r'C:\Users\Blades\Documents\zipfiles.txt'):
    print('The specified file does not exist')
else:
    print('The specified file exists')

If the file exists, a True value will be returned.

Python if not file exists
Check if the file is present in the local file system

Now if I specify a file that does not exist, a False value will be returned.

import os
if not os.path.isfile(r'C:\Users\Blades\Documents\random.txt'):
    print('The specified file does not exist')
else:
    print('The specified file exists')
if not file exists python
File not found in the local file system

Hence, in this way you can check whether a file exists in the local file system or not.

Read Create a dictionary in Python

Python if not file exists create

If you want to create a file in the local file system with Python, you can use the open() function.

A file can be opened in two ways:

  • Write mode: Overwrite the previous file contents.
  • Append mode: Append new data to the file without losing the old data.

If you want to create and open a file if it does not exist already, you can use either of the two options inside the open() function:

  • w+: For creating a file if it does not exist and open it in write mode.
  • a+: For creating a file if it does not exist and open it in append mode.

For instance, to create a new file if it does not exist and open it in write mode, you can use the following code snippet:

# Opening the file in write mode
file = open(<file name>, 'w+')

# Writing data in the file
file.write(<data to be written in the file>)

# Closing the file after the contents are written
file.close()

If you want your file to be opened in the append mode, just replace ‘w+‘ with ‘a+‘.

For example, the below code will write data into a file named new_file.txt if it exists. And if the file does not exist, it will be created.

file_name = 'new_file.txt'
# Opening the file in write mode
file = open(file_name, 'w+')

# Writing data in the file
file.write('Sample file contents')

# Closing the file after the contents are written
file.close()
Python if not file exists create
A new file is created

You can see that a new file is created in your Python source file location with the specified data. In this way, you can create a new file in Python if it does not exist.

You may like the following Python tutorials:

So, in this Python tutorial, we have understood a number of use cases of the if not condition in Python. Also, we have covered the following topics.

  • Python if not condition example
  • Python if not equal to null
  • Python if not true
  • Python if not alphabet
  • Python if not equal to string
  • Python if not empty string
  • Python if not equal to two values
  • Python if not equal to multiple values
  • Python if not equal to integer
  • Python if not in list
  • Python list add if not present
  • Python raise error if not in list
  • Python if not do nothing
  • Python if not startswith
  • Python if not file exists
  • Python if not file exists create