Python If with NOT Operator

Python IF NOT

We can use logical not operator with Python IF condition. The statements inside if block execute only if the value(boolean) is False or if the value(collection) is not empty.

Sytnax

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.

In summary, we can use if not expression to conditionally execute a block of statements only if the value is not empty or not False.

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

a = False

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

Output

a is false.

Example 2: Python if not – String

In this example, we will use Python if not expression to print the string only if the string is not empty.

Python Program

string_1 = ''

if not string_1:
    print('String is empty.')
else:
    print(string_1)
Run

Output

String is empty.

Example 3: Python if not – List

In this example, we will use Python if not expression to print the list only if the list is not empty.

Python Program

a = []

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

Output

List is empty.

Example 4: Python if not – Dictionary

In this example, we will use Python if not expression to print the dictionary only if the dictionary is not empty.

Python Program

a = dict({})

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

Output

Dictionary is empty.

Example 5: Python if not – Set

In this example, we will use Python if not expression to print the set, only if the set is not empty.

Python Program

a = set({})

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

Output

Set is empty.

Example 6: Python if not – Tuple

In this example, we will use Python if not expression to print the tuple, only if the tuple is not empty.

Python Program

a = tuple()

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

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.