Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 864
user2239318 Avatar asked Jun 18 '13 11:06

user2239318


People also ask

How do you negate true/false in Python?

Use the not Operator to Negate a Boolean in Python Here, the bool() function is used. It returns the boolean value, True or False , of a given variable in Python. The boolean values of the numbers 0 and 1 are set to False and True as default in Python. So, using the not operator on 1 returns False , i.e., 0 .

Does 1 == true evaluate true or false in Python?

Operator precedence... the == binds tighter than in , so [1,0] == True gets evaluated first, then the result of that gets fed to 1 in other_result . I've removed the Python-2.7 tag, since Python 3.2 behaves the same way.

How do you do a negation in Python?

The negation operator in Python is not . Therefore just replace your ! with not .


2 Answers

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 
like image 152
Martijn Pieters Avatar answered Sep 18 '22 15:09

Martijn Pieters


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

like image 21
TerryA Avatar answered Sep 18 '22 15:09

TerryA