Programming & Coding How-TosTechnology

NameError: Name Is Not Defined in Python — Causes and Fixes

Admin
NameError: Name Is Not Defined in Python — Causes and Fixes

NameError: name 'x' is not defined is usually the first error a Python beginner ever meets. Python is telling you, in its blunt way, that you used a name it has never seen. The variable might be misspelled, defined in the wrong place, or used before it was created. This guide explains how Python names work, the six causes behind almost every NameError, and a quick checking routine that finds the problem in under a minute.

Quick Answer

A NameError means Python reached a name that has no value assigned anywhere it can see. Check three things first: the spelling matches the definition exactly (Python is case-sensitive), the variable is assigned before the line that uses it, and it is defined in the same scope, meaning the same function or the top level of the script. Fixing one of those three resolves most cases.

How Python Names Work

A name in Python is a label attached to a value when you assign it, like score = 10. Names are case-sensitive, so Score, score, and SCORE are three different names. Python looks names up in a specific order: local scope inside the current function, then enclosing scopes, then the global top level of the module, then built-in names like print and len. If the search finishes with no match, you get the NameError. Note that Python checks names when the line runs, not when the file is read, which is why a typo inside a rarely used function can hide until that function is finally called.

The Six Usual Causes

1. A simple typo

You defined user_name but typed usr_name later, or wrote print as prnt. Compare both spellings character by character; your eyes will skip over the difference surprisingly often.

2. Case mismatch

You defined Total = 0 and later used total. Python treats them as unrelated names, so the lowercase one is undefined.

3. Using the variable before assigning it

Code runs top to bottom. If print(result) sits above result = 42, the print line runs first and fails. Move the assignment earlier.

4. The name only exists inside a function

Variables created inside a function are local to it. If total is created inside calculate(), printing total outside the function raises NameError. The fix is to return the value from the function and store it outside.

5. The assignment never ran because it sits in a branch

If discount is only assigned inside an if block, and that condition was false, the name never got a value, yet later code uses it anyway. Give the variable a default value before the if, such as discount = 0.

6. Missing quotes around text

Writing print(hello) when you meant print("hello") makes Python hunt for a variable called hello. Beginners meet this one constantly in their first week.

A Quick Routine to Find the Problem

  1. Read the name in the error. The traceback says exactly which name is unknown, for example name 'reslt' is not defined. That spelling is your first clue.
  2. Search your file for that name. Use your editor’s find function. If the only occurrence is the failing line, the definition is missing entirely or spelled differently at its source.
  3. Search for similar spellings. Look for the name you intended and compare. Fix every occurrence to one consistent spelling.
  4. Check the order. Confirm the assignment line physically sits above the use, and that the code path actually passes through it. A quick print("checkpoint") or a debugger breakpoint proves whether the assignment runs.
  5. Check the scope. If the assignment is inside a function and the use is outside, restructure: return the value, or move the calculation to where it is needed. The official exception documentation describes NameError alongside its close relative, UnboundLocalError.

A Note on “Did You Mean?” Suggestions

Modern Python versions often add a friendly hint, such as NameError: name 'colour' is not defined. Did you mean: 'color'? when a similar name exists in scope. Treat the suggestion as a strong lead, but confirm the spelling you actually want before accepting it, especially when two similar variables both exist on purpose. If you meet a cluster of these beginner errors together, our overview of the SyntaxError that points at a correct-looking line explains the neighbouring error beginners usually hit next.

Common Mistakes to Avoid

  • Defining the variable after the error “to make it go away”. Scattering assignments randomly breaks the program’s logic. Put the definition where the value is genuinely created.
  • Renaming only one occurrence. Use find-and-replace on the whole file so every use matches the definition exactly.
  • Reaching for global everywhere. Sprinkling global declarations fixes the symptom while making the code fragile. Returning values from functions is the cleaner habit.
  • Ignoring indentation while checking scope. A line accidentally indented into a function or loop changes which scope the name belongs to.

A Tiny Example That Shows Scope in Action

Sometimes one small example teaches scope faster than any rule. Consider this script:

def greet():
    message = "Hello"
    print(message)
greet()
print(message)

The first print works because it lives inside the function, where message was created. The final print raises NameError: name 'message' is not defined, because the function’s local names are discarded when the function returns. Nothing is wrong with the spelling or the order; the name simply does not exist out there. Returning the value fixes it properly: change the function to return "Hello", store the result outside with message = greet(), and both prints work.

Imports behave like definitions too, which is why import math must appear before any use of math.pi, and why a from math import sqrt line defines the name sqrt but not the name math. When a NameError names something you are sure you “brought in,” check exactly what your import statement actually defined — the import line is the definition, and its wording decides which names exist.

Conclusion

A NameError always means the same thing: at the moment the line ran, Python had never seen that name in any visible scope. Compare spellings, confirm the assignment runs before the use, and keep function-local values inside their function unless you return them. Those three checks solve nearly every NameError you will ever meet.

Frequently Asked Questions

What is the difference between NameError and UnboundLocalError?

UnboundLocalError is a special NameError for a local variable used before assignment inside a function. Python knows the name is supposed to be local because you assign it somewhere in the function, but the assignment line has not run yet. The fix is the same: assign a value earlier in the function.

Why does the error appear only sometimes when I run the script?

Because the failing line only runs on certain paths. If the broken code sits inside an if branch or a function that is rarely called, the error stays hidden until that path executes. Test the branch or call that triggers it while you fix the name.

Can a missing import cause a NameError?

Yes. If you use math.sqrt(16) without import math at the top, Python reports that the name math is not defined. A missing import usually produces a NameError for the module name itself, which makes this cause easy to spot and fix.

How do I check whether a name exists before using it?

For dictionary keys, use in or .get(). For variables, the normal approach is good structure rather than checks: assign defaults before branches and keep names consistent. In interactive sessions you can inspect dir() or globals() to see which names currently exist.

Why does Python say my function name is not defined?

Either the def line comes after the call in the file, or the function is defined inside another function or a conditional block. Python defines functions in order as the file runs, so move the definition above the first call, ideally near the top of the script.

Admin

Passionate about the intersection of style and storytelling. I simplify fashion trends and industry news into easy-to-follow advice, helping you stay stylish and informed in the fast-paced world of fashion.

2 responses to “NameError: Name Is Not Defined in Python — Causes and Fixes”

Leave a Reply

Your email address will not be published. Required fields are marked *