How Do I Get the Opposite (Negation) of a Boolean in Python?

For the following sample:

def fuctionName(int, bool):
    if int in range(...):
        if bool == True:
            return False
        else:
            return True

Is there any way to skip the second if-statement? Just to tell the computer to return the opposite of the boolean bool?

3

9 Answers

To negate a boolean, you can use the not operator:

not bool

Or in your case, the if/return blocks can be replaced by:

return not bool

Be sure to note the operator precedence rules, and the negated is and in operators: a is not b and a not in b.

4

The not operator (logical negation)

Probably the best way is using the operator not:

>>> value = True
>>> not value
False

>>> value = False
>>> not value
True

So instead of your code:

if bool == True:
    return False
else:
    return True

You could use:

return not bool
Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.