How to Return Nothing/Null From a Python Function?

In Python, there's no "null" keyword. However, you can use the "None" keyword instead, which implies absence of value, null or "nothing". It can be returned from a function in any of the following ways:

  1. By returning None explicitly;
  2. By returning an empty return;
  3. By returning nothing at all.

Using any of these is equivalent and purely a stylistic choice.

Returning None Explicitly

You can return None explicitly in a function like so:

def foo(x):
    if x == 0:
        return None

    return 'foo'

print(foo(0)) # None
print(foo(1)) # 'foo'

Returning an Empty return

Returning an empty return in a function is the same as returning None explicitly:

def foo(x):
    if x == 0:
        return

    return 'foo'

print(foo(0)) # None
print(foo(1)) # 'foo'

Returning Nothing at All

You can also return nothing at all from a function, in which case, the return value is implicitly None. For example:

def foo(x):
    if x != 0:
        return 'foo'

print(foo(0)) # None
print(foo(1)) # 'foo'

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.