HOWTO · Python
How to Fix Function Is Not Defined Error in Python
Diagnose a Python NameError by checking the unresolved name, execution order, spelling, imports, and scope, then apply a focused fix.
On this page
NameError means Python evaluated a name that is not available in the current execution context. For an error such as NameError: name 'greet' is not defined, start with the quoted name: Python could not resolve greet at that point. The definition might be below a call that already ran, the spelling or capitalization might differ, a module may not be imported, or the name may be local to another function.
The traceback identifies the line where lookup failed. Check that line and work through the causes below; adding a name with the same spelling in an unrelated place will not fix a problem with execution order or scope.
Identify the name in the NameError
Read the final line of the traceback and copy the name between the quotes. Then inspect the failing expression for that exact identifier. In NameError: name 'random' is not defined, the unresolved name is random; it is not necessarily the function call or value you intended to get from that module. Python identifiers are looked up as written, so a similar-looking name elsewhere does not satisfy the lookup.
Use the traceback’s file and line to find the first failing lookup. If the error occurs while one module imports another, inspect the import path and the code executed during import as well. Fix the cause at the point where the name should become available, rather than masking the error with an unrelated assignment.
Check when the function is defined and called
Python executes a module from top to bottom. A function definition binds its name when execution reaches the def statement; a call earlier in that execution cannot use a definition that has not run yet. Move the call below the definition, or arrange for the call to happen after the module has finished defining its functions. A later definition can work when a function body calls it only after both definitions have executed.
Run this example:
def greet(name):
return f"Hello, {name}!"
message = greet("Ada")
print(message)
The function is defined before its call, and its returned string is printed. When a program is intended to run as a script, a if __name__ == "__main__": guard is another way to keep calls after definitions while allowing the module to be imported without starting the script’s main work.
Check spelling and capitalization
Python names are case-sensitive: Orange, orange, and ORANGE are separate identifiers. Compare the spelling at the use site with the assignment or def statement, character by character. A capital letter, missing underscore, or small typo is enough to make the requested name unavailable. Do not infer from a suggested name in an error message that the suggestion is always the intended variable; verify what the program should use.
For example, Orange = "orange" followed by print(orange) looks similar but asks Python for a different name. Change one side so the assignment and use match. Apply the same check to function calls, imported names, and names passed between modules. Consistent lowercase snake_case for ordinary functions and variables can make mismatches easier to spot, but correctness comes from using the same identifier at definition and use.
Import the module before using its names
Built-in functions such as print() are available without an import. Names in standard-library modules are different: the module must be imported before code refers to its attributes. For example, random is a standard-library module, so random.random() requires import random first. The module name and the attribute name have distinct roles: the import binds random, and .random() calls the function supplied by that module.
If an import is already present, check that it executes before the failing line and that the code uses the name form established by the import. import random supports random.random(); from random import random supports random() instead. When importing a module from your own project, also check that the module file is in the import search path and that its name does not unintentionally shadow a standard-library module. Saving a file alone does not make an unavailable name visible to the current module.
Check whether the name is in scope
A variable assigned inside a function is local to that function unless declared otherwise. Another function cannot directly read that local variable merely because it ran first. Pass the value to the function that needs it, then return the changed value. This makes the data dependency visible and avoids using global as a general workaround.
For example, have take_order() return its list, then pass that list to delete_order(orders, item). Inside delete_order, remove the requested item and return the list; the caller can store the returned value. If a name is expected to come from an enclosing function, review nested-function rules and whether nonlocal is appropriate. For module-level state, verify that the assignment runs before use and that the code is reading the same module-level name.
In this example, orders exists only inside make_order(), so count_orders() cannot look it up directly. It catches the NameError and returns its text; the subsequent call passes the returned list to count_order_items() and prints the count 1. The supplied runtime run completed successfully.
def make_order():
orders = ["tea"]
return orders
def count_orders():
try:
return len(orders)
except NameError as error:
return f"{type(error).__name__}: {error}"
def count_order_items(orders):
return len(orders)
print(count_orders())
print(count_order_items(make_order()))
NameError: name 'orders' is not defined
1
Verify the fix with a minimal example
After identifying the cause, reduce the failing code to the name definition or import, the relevant call, and the smallest input needed. Verify these points in order:
- The identifier in the failing line exactly matches its definition or import, including capitalization.
- The definition or import executes before the lookup.
- The code performing the lookup can access the name in its scope, or receives the value as an argument.
- The minimal example works before restoring surrounding code.
If the reduced example works but the full program still raises NameError, add back the surrounding code gradually and follow the traceback to the first failing lookup. This helps expose a different execution path, an import-time lookup, or a name that is available in one function but not another. Keep the original traceback until the issue is resolved; it records which name Python could not resolve and where the lookup occurred.