How to use the if not Python statement?

This page demonstrates the if-not condition with an example in Python. However, The If condition in Python determines which parts of a statement should be executed. The If not Python Statement checks whether some condition is met or not. Moreover, If not is a logical operator that tests whether a condition is true. However, the condition returned false; the if statement will return the value true(due to not having an operator). However, if any of the preceding conditions are met, it will contain a false value. The following are the ways that demonstrate how if not condition executes:

  • Purpose of the Python statement ‘If not’
  • If not condition to check the alphabets lowercase
  • How to use If not condition in Python?
    • Boolean data type test using if not condition in Python
    • String data type test using if not condition in Python
    • List data type test using if not condition in Python
    • Dictionary data type test using if not condition in Python
    • Set data type test using if not condition in Python
    • Tuple data type test using if not condition in Python
  • If not condition using defined function 
  • If not condition to check file exists in the path or not.
  • Using the dict comprehension 
  • List comprehension handling with, if not in condition in Python

Working on Jupyter Notebook→ Anaconda Environment Python 3.0+

In operator in Python

“in” operator  − In operator checks whether items/elements are present in a provided list. Unless the element is present in the list, it returns false. Let’s understand it through the following example:

list1=['entechin','Python', 'if not condition', '1']
#input() function allows user to enter data
input_data = input('Enter something: ')
#invoking if not in condition
if input_data in list1:
#returns true if input_data match with provided list
   print('The entered data is in the provided list')
   print('True')
#returns False if input_data does not match with provided list
else:
   print('The entered data is not in the provided list')
   print('False')
Enter something: January
The entered data is not in the provided list
False

What is the Not in Operator in Python?

Not in operator – “not in” operator checks whether a given item/element is non-exist in the provided list. In the case of items not existing in the list, the function returns true. If the item exit in the provided list or matches its search, it returns true. Moreover, it invertes the in-operator computations. 

However, the true value of Boolean expressions can be inverted using Python’s not operator. Moreover, not operator can be coupled with if statements (if not) and loops

Let’s dive into the sample to compute its process.

list1=['entechin','Python', 'if not condition', '1']
#input() function allows user to enter data
input_data = input('Enter something: ')
#invoking if not in condition
if input_data not in list1:
#returns true if input_data not match with provided list
   print('The entered data is not in the provided list')
   print('True')
#returns False if input_data match with provided list
else:
   print('The entered data is in the provided list')
   print('False')
Enter something: abcd
The entered data is not in the provided list
True

Otherwise returns

Enter something: if not condition
The entered data is in the provided list
False

What is the purpose of the Python statement ‘If not’?

We use Python’s ‘If not’ statement for various reasons.  ‘If not’ statement uses because of their flexibility.   

An if statement allows you to check for one condition, and if that condition occurs, the program will perform an action. 

However, In an if not condition, when a logical condition is not met, the if statement code executes. On the contrary, if a case statement matches, the if statement computes the results and returns False, and else or elseif (optional) executes. 

Moreover, if not condition controls the flow of execution or the logical operation. 

#import datetime
from datetime import datetime
#syntax to print today date or time
today = datetime.today().strftime("%b/%d/%Y")
print('today:' , today)
if not today == 'Jan/21/2023' :
#executes if today date does not match with provided date
   print('wrong information')
#executes if today date match with provided date
else:
   print("lt's True")
today: Jan/20/2023
wrong information

Otherwise, it returns

today: Jan/20/2023
lt's True

If not condition to check the alphabets lowercase

If not condition is used to check whether the logical statement matches with them or not. However, if it meets the provided condition, it executes an optional else statement. Otherwise, it executes if not statement. Here is a tip to explore Python and practice the Python methods. Press the tab after the (.) dot operator, and you will see built-in methods in Python. However, use the one that fits your code demand.

Here is an example to test the lowercase:

  • If not statement executes if provided variable does not match the function or method.

If the variable matches the operation, it executes the else code.

lower_case = 'xyz@gmail.com'
if not lower_case.islower():
#executes if lower_case does not match with provided function
   print('lower_case is not all lowercase.')
#executes if lower_case do match with provided function
else:
   print('lower_case is all lowercase.')
lower_case is all lowercase.

How to use If not condition in Python?

An int, float, range, Boolean (bytes, bytearray), string, Nonetype, list, dictionary, set, or tuple can be tested via Python’s ‘if not’ condition. Here is the test for standard six data types in Python using if not condition.

Boolean data type test using if not condition in Python

It’s execution is pretty simple, just follow the following steps:

  • Define a boolean variable, 0,1 or True or False
  • Then invoke if not condition
  • If the condition matches with the variable optional else print() command, execute, However, 
  • If the condition does not match with the provided variable, if the statement executes
Bool_input = 0
if not Bool_input == True :
#executes if Boolean does not match with provided variable
   print('Boolean False')
#executes if Boolean match with provided variable
else:
   print("lt's Boolean True")
Boolean False

String data type test using if not condition in Python

Here is how if not condition executes string data type:

  • Define a variable considering string.
  • Invoke condition in if not syntax.
  • If the condition matches the provided string variable, it executes the other body.
  • If the condition does not match the provided string, it executes the if statement
url = 'www.entechin.com'
if not url=='Python':
   print('url is not provided.')
else:
   print('url is provided:', url)
url is not provided.

However, do it in more Pythonic way, like this.

You can bind the user to enter its own string. If the user string matches with the logical if not condition, then it executes the else body. However, if the user input string does not meet the statement, it prints if not condition. 

url= input('enter url: ')
if not url.startswith('www'):
   print('Invalid url')
else:
   print('The valid url: ', url)
enter url: entechin.com
Invalid url

List data type test using if not condition in Python

If not condition to test the element present in the list or not. If so, it executes the else body. However, it does not match the input data; it executes if not a statement.

flower_body_parts = ['sepal','patels','leaves','stems','roots','fruit']
input_date = input('Enter an folower body part: ')
if input_date not in flower_body_parts:
   print('fruit does not includes in the flower')
else:
   print('fruit includes in the flower')
Enter an folower body part: patels
fruit includes in the flower

The list has the property to append, using the append() function with the (.) operator to modify and add the new element to the list. 

flower_body_parts = ['sepal','patels','leaves','stems','roots','fruit']
input_date = input('Enter an folower body part: ')
flower_body_parts.append(input_date)
if input_date not in flower_body_parts:
   print('added in list')
else:
   print('already present in list')
Enter an folower body part: roots
already present in list

Dictionary data type test using if not condition in Python

Like other data types, dictionaries also provide accessibility to check their data type using if not condition. 

  • If a is not empty, else the body will execute. 
a= {'Players': ['Fakhar Zaman', 'JN Malan', 'JC Buttler', 'Ibrahim Zadran', 'Babar Azam'],
                  'Runs': ['193','177*','162*', '162', '158']}
if not a:
   print('Dictionary is empty.')
else:
   print(a)
{'Players': ['Fakhar Zaman', 'JN Malan', 'JC Buttler', 'Ibrahim Zadran', 'Babar Azam'], 'Runs': ['193', '177*', '162*', '162', '158']}

Set data type test using if not condition in Python

The set data type will check the empty status or not. If the set is empty, if not condition body executes; otherwise, else body executes. 

data = set({'Fakhar Zaman', 'JN Malan', 'JC Buttler', 'Ibrahim Zadran', 'Babar Azam'})
print(type(data))
if not data:
   print('Set is empty.')
else:
   print(data)
<class 'set'>
{'JN Malan', 'JC Buttler', 'Ibrahim Zadran', 'Babar Azam', 'Fakhar Zaman'}

Tuple data type test using if not condition in Python

The following example checks the provided tuple matches the condition; if it matches, it executes the else body; otherwise, it executes if not condition. 

a = ('Python','R','C++')
if not a=='java':
   print('not in tuple')
else:
   print('already present in tuple', a)
not in tuple

If not condition using the defined function 

However, by defining a function using the keyword ‘def’ you can form an operation with if not condition.

Here is how it executes:

  • Defina a function and pass parameter to its scope
  • Within the function body, invoke if not statement with a logical condition.
  • If the function attribute satisfies the logical condition, it executes the else body,
  • Otherwise, it executes if not condition. 
  • In the following example, if not condition inverts the operators’ results and returns True. 
def today(day):
   if not  ( day =='Sunday') :
       return True
   else:
       return False
today('Friday')
True

If not condition to check file exists in the path or not. 

Calling .exists() on file with the not operator inverts its result. If .exists() returns False, then the else statement will execute.  

Here is how it executes:

  • Import Path from the pathlib module
  • Import the file from the directory whose existence you want to detect.
  • If not condition checks whether the file exists in the directory or not. If it exists, else the body will execute,

Otherwise, if not statement executes.

#import Path from the pathlib module
from pathlib import Path
#import file from your local directory
txt_file_path = Path("Data_read.txt")
#if not condition check either the file exist in the directory or not
if not txt_file_path.exists():
   print('file is not in the directory')
else:
       print('found in directory')
found in directory

Import file using os module 

You can check the existence of file in your directory by importing the os module. Here is how if not condition helps you to detect a file’s existence in your path. 

import os
if not os.path.isfile("Daty_read.txt"):
#if not condition check either the file exist in the directory or not
   print('file is not in the directory')
else:
       print('found in directory')
file is not in the directory

Using the dict comprehension 

One-liner Python code can remove the keys and values from a dictionary using the dict comprehension approach. 

Here is the execution process that executes the removal of multiple dictionary operations:

  • Creating a dictionary containing multiple keys.
  • Create a list of keys you want to remove from the original dictionary. 
  • With a one-liner dict comprehension, removing multiple keys from the original dictionary. 
  • Using for…in iterable structure in aggregation with if…not in conditional structure to perform the entire operation in a one-liner command. 
  • During the for loop execution, the keys from the dictionary are removed if they are present in the if…not in the structure.  However, keys are removed from the dictionary if the condition if…not it is true in the for a loop.
original_dict={'key1': 'Entechin', 'key2': 2, 'key3': 3, 'key4': 'Python'}
#keys to be removed from the original dictionary
removing_keys = ["key2", 'key3']
print("original_dictionary:\n \t",original_dict)
#using if not condition in dictionary comprehension
print("remove_dict_keys:\n", {key: original_dict[key] for key in original_dict if key not in removing_keys})
original_dictionary:
 	 {'key1': 'Entechin', 'key2': 2, 'key3': 3, 'key4': 'Python'}
remove_dict_keys:
 {'key1': 'Entechin', 'key4': 'Python'}

List comprehension handling with, if not in the condition in Python

List comprehension is a one-liner Python syntax to execute a program instead of using for loop over a list for computation. However, List comprehension consists of for…in structure computes in aggregation with if not in a condition to act on a list.

Here in the following example, if not, conditions execute as:

  • Considering a two list
  • Using for…in structure, and iterate it over lst1, and if not in condition to check whether lst1 exists in lst2.

Below, the condition if x is not in lst2 returns True if the lst2 item is present in lst1. Therefore, the new list will exclude names that include lst2 elements.

lst1, lst2 = ['coding', 'is','fun'], ['is', '1','2']
lst3 = [x for x in lst1 if x not in lst2]
print(type(lst3))
lst3
<class 'list'>
['coding', 'fun']

Conclusion

This page covers methods and functions for using, if not conditions, in Python. The tutorial covers the demonstration of not operator, in operator, not an operator, if not, and if not in conditions in Python in detail with example code. Moreover, it covers how to use them and how these work and computing. Grab the one that best finds your solution to the problem. 

If you want to learn more about Python Programming, visit Python Programming Tutorials.

Leave a Comment

Your email address will not be published. Required fields are marked *