How exactly does not work, especially if we write not not?

Question

How exactly does not work, especially if we write not not?

Answer

The basics are simple enough, but like a lot of things we’ve learned so far, can become pretty tricky if we add onto them! The not operator is no exception!
Something that may help us when determining if a statement is True or False is breaking it down into its simplest parts and then solving the whole thing. Take a look below for an example:
bool_complicado = not not 3 ** 2 + 10 != 60
First let’s do the stuff after the 2 nots to make life easier. Step by step, that’d look like:

bool_complicado = not not 9 + 10 != 60
bool_complicado = not not 19 != 60
bool_complicado = not not True

Great! Now we see it in a much simpler form and can apply those pesky nots. Always apply the inner-most not first.

bool_complicado = not False
bool_complicado = True

Notice how not True became False on the first line above, and then not False is as much as we could break it down before writing the final answer!

5 Likes

I can’t see any practical use for these bizarre twists of logic.
What are some actual uses for using “not not True” ?

7 Likes

It will come up eventually when working with truthiness, as opposed to boolean literals.

a = 0
b = 7
not (a * b)      =>  True

but zero is not truthy, so double not will yield the correct boolean to match.

not not (a * b)  =>  False
3 Likes

I hope “truthy” is something we learn later on.

6 Likes

There are only two boolean literals… True, and False. The conditionals if and while always resolve to one or the other, regardless what form of expression is given as the argument. This is where truthy comes in.

"The dew is heavy this morning."

True, or False? The computer doesn’t know that this is true, or false. All it sees is a string of characters for which it has only one lexicon… Character codes. It can’t even tell us what language this is without some outside help. But it can tell us it is truthy so as an if expression, it will yield True.

dew_is_heavy = "The dew is heavy this morning."
if dew_is_heavy:
    print "Don't wear sandals this morning if walking on the grass."
else:
    print "Safe to wear sandals for walking in the grass this morning."

All the computer can do is look at values and resolve them one way or the other. Every expression can be boiled down to a value. Empty strings, zero and None are values that have no real definition so cannot be truthy or nothing would make sense.

def is_even(x):
    return not x % 2

Let’s say x is 11. Then x % 2 will be 1. We want to return a boolean to the caller (as implied by the prefix, is_) that describes the argument given to the function. In this instance not will cast a boolean from the expression. 1 is truthy, but 11 is odd. In this case we return False because of the not which toggles to the opposite boolean.

not "string"  =>  False
not ""        =>  True
11 Likes