To negate a boolean variable in Python, the easiest way is with the not operator.

bool_var = True

print(not bool_var)

#Output:
False

When working with conditional expressions, the ability to change their values easily is valuable.

One such case is if you want to negate a conditional and negate a boolean value.

In some programming languages, you can use ! to negate a conditional expression, but in Python, the only want to negate a boolean value is with the Python not operator.

Below shows you how to negate a boolean variable with not in Python.

bool_var = True

print(not bool_var)

#Output:
False

Negating Conditional Expressions With not Operator in Python

In Python, when creating conditional expressions, you can use not to create complex expressions.

For example, if you want to create an if statement with multiple conditions and negate it, you can simply use not in the following way.

num = 1

if not num > 3 and num > 0:
    print("num is not greater than 3 but is greater than 0")
else:
    print("num is greater than 3")

#Output:
num is not greater than 3

You can also negate conditional expressions with not by wrapping the entire expression in parentheses.

num = 1

if not (num < 10 and num > 0):
    print("num is not between 0 and 10")
else:
    print("num is between 0 and 10")

#Output:
num is between 0 and 10

Hopefully this article has been useful for you to learn how to negate boolean values and negate conditional expressions in your Python code.

Categorized in:

Python,

Last Update: March 12, 2024