if myval == 0:
nyval=1
if myval == 1:
nyval=0
C'è un modo migliore di fare un interruttore in python, come un valore nyvalue = non myval?python come "negare" valore: se true restituisce false, se false restituisce true
if myval == 0:
nyval=1
if myval == 1:
nyval=0
C'è un modo migliore di fare un interruttore in python, come un valore nyvalue = non myval?python come "negare" valore: se true restituisce false, se false restituisce true
Utilizzare la not
boolean operator:
nyval = not myval
not
ritorna un valore booleano valore (True
o False
):
>>> not 1
False
>>> not 0
True
Se è necessario disporre di un numero intero, gettato indietro:
nyval = int(not myval)
Tuttavia, il tipo pitone bool
è una sottoclasse di int
, quindi questo non può essere necessaria:
>>> int(not 0)
1
>>> int(not 1)
0
>>> not 0 == 1
True
>>> not 1 == 0
True
In pitone, not
è un operatore booleano che ottiene l'opposto di un valore:
>>> myval = 0
>>> nyvalue = not myval
>>> nyvalue
True
>>> myval = 1
>>> nyvalue = not myval
>>> nyvalue
False
e True == 1
e False == 0
(se avete bisogno di convertirlo in un intero, è possibile utilizzare int()
)
usa not
, per esempio:
return not myval