JavaScript
x
5
1
if myval == 0:
2
nyval=1
3
if myval == 1:
4
nyval=0
5
Is there a better way to do a toggle in python, like a nyvalue = not myval ?
Advertisement
Answer
Use the not
boolean operator:
JavaScript
1
2
1
nyval = not myval
2
not
returns a boolean value (True
or False
):
JavaScript
1
5
1
>>> not 1
2
False
3
>>> not 0
4
True
5
If you must have an integer, cast it back:
JavaScript
1
2
1
nyval = int(not myval)
2
However, the python bool
type is a subclass of int
, so this may not be needed:
JavaScript
1
9
1
>>> int(not 0)
2
1
3
>>> int(not 1)
4
0
5
>>> not 0 == 1
6
True
7
>>> not 1 == 0
8
True
9