How to Fix “Function is Not Defined” Error in Python

NameError is common in Python, and it is usually easy to fix once you slow down and read what the traceback is telling you. I hit it often while coding, especially on larger codebases where functions, imports, and helper names move across files.

You can ask an AI assistant to patch a Python NameError for you, and sometimes that is the fastest way out. Still, every developer needs the debugging habit behind the fix: follow the failing line, find the name Python could not resolve, and check where that name should have been defined.

What NameError Means

A name in Python is a label the interpreter can resolve to a value, function, class, or module. Names are created by assignment (x = 1), by def, by class, and by import.

If the interpreter hits a name and no binding exists at the time, it raises NameError: name ‘foo’ is not defined. Python is case-sensitive. print_greeting and print_greting are two different names. Spelling matters.

Python also uses lexical scoping: a name resolved inside a function looks at the function’s local scope first, then the enclosing scope, then the module scope, then the built-ins. A name only available inside one scope is invisible everywhere else.

The Four Common Causes

Almost every NameError you meet falls into one of these four buckets.

Cause 1: Calling a Function Before Defining It

print_greeting("John")

def print_greeting(name):
    print("Hello " + name)

Output:

Traceback (most recent call last):
  File "example.py", line 1, in <module>
    print_greeting("John")
NameError: name 'print_greeting' is not defined

Python reads a script from top to bottom. The call sits above the def, so the name does not exist yet. Move the def above the call and the error goes away.

Cause 2: Misspelling a Function Name

def print_greeting(name):
    print("Hello " + name)

print_greting("John")

Output:

Traceback (most recent call last):
    File "example.py", line 4, in <module>
    print_greting("John")
NameError: name 'print_greting' is not defined

The fix is the corrected spelling: print_greeting. Tab completion in your editor catches most of these before you run the script.

Cause 3: Forgetting to Import a Module

print(random.randint(1, 6))

Output:

Traceback (most recent call last):
    File "example.py", line 1, in <module>
    print(random.randint(1, 6))
NameError: name 'random' is not defined

Python saw the name random but had no module bound to it. Add the import:

import random
print(random.randint(1, 6))

Output:

3

The exact number will vary from run to run, but the call resolves once random is imported. Imports live at the top of the file as a habit.

Cause 4: A Name That Only Exists Inside a Function

def make_greeting():
    msg = "Hi"

print(msg)

Output:

Traceback (most recent call last):
    File "example.py", line 4, in <module>
    print(msg)
NameError: name 'msg' is not defined

The variable msg only exists while make_greeting is running. Returning it keeps it alive outside:

def make_greeting():
    msg = "Hi"
    return msg

print(make_greeting())

Output:

Hi

A Reproducible Example You Can Run

Below is a script with three of the four causes in it. Run it as is. Each error you see maps directly to one of the causes above.

def fetch_user(user_id):
    return {"id": user_id, "name": "Ada"}

current = fetchUser(7)
print(current["name"])

expiry = datetime.date(2026, 1, 1)
print(expiry.year)

Traceback from the second call (the typo fetchUser against the defined fetch_user):

Traceback (most recent call last):
    File "example.py", line 4, in <module>
    current = fetchUser(7)
NameError: name 'fetchUser' is not defined

Fix 1: rename the call to match the definition.

current = fetch_user(7)

Rerun. The next NameError will come from the missing import datetime. Add the import:

import datetime
expiry = datetime.date(2026, 1, 1)

Rerun. The script prints Ada followed by 2026.

When the Name Exists but Is the Wrong Kind

A subtler case looks like a NameError in the traceback but ends up being something else underneath: you shadowed a built-in name and the interpreter cannot find what you expected.

list = [1, 2, 3]
list((4, 5))

Output:

Traceback (most recent call last):
    File "example.py", line 2, in <module>
    list((4, 5))
TypeError: 'list' object is not callable

Python did not raise NameError this time. It raised TypeError because the name list now points to a list object instead of the built-in type.

The same shadowing applies to id, type, input, sum, and dict. Pick a different name and the built-in comes back.

How to Debug a NameError

Read the traceback bottom-up. The last line tells you the exact name the interpreter could not find, and the line above it tells you where the lookup failed. From there, work through these checks in order.

Work through these checks in order when you hit a NameError.

  • Search the file for the spelling you used at the definition site. A case mismatch is enough.
  • Check whether the name sits inside a function. If it does, return it or pass it out as an argument.
  • Check whether the name came from a module you forgot to import, or whether you imported the wrong symbol. The line “from module import name” brings in name, not module.
  • Run the offending script under a debugger if the call site is not obvious. Set a breakpoint on the failing line and inspect the local and global scopes.

References

The official Python tutorial covers naming and binding in the execution model section, and the standard library ships with the dis module if you want to see how the compiler resolves names in compiled bytecode.

Also read: Python ‘Global name not defined’ Error and How to Handle It

Gurpreet Kaur
Gurpreet Kaur
Articles: 37