Concepts / Naming Variables: Rules and Best Practices

Naming Variables: Rules and Best Practices

Keywords are reserved words used by Python to define program structure and cannot be used as variable names.

  • Programming
Interactive lab

Try it: Assignment, Statement by Statement

How an assignment statement evaluates its right side first (using the names' current values) and only then binds the name on the left: updating x = x + 1, augmented operators like += and //=, chained a = b = 0, simultaneous a, b = b, a + b versus one-at-a-time assignment, rebinding a name to a value of another type, the NameError for a name that was never assigned, and the SyntaxError for a name that breaks the naming rules.

How it works

  1. Before anything runs, Python compiles the whole program; a name that breaks the rules (starts with a digit, contains a space or a dash, or is a keyword) is a SyntaxError and no line runs at all.
  2. For each assignment, evaluate the complete right side first, looking every name up in the variable table as it is now.
  3. Then bind the name(s) on the left to that value: a new name is added to the table, an existing one is replaced (even by a value of a different type).
  4. x += 5 reads x, applies the operator (+, -, *, //, %, **) and binds the result back to x; a = b = 0 evaluates 0 once and binds a, then b.
  5. a, b = b, a + b builds the whole right-hand tuple from the OLD values before binding a and b; two separate statements would use the new a in the second line.
  6. Reading a name that is not in the table raises NameError and the program stops at that line.

Default run (10 steps): A 4-line program. Python first compiles all of it, then runs it top to bottom. The variable table on the right starts empty. … Program finished. Final table: x = 16.

Simplified: The programs are fixed templates: you choose the template, its numbers, the operator and the variable name, never the code. The lab's own small Python tokenizer and parser (written for the statements these programs use: assignments, print calls, if / elif / else, for, while, def and return) checks the text; nothing is executed as real Python. Every program the lab can show was compiled by CPython 3.12 and the lab reproduces its exception type, message, line, caret columns and the printed report. A small interpreter written for the same statements then runs them (integers of any size, the str/float results these templates produce, and print); each program was also run in CPython 3.12 under sys.settrace, and the lab reproduces the variables after every line, the output and the error.

Educational simulation

Loading the simulation…

A Name Has a Role

When you name a variable, you are choosing a user-defined identifier: a name for a value in your program. Python also has its own reserved words. These keywords are used to define program structure, so they are not available for variable naming. The central question is therefore not only whether a name looks readable, but also whether Python has already assigned that word a special structural role.

User-definedidentifierChosen for a variableVariable nameAvailable nameReserved keywordUsed for program structureVariable nameNot availablecan definecannot define
What is the difference between a name a programmer can define and a reserved word Python already uses for program structure?

How Python Interprets Names

Python must interpret each name according to the role it plays in a statement. A user-defined variable name is available for the programmer to choose, while a reserved keyword already belongs to Python's program-structure vocabulary. If the same word is placed where a variable name is expected, Python cannot treat it as an ordinary user-defined name. The statement is therefore syntactically invalid and produces a SyntaxError.

Definition

Reserved keyword: a word reserved by Python to define program structure. It cannot be used as a variable name.

Reserved wordPython structureSyntaxErrorroles conflictAssignment markerexpects a name before itValueassigned valueplaced beforefollowed bycannot act as variable name
What changes when a reserved keyword is parsed where Python expects a variable name?

The Reserved Set

Python has 35 specific reserved keywords that are off-limits for variable names. The important recognition skill is to separate this fixed reserved set from names that a programmer is allowed to define. A word may look short, familiar, or readable and still be unavailable if Python reserves it for program structure.

Name categoryPython's treatmentCan it be a variable name?
User-defined identifierChosen by the programmerYes, when it follows the naming rules
Reserved keywordUsed to define program structureNo

The key distinction is whether Python has already reserved the word for program structure.

Shape Rules for Names

A variable name can fail before keyword checking if its shape violates Python's naming rules. Variable names cannot start with a number. They also cannot contain most special characters, including characters such as @ or $. These restrictions are separate from the reserved-keyword rule: a name can be invalid because of its characters, or because the entire word is reserved for Python's program structure.

Worked example

Classifying Three Candidate Names

Decide why each generated candidate should not be used as a Python variable name.

  1. 1
    Candidate A

    A candidate that begins with a number violates the rule that variable names cannot start with a number.

  2. 2
    Candidate B

    A candidate containing @ violates the restriction on most special characters.

  3. 3
    Candidate C

    A candidate that is one of Python's reserved keywords cannot be used as a variable name because the word already defines program structure.

Result

The three candidates fail for two different kinds of reasons: invalid name shape and reserved-word conflict.

Mistakes That Cause SyntaxError

  • Common mistake

    Using a reserved keyword as a variable name

    What it looks like

    Generated example: choosing a word from Python's reserved program-structure vocabulary as the name on the left side of an assignment.

    Why it fails

    Python already uses that word for program structure, so it cannot also be interpreted as an ordinary user-defined variable name.

    Do this instead

    Choose a different user-defined identifier that is not in the reserved set.

  • Common mistake

    Starting a variable name with a number

    What it looks like

    Generated example: a candidate whose first character is a digit.

    Why it fails

    Variable names cannot start with a number.

    Do this instead

    Begin the name with an allowed non-numeric character instead.

  • Common mistake

    Putting @ or $ inside a variable name

    What it looks like

    Generated example: a candidate containing @ or $.

    Why it fails

    Variable names cannot contain most special characters, including these examples.

    Do this instead

    Remove the restricted special character and choose a name that follows the naming rules.

Debugging

When Python reports a SyntaxError near a proposed variable name, inspect the name in two passes. First, check its shape: does it begin with a number, or does it contain a character such as @ or $? Second, check its role: is the complete word one of Python's 35 reserved keywords? This process distinguishes a malformed name from a name that conflicts with Python's program structure.

A Naming Decision Routine

  1. 1
    Start with the complete candidate name rather than judging only part of it.
  2. 2
    Check that the name does not start with a number.
  3. 3
    Check that it does not contain restricted special characters such as @ or $.
  4. 4
    Check whether the complete word is one of Python's 35 reserved keywords.
  5. 5
    If any check fails, select another user-defined identifier before continuing.
EASY

For each of the following generated descriptions, identify the rule that must be checked first: a name beginning with a digit, a name containing $, a word used by Python for program structure, and a name that passes those three checks. Explain whether the issue is name shape, reserved-word status, or no issue identified by the rules in this article.

Hints
  • A leading digit is a shape problem.
  • The dollar sign is a special-character problem.
  • A word used for program structure must be checked against the reserved set.
  • Passing these checks does not require inventing additional restrictions not covered here.

What to Remember

  1. 1
    User-defined identifiers are names chosen for variables, while reserved keywords are reserved by Python for program structure.
  2. 2
    Python has 35 reserved keywords, and none of them can be used as variable names.
  3. 3
    Using a reserved keyword where Python expects a variable name creates a syntax conflict and causes a SyntaxError.
  4. 4
    Variable names cannot start with a number or contain most special characters, including @ and $.
  5. 5
    When diagnosing an invalid name, check both its character pattern and its reserved-word status.

At a glance

  • A variable name must be available for programmer definition and must not be a reserved Python keyword.
  • The reserved keyword set contains 35 words used to define program structure.
  • A reserved keyword used as a variable name creates a SyntaxError because Python cannot assign it both roles.
  • Names beginning with numbers or containing characters such as @ or $ violate variable-naming rules.

Related concepts

More concepts starting with N