I was in this code golf thread where I learned in Python 2 you can set True=False
. Now that I would like to go back to the real world I want True
to be regular old True but if I run True=True
python diverts the assignment True
to False
.
I realize I can assign True=1
and things will mostly work normally, but is there a way to reset True
without reseting the kernel?
Because True is equal to 1 and False is equal to 0 , adding Booleans together is a quick way to count the number of True values.
You can convert True and False to strings 'True' and 'False' with str() . Non-empty strings are considered True , so if you convert False to strings with str() and then back to bool type with bool() , it will be True .
Use the boolean OR operator to convert None to 0 in Python, e.g. result = None or 0 . The boolean OR operator returns the value to the left if it's truthy, otherwise the value to the right is returned. Since None is a falsy value, the operation will return 0 .
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 .
del True
This removes the binding you created for True
, unhiding the built-in. This is a slightly more thorough way to undo your mistake than assigning anything to True
, although it usually won't matter.
A lot of things return True
. Do True = 1 == 1
.
Moral of the story: Don't run code-golf code in production environments! You're lucky that that was all you did, a lot of the stuff there is even worse... And I know, coming from PPCG :P
Just a fun one:
True = not True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With