Variables and Naming
Topic — In Python, variable names are identifiers that bind names to objects stored in memory. While the interpreter strictly rejects syntax errors like leading digits or hyphens, the greater danger lies in naming anti-patterns: accidentally shadowing built-in functions like
listorsumwithout realizing it. This guide covers legal identifier syntax, the 35 reserved keywords, PEP 8 styling conventions, and the memory pointer model.
1. The Core Concept
An identifier is a token used to name a variable, function, class, or module. In Python:
| Status | Rule | Example |
|---|---|---|
| Allowed | Must start with a letter (a-z, A-Z) or an underscore (_) | student, _private |
| Allowed | Can contain letters, digits (0-9), and underscores | user_123, batch_size |
| Allowed | Case-sensitive (age, Age, AGE are 3 separate variables) | age != Age != AGE |
| Forbidden | Cannot start with a digit | 2fast (SyntaxError) |
| Forbidden | Cannot contain spaces | student name (SyntaxError) |
| Forbidden | Cannot contain hyphens or symbols (-, @, #, $, %) | my-var, total$ |
| Forbidden | Cannot be a Python keyword | class, for, def |
| Warning | Should never shadow built-ins (list, str, dict, sum) | list = [1, 2] (Breaks list()) |
If you only take one thing from this page
In Python, - is the subtraction operator, not a separator. Writing student-name is parsed as student minus name, raising SyntaxError: cannot assign to expression. Always use underscores (student_name).
2. Interactive Variable Name Validator
Type any candidate identifier into the input box below or click the preset buttons to check syntax legality, keyword collisions, built-in shadowing, and PEP 8 compliance live:
Python Variable Name Validator
Type a candidate variable name or test one of the common problem presets:
Legal Python identifier adhering to standard PEP 8 snake_case.
3. Python's 35 Reserved Keywords
Python 3.11 features 35 reserved keywords. These are hardcoded into the language grammar and cannot be assigned as variable names:
| Category | Reserved Keywords |
|---|---|
| Control Flow | if, elif, else, for, while, break, continue, pass |
| Functions & Classes | def, return, lambda, yield, class |
| Imports & Modules | import, from, as |
| Exception Handling | try, except, finally, raise, assert |
| Logic & Identity | and, or, not, in, is |
| Constants | True, False, None |
| Scope & Memory | global, nonlocal, del |
| Asynchronous & Context | with, async, await |
Soft Keywords
Python 3.10 introduced "soft keywords" (match, case, type, and _). These act as keywords inside pattern matching statements, but remain syntactically legal as variable names elsewhere. However, using them as variables confuses collaborators and linters; avoid them.
4. The Silent Hazard: Shadowing Built-ins
Unlike keywords, Python's built-in functions (list, str, int, dict, sum, id, type, input, min, max) are not reserved syntax tokens.
Assigning list = [1, 2, 3] is syntactically legal. However, doing so shadows the built-in function in the local namespace:
# THE SHADOWING TRAP
list = [1, 2, 3] # Legal, but 'list' now references an array instance!
# Later in your codebase:
new_items = list((4, 5))
# TypeError: 'list' object is not callable
Why Shadowing is Worse than a SyntaxError
A SyntaxError prevents your program from starting immediately. Built-in shadowing compiles cleanly and fails silently much later in unrelated modules when another function attempts to call str(), sum(), or list().
5. Interactive Memory Pointer Model
Variables in Python are named labels pointing to objects on the heap, not physical boxes containing data:
Memory Pointer and Object Identity Simulator
Select a scenario to visualize how variables reference objects in memory:
a = [1, 2, 3] b = a # Both labels point to memory address 0x7f9a b.append(99) # Modifies the object in-place! print(a) # Output: [1, 2, 3, 99]
Memory Mechanism: Because lists are mutable, b = a does not duplicate the list. Both variable names point to the exact same heap memory location (a is b == True).
6. Implementation Lab
Lab Exercise: Identifiers, Built-in Shadowing & Memory Aliasing
An interactive, fully functional Google Colab / Jupyter Notebook is available to validate identifiers programmatically using keyword.iskeyword() and str.isidentifier(), inspect memory addresses with id(), and reproduce built-in shadowing live in your browser.
How to run the lab:
- Click the "Open In Colab" badge above to launch the interactive notebook.
- Run cells sequentially to test identifier validation rules and memory aliasing.
Key Experiments to Run:
- Experiment 1 (Programmatic Legality): Iterate over 10 candidate names using
str.isidentifier()andkeyword.iskeyword(). - Experiment 2 (The Built-in Shadowing Crash): Assign a variable
sum = 300and observe the subsequentTypeErrorwhen attempting to callsum([10, 20]). Restore the function usingdel sum. - Experiment 3 (Object Identity with id()): Inspect
hex(id(a))andhex(id(b))to empirically verify shared heap references.
7. Common Mistakes
- 1. Using Hyphens (Kebab-Case)
- 2. Shadowing Built-in Functions
- 3. Starting Identifiers with Digits
- 4. Believing UPPER_CASE Enforces Real Constants
- 5. Case-Sensitivity Confusion
- The Misconception: "HTML and CSS use
user-name, so Python allows it." - Wrong Thinking: Typing
user-name = "Alex". - The Right Principle:
-is the subtraction operator. Python evaluatesuser minus name = "Alex", which raisesSyntaxError: cannot assign to expression. Always use underscores (user_name).
- The Misconception: "Using
list = [1, 2]ormax = 50is fine because Python didn't raise a syntax error." - Wrong Thinking: Naming variables after built-in types or functions.
- The Right Principle: Python silently overwrites the built-in reference in your local scope, causing
list()ormax()to crash later withTypeError: 'int' object is not callable.
- The Misconception: "Naming a variable
1st_placeis clear and descriptive." - Wrong Thinking: Placing a number as the first character.
- The Right Principle: When the Python lexer encounters a digit, it enters numeric literal parsing mode. Hitting letters causes an immediate
SyntaxError: invalid decimal literal. Usefirst_placeorplace_1.
- The Misconception: "Defining
MAX_USERS = 100prevents other code from reassigning it." - Wrong Thinking: Assuming Python has native compiler constants like
constin C++ or JavaScript. - The Right Principle:
UPPER_CASEis strictly a PEP 8 human convention. Python's runtime does not protect constants;MAX_USERS = 200reassigns without error.
- The Misconception: "Typing
Ageoragereferences the same variable." - Wrong Thinking: Treating Python as case-insensitive like SQL.
- The Right Principle: Python is strictly case-sensitive.
age,Age, andAGEare three completely independent variables in the namespace.
8. Summary
Syntactic Rules
- Valid First Character: Letter (
a-z,A-Z) or underscore (_). - Subsequent Characters: Letters, digits (
0-9), and underscores. - Forbidden: Digits first, spaces, hyphens (
-), symbols (@,$). - Reserved: 35 Python grammar keywords (
class,def,for).
PEP 8 Style Conventions
- snake_case: Variables and functions (
student_name,calc_total). - UPPER_CASE: Constants (
MAX_RETRIES,DEFAULT_TIMEOUT). - PascalCase: Classes (
StudentProfile,LinearModel). - _leading: Internal / private scope hint (
_hidden_state).
Key Takeaways
- Variables are pointers: Assignment binds a label to an object; mutable objects can be altered via any shared alias tag.
- Never shadow built-ins: Avoid using
list,str,dict,sum,id,type, orinputas variable names. - Follow PEP 8: Use descriptive
snake_casenames rather than single-letter acronyms.
Next Section: Data Types - exploring the full catalog of Python's built-in numeric, sequence, mapping, and set data types.
9. Active Recall
Test your understanding by answering first, then clicking to reveal the underlying principles.
Interactive Checkpoint Quiz
Interactive Checkpoint: Identifying the Illegal Identifier
Which of the following variable assignments will cause an immediate Python SyntaxError?
Review Flashcards
1. [THEORY] Why does Python raise a SyntaxError on student-name = "Alex", but a NameError on student#name = "Alex"?
- Hyphen (
-): Is parsed as the binary subtraction operator. Python sees an expression assignment (student minus name = ...), which is illegal syntax. - Hash (
#): Marks the start of a code comment! Python completely ignores everything after#on that line, executing onlystudent. - Because
studenthas never been defined, Python raisesNameError: name 'student' is not defined.
2. [PRACTICE] What happens when you run sum = 100 followed by sum([1, 2, 3])? How do you fix it?
- The Crash:
TypeError: 'int' object is not callable. - Assigning
sum = 100binds the namesumto an integer object in your local namespace, shadowing the built-in function. - Attempting to call
sum(...)now treats the integer100as a function! - The Fix: Delete the variable from the namespace:
del sum. This restores access to the global built-in function.
3. [THEORY] What does the is operator test compared to == in Python?
==tests Value Equality: Does object A hold the same contents as object B?istests Reference Identity: Do labels A and B point to the exact same object at the same memory address (id(A) == id(B))?- Example:
[1, 2] == [1, 2]isTrue, but[1, 2] is [1, 2]isFalse(two distinct list instances).
4. [ANALYZE] Does Python have true constants like C++ const or JavaScript const?
- No: Python has no language construct to prevent variable reassignment.
- Writing
MAX_USERS = 100is purely a PEP 8 signaling convention to human developers that the variable should not be changed. - If a developer executes
MAX_USERS = 200, the interpreter rebinds the variable without any error.
5. [THEORY] Why are leading underscores used in variable names like _cache?
- PEP 8 Privacy Convention: A single leading underscore signals to other developers and IDEs that the variable or method is intended for internal use only.
- Wildcard Import Protection: Names with a leading underscore are not imported when another module executes
from my_module import *.