# NameError: name 'x' is not defined

**Code:** `NameError` · **Category:** Python · **Seen on:** Python

Python doesn’t know the name — it was never assigned/imported in this scope, or it’s misspelled.

## Meaning

Equivalent to JavaScript’s ReferenceError. Common after forgetting an import, using a variable before assignment in a branch that didn’t run, or Python 2 code (`raw_input`, `unicode`) on Python 3.

## Common causes

- Missing import
- Typo or wrong case
- Variable only defined inside an if branch that didn’t run
- Python 2 names on Python 3

## Quick fix

1. Add the import
2. Initialize the variable before branches
3. Replace Python 2 built-ins (`raw_input` → `input`)

## Detailed fix by platform

### Python

1. Linters (ruff, pyflakes) catch undefined names before runtime.

## Code examples

### Variable only set in one branch

```python
if user.is_admin:
    role = "admin"
print(role)        # ❌ NameError when the user is not an admin

role = "member"    # ✅ initialise before branching
if user.is_admin:
    role = "admin"
```

## How to diagnose

1. **Name** — Spelling and case
2. **Import** — Imported in this module?
3. **Flow** — Assigned on every code path before use?
4. **Python 2** — raw_input / unicode / xrange in old code?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/python/nameerror-name-is-not-defined)
