Python If with NOT Operator
Python If with not is used to check whether a variable is empty or not. This variable could be Boolean, List, Dictionary, Tuple ,String or set.
Let us go through the examples of each. Note - Below code has been tested on Python 3.
Python Check if not boolean
x = True
if x:
print(x)
If not can check for any expression too.
x = 4
if not x==5:
print("%d is not 5"%x)
Below expression will become true if x is 0.
x = 0
if not 0:
print(x)
else:
print()
Note: Above will true if x is any value other than 0.
x = -2
if not x:
print(0)
else:
print('not 0')
Python Check if not String
With "if not", we can check if string is empty
x = ""
if not x:
print("x is empty")
else:
print(x)
Python Check if not None
x = None
if x is not None:
print("not none")
else:
print(x)
Python Check if not Dictionary
x = {}
if not x:
print(x, "is empty")
else:
print(x,"not empty")
Python Check if not Key in Dictionary
Let us check for key 'b' with Python 'if not'
x = {'a':1,'b':2,'c':3}
if 'b' not in x:
print('key b is not present in x')
else:
print('b is present')
Python Check if not List
If not works on the same way on Python list too as it works on Dictionaries.
x = [1,2,3,4,5,]
if not x:
print('List is empty')
else:
print(x)
Python Check if Element not in List
x = [1,2,3,4,5]
if 6 not in x:
print('6 is not in List')
else:
print('6 is present in list')
x = ["a b","c d"]
if "a b" not in x:
print('"a b" is not present in List')
else:
print('"a b" is present in list')
Python Check If not Set
In this example, we will use Python if not, to check if set is empty.
x = set({})
if not x:
print('Set is empty.')
else:
print(x)
Python Check if value not in Set
x = set({'a','b','c'})
if 'd' not in x:
print('d not in x')
else:
print('d in x')
Python Check if not Tuple
In this example, we will use Python if not, to check if tuple is empty.
x = tuple()
if not x:
print('Tuple is empty.')
else:
print(x)
Python Check if not value in Tuple
x = ("a","b","c")
if 'd' not in x:
print('d not in x')
else:
PRint('d in x')
Summary: Python "if not" operator is very easy to use. I hope the above examples made the usage of Python "if not" clearer.
Related Notebooks
- If Else Statement In R
- How to do SQL Select and Where Using Python Pandas
- Summarising Aggregating and Grouping data in Python Pandas
- Merge and Join DataFrames with Pandas in Python
- How to Convert Python Pandas DataFrame into a List
- How to Plot a Histogram in Python
- How to Generate Random Numbers in Python
- Python Pandas String To Integer And Integer To String DataFrame
- How to Upgrade Python PIP