python how to “negate” value : if true return false, if false return true

廉价感情. 提交于 2019-11-27 15:28:15

问题


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 ?


回答1:


Use the not boolean operator:

nyval = not myval

not returns a boolean value (True or False):

>>> not 1
False
>>> not 0
True

If you must have an integer, cast it back:

nyval = int(not myval)

However, the python bool type is a subclass of int, so this may not be needed:

>>> int(not 0)
1
>>> int(not 1)
0
>>> not 0 == 1
True
>>> not 1 == 0
True



回答2:


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())




回答3:


Use not, for example:

return not myval


来源:https://stackoverflow.com/questions/17168046/python-how-to-negate-value-if-true-return-false-if-false-return-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!