Quick Answer

Variable is not defined in current scope. Check for typos, ensure variables are defined before use, and verify import statements for modules.

Understanding the Issue

NameError indicates that Python cannot locate a name (variable, function, class, or module) in any accessible namespace. This commonly occurs due to typos, using variables before definition, incorrect scope access, or missing import statements.

The Problem

This code demonstrates the issue:

Python Error
# Problem 1: Using variable before definition
print(my_variable)  # NameError: name 'my_variable' is not defined
my_variable = "Hello World"

# Problem 2: Typo in variable name
user_name = "Alice"
print(username)  # NameError: name 'username' is not defined (should be user_name)

The Solution

Here's the corrected code:

Python Fixed
# Solution 1: Define variables before use
# Correct order: define then use
my_variable = "Hello World"
print(my_variable)  # Now it works

# Initialize variables with default values
user_input = None  # Initialize first
if True:  # Some condition
    user_input = "User provided input"

print(f"Input: {user_input}")

# Safe variable checking
def safe_print_variable(var_name, local_vars):
    """Safely print a variable if it exists"""
    if var_name in local_vars:
        print(f"{var_name}: {local_vars[var_name]}")
    else:
        print(f"Variable '{var_name}' is not defined")

# Example usage
current_vars = locals()
safe_print_variable("my_variable", current_vars)
safe_print_variable("undefined_var", current_vars)

# Solution 2: Handle scope and imports correctly
# Global vs local scope
global_var = "I am global"

def demonstrate_scope():
    local_var = "I am local"
    print(f"Inside function: {global_var}")  # Can access global
    print(f"Inside function: {local_var}")   # Can access local
    
    # To modify global variable
    global global_var
    global_var = "Modified global"

demonstrate_scope()
print(f"Outside function: {global_var}")  # Modified value
# print(local_var)  # This would cause NameError - local_var not accessible

# Proper import handling
try:
    import math
    result = math.sqrt(16)
    print(f"Square root: {result}")
except ImportError as e:
    print(f"Import error: {e}")

# Check if module/function exists before using
def safe_function_call(func_name, *args):
    """Safely call a function if it exists"""
    if func_name in globals():
        func = globals()[func_name]
        if callable(func):
            return func(*args)
        else:
            print(f"{func_name} is not callable")
    else:
        print(f"Function {func_name} not found")
    return None

# Define a test function
def test_function(x):
    return x * 2

# Test safe calling
result1 = safe_function_call("test_function", 5)
result2 = safe_function_call("nonexistent_function", 5)
print(f"Results: {result1}, {result2}")

Key Takeaways

Always define variables before using them. Check for typos in variable names. Understand variable scope (local vs global). Import required modules before use. Use try-except blocks for safer variable access when uncertain.