How do I get the opposite (negation) of a Boolean in Python?

后端 未结 7 1501
太阳男子
太阳男子 2020-12-08 03:57

For the following sample:

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


        
7条回答
  •  生来不讨喜
    2020-12-08 04:02

    The accepted answer here is the most correct for the given scenario.

    It made me wonder though about simply inverting a boolean value in general. It turns out the accepted solution here works as one liner, and there's another one-liner that works as well. Assuming you have a variable "n" that you know is a boolean, the easiest ways to invert it are:

    n = n is False
    

    which was my original solution, and then the accepted answer from this question:

    n = not n
    

    The latter IS more clear, but I wondered about performance and hucked it through timeit - and it turns out at n = not n is also the FASTER way to invert the boolean value.

提交回复
热议问题