How to "negate" value: if true return false, if false return true?
Asked Answered
H

4

66
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 ?

Haemato answered 18/6, 2013 at 11:47 Comment(0)
A
113

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
Arresting answered 18/6, 2013 at 11:49 Comment(0)
R
3

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

Rettarettig answered 18/6, 2013 at 11:50 Comment(0)
B
3

Use not, for example:

return not myval
Billie answered 18/6, 2013 at 11:50 Comment(0)
K
0
variable = not (False | variable)

is similar to

if variable == True:
    variable = False
elif variable == False:
    variable = True
Kauffman answered 18/1, 2022 at 10:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.