Why Your Python Function Keeps Returning None and How to Fix it

We’ve all been there… You spend hours crafting the perfect Python function, you put it to the test, and instead of the satisfying output you’re expecting, you’re met with a bewildering ‘None’. And you wonder, “what on earth am I doing wrong?”

Here’s What Actually Works

The frustrating ‘None’ you’re getting is basically Python’s way of saying “hey mate, you didn’t tell me what to return!” It’s important to understand that in Python, every function returns a value. If the function doesn’t explicitly return a value, it returns None.

This is a common oversight for folks new to Python, especially if you’re coming from a language that doesn’t implicitly return a value. Let’s say you have this simple function:

def add(x, y):
    sum = x + y

When you call it with some numbers like add(2, 3) you might expect it to return 5, but it doesn’t. It returns None. Why? Simply because we’ve only calculated the sum, but we forgot to tell Python to return it. Here’s the fixed version:


def add(x, y):
    sum = x + y
    return sum

Now, when you call add(2, 3), you’ll get 5, as expected.

Pro Tips From Experience

  1. Always make sure your function is returning something, even if it’s explicitly None. This will help when debugging.

  2. Be aware that Python functions exit as soon as they hit a return statement. So, if you have code after a return statement, it won’t run.


def add(x, y):
    return x + y
    print("This won't execute!")  # This line won't run
  1. If you are writing a function that alters an object like a list or dictionary, remember that it alters the object itself and you may not need to return it for changes to be preserved.

Bottom Line

The bottom line is, be explicit with your return statements. The few seconds it takes to write “return output” can save you hours of brain-racking debugging. More importantly, your functions will do what they are supposed to do. I’ve learned this the hard way, but it’s one of the most important habits I’ve developed. Finally, learn to love ‘None’ – it’s just a sign that Python is eagerly waiting for your instructions on what to return.