Search code examples
python-3.xnonetype

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?


Solution

  • 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