Python If with NOT Operator

Python IF NOT

You can use logical not operator in Python IF boolean expression.

The syntax of Python If statement with NOT logical operator is

if not value:
    statement(s)

where the value could be of type boolean, string, list, dict, set, etc.

If value is of boolean type, then NOT acts a negation operator. If value is False, not value would be True, and the statement(s) in if-block will execute. If value is True, not value would be False, and the statement(s) in if-block will not execute.

If value is of type string, then statement(s) in if-block will execute if string is empty.

If value is of type list, then statement(s) in if-block will execute if list is empty. The same explanation holds correct for value of other collection datatypes: dict, set and tuple.

Example 1: Python if not – Boolean

In this example, we will use Python not logical operator in the boolean expression of Python IF.

Python Program

#not boolean value
a = False

if not a:
	print('a is false.')

#not boolean condition
a = 5

if not a==5:
	print('a is not 5')
else:
	print('a is 5')
Run this program

Output

a is false.
a is 5

Example 2: Python if not – String

In this example, we will use Python if not, to check if string is empty.

Python Program

string = ""

if not string:
    print('String is empty.')
else:
    print(string)
Run this program

Output

String is empty.

Example 3: Python if not – List

In this example, we will use Python if not, to check if list is empty.

Python Program

a = []

if not a:
    print('List is empty.')
else:
    print(a)
Run this program

Output

List is empty.

Example 4: Python if not – Dictionary

In this example, we will use Python if not, to check if dictionary is empty.

Python Program

a = dict({})

if not a:
    print('Dictionary is empty.')
else:
    print(a)
Run this program

Output

Dictionary is empty.

Example 5: Python if not – Set

In this example, we will use Python if not, to check if set is empty.

Python Program

a = set({})

if not a:
    print('Set is empty.')
else:
    print(a)
Run this program

Output

Set is empty.

Example 6: Python if not – Tuple

In this example, we will use Python if not, to check if tuple is empty.

Python Program

a = tuple()

if not a:
    print('Tuple is empty.')
else:
    print(a)
Run this program

Output

Tuple is empty.

Summary

In this tutorial of Python Examples, we learned to use not logical operator along with if conditional statement, with the help of well detailed examples programs.