Why does 'if not None' return True?

I'm having trouble understanding this

I tried:

if not None:
    print('True')

Why does it print True? Isn't the None type supposed to be None ?


In Python None is a singleton. It is called the null in other languages.

In your if not None: , the compiler assumes that not None means non empty, or non-zero and we know an if statement evaluates non-zero values as True and executes them.

Function Examples:

1) if not None: prints argument x in test()

   def test(x):
       if not None:
           print(x)

   >>> test(2)
   2

2) if 1: prints argument x in test()

   def test(x):
       if 1:
           print(x)

   >>> test(2)
   2

3) if -1: prints argument x in test()

   def test(x):
       if -1:
           print(x)

   >>> test(2)
   2

4) if 0: does not prints argument x in test()

   def test(x):
       if 0:
           print(x)

   >>> test(2)

5) if True: prints argument x in test()

   def test(x):
       if True:
           print(x)

   >>> test(2)
   2

All Python objects have a truth value, see Truth Value Testing. That includes None , which is considered to be false in a boolean context.

In addition, the not operator must always produce a boolean result, either True or False . If not None produced False instead, that'd be surprising when bool(None) produces False already.

The None value is a sentinel object, a signal value. You still need to be able to test for that object, and it is very helpful that it has a boolean value. Take for example:

if function_that_returns_value_or_None():

If None didn't have a boolean value, that test would break.


Python Documentation

4.1. Truth Value Testing

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

None

False

zero of any numeric type, for example, 0, 0.0, 0j.

any empty sequence, for example, '', (), [].

any empty mapping, for example, {}.

instances of user-defined classes, if the class defines a bool () or len () method, when that method returns the integer zero or bool value False.

链接地址: http://www.djcxy.com/p/76626.html

上一篇: IF语句导致webpy发生内部服务器错误

下一篇: 为什么'if not None'返回True?