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...
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?
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.
Must Read
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