In Python, how do you explain the expression 'x = not x'

Asked

Viewed 349 times

8

I already know the result, but I would like to understand what happens, why of such a result...

For example:

>>> a = True
>>> b = not a    
>>> print(b)
False

It’s a simple thing, but I feel upset to wear something without knowing how it works.

  • 1

    I don’t know if I understood your question, but I answered it as completely as I could. If that’s not what you wanted, please clarify what in the quoted expression you don’t understand.

  • Thank you for the answer! Indirectly his answer clarified the doubt, which arose after reading a code that used this expression, because he was used to using not in expressions like 'if x not in y:' or 'if x not True:'

1 answer

8


The precedence of operators = and not is such that the instruction cited is to be interpreted as:

=(b, not(a))

i.e. "evaluate not(a) and save the result in b".

Already the expression not(x) returns True if x is false in a Boolean context, or False if x is true in the same context. In Python, the following values are considered "false":

False
None
0
0.0
-0.0
""
[]
()
{}
class MinhaClasse(object):
    def __bool__(self): # Python 3
        return False
    def __nonzero__(self): # Python 2
        return False

The other values are considered "true".

Like a is one of the true values (True), then not(a) evaluates to False, and this is the value that is stored in b.

If the same variable were used (as in the title of your question), naturally all evaluation on the right side would occur before assignment to the left side:

>>> x = True
>>> x = not x   # x é True; not(True) é False; guarde False em x => x é False.
>>> print(x)
False

Note that the result of not(x) will always be True or False, only, unlike operators such as and or the or that always return one of the original values:

>>> 1 and "teste"   # Verdadeiro(1) E Verdadeiro(2) é Verdadeiro(2)
'teste'
>>> {} and True     # Falso(1) E Verdadeiro(2) é Falso(1) => curto-circuito
{}
>>> False or []     # Falso(1) OU Falso(2) é Falso(2)
[]
>>> 42 or None      # Verdadeiro(1) OU Falso(2) é Verdadeiro(1) => curto-circuito
42

Browser other questions tagged

You are not signed in. Login or sign up in order to post.