[python] python how to "negate" value : if true return false, if false return true

if myval == 0:
   nyval=1
if myval == 1:
   nyval=0

Is there a better way to do a toggle in python, like a nyvalue = not myval ?

This question is related to python boolean negate

The answer is


Use not, for example:

return not myval

In python, not is a boolean operator which gets the opposite of a value:

>>> myval = 0
>>> nyvalue = not myval
>>> nyvalue
True
>>> myval = 1
>>> nyvalue = not myval
>>> nyvalue
False

And True == 1 and False == 0 (if you need to convert it to an integer, you can use int())