How to Fix NameError name is not defined in Python With Examples

 


What is NameError?

NameError: name 'x' is not defined means you're trying to use a variable or function that hasn't been defined yet.

Common Causes & Fixes:

1. Using Undeclared Variable

print(name)

Fix:

name = "John"
print(name)

2. Typo in Variable or Function Name

value = 90
print(vaalue)

Fix:

value = 90
print(value)

3. Calling a Function That Hasn’t Been Defined Yet

result = compute()

Fix:

def compute():
    return 2 * 2

result = compute()

4. Using Variable Outside Its Scope

def greet():
    msg = "Hi"

print(msg)

Fix:

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

print(greet())

5. Incorrect Order of Execution

print(number)
number = 7

Fix:

number = 7
print(number)

Tips to Avoid NameError:

  • Use a code editor with linting/autocomplete.
  • Double-check variable/function spelling.
  • Always define variables before using them.
  • Use print() or a debugger to track variable availability.

0 Comments:

Post a Comment