Last modified: Sep 18, 2026

Function Not Defined Python Error Explained

Python is a powerful programming language, but even beginners often encounter the 'function is not defined' error. This error occurs when Python cannot find the function you are trying to call. Let’s explore why this happens and how to fix it.

What Causes the Error?

The error typically appears like this:


NameError: name 'my_function' is not defined

Here are the main reasons:

1. Calling a Function Before Defining It

Python executes code from top to bottom. If you call a function before defining it, Python raises an error.


# Example: Calling a function before defining it
print(my_function())  # This will raise an error

def my_function():
    return "Hello, World!"

NameError: name 'my_function' is not defined

Solution: Define the function before calling it.


# Correct order
def my_function():
    return "Hello, World!"

print(my_function())  # Output: Hello, World!

2. Function in the Wrong Scope

Functions defined inside another function are not accessible outside that scope.


def outer_function():
    def inner_function():
        print("I'm inside!")
    return inner_function

outer_function()  # This will not raise an error
inner_function()  # This will raise an error

NameError: name 'inner_function' is not defined

Solution: Return or store the inner function if you need to use it outside.


def outer_function():
    def inner_function():
        print("I'm inside!")
    return inner_function

func = outer_function()
func()  # Output: I'm inside!

3. Typo in the Function Name

Even a small typo in the function name can cause the error.


def my_func():
    print("Hello")

my_func()  # Correct name
my_funcion()  # Typo: 'my_funcion' instead of 'my_func'

NameError: name 'my_funcion' is not defined

Solution: Check for typos in the function name.

4. Missing Import Statements

If you try to use a function from another module without importing it, you’ll get this error.


import math

print(math.sqrt(16))  # Works
print(math.sqr(16))   # Typo: 'sqr' instead of 'sqrt'

AttributeError: module 'math' has no attribute 'sqr'

Solution: Ensure the correct function name and module import.

Debugging Tips

Here are some strategies to resolve the error:

  • Check the Line Number: The error message includes the line number where the call failed. Review that line.
  • Print the Function: Add a print statement before the call to verify the function exists in scope.
  • Use an IDE: Tools like VS Code or PyCharm highlight undefined functions in real time.

Conclusion

The 'function is not defined' error is common but easy to fix once you understand its causes. Always define functions before using them, check for typos, manage scope properly, and ensure correct imports. Practice writing and debugging code to become more familiar with Python’s execution flow. With time, these errors will become easier to spot and resolve.