Concepts / Creating and Assigning Variables

Creating and Assigning Variables

Variable names must start with a letter or underscore and can contain letters, numbers, and underscores. They cannot start with a digit or contain special characters like @, #, or $.

  • 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…

Why Names Matter

When you create and assign variables, the name you choose has two jobs. It must satisfy Python's syntax rules, and it should help people understand the data it represents. A name such as x is legal but communicates very little. Names such as student_age and total_revenue communicate purpose to other programmers and to your future self.

The Character Positions

Python applies a positional rule to variable names. The first character must be a letter or an underscore. After that first position, the name may contain letters, numbers, and underscores. A digit is therefore allowed later in a name, but not at its beginning. Special characters such as @, #, and $ are not allowed in variable names.

First characterletter or _Later charactersletters, numbers, or _Special characters@ # $ not allowedmay be followed bycannot use
What can appear in the first position, and what additional characters are allowed later?
Worked example

Checking Character Positions

Determine whether each name follows the positional character rules.

  1. 1
    my_var_123

    It begins with a letter and later contains letters, underscores, and numbers, so it follows the technical character rules.

  2. 2
    _private_data

    It begins with an underscore and then uses letters and another underscore, so it follows the technical character rules.

  3. 3
    3rd_attempt

    It begins with a digit, so Python does not accept it as a variable name.

  4. 4
    price$

    It contains the special character $, which is not allowed in a variable name.

Result

A valid name must begin with a letter or underscore, and its remaining characters must be letters, numbers, or underscores.

Accepted and Rejected Names

user_namevalid3rd_attemptstarts with a digit_private_datavalidtotal-costcontains a hyphenMAX_ATTEMPTSvalidimportreserved keywordaccepted namesrejected names
Which example names will Python accept, and which violate a naming rule?

A name that starts with a digit is rejected because the first character does not meet Python's rule. A name containing a hyphen or a symbol such as $ is rejected because those characters are not allowed in variable names. These violations cause Python to stop and report a SyntaxError.

Reserved keywords are another category of rejected name. Words such as class, if, for, while, def, return, and import have special meanings in Python, so they cannot be used as variable names. Using one as a variable name causes a SyntaxError even if its characters would otherwise fit the naming pattern.

NameResultReason
user_nameValidBegins with a letter and uses letters and an underscore
3rd_attemptInvalidBegins with a digit
_private_dataValidBegins with an underscore
total-costInvalidContains a hyphen
MAX_ATTEMPTSValidUses letters and underscores
importInvalidReserved keyword
studentGPAValid but not idiomatic PythonIts characters are allowed, but it does not follow the usual snake_case convention
price$InvalidContains $
my_var_123ValidThe number appears after the first character
returnInvalidReserved keyword

Examples of Python naming rules and conventions

Rules and Conventions

CategoryWhat it meansExamples
Technical rulePython requires this for the name to be acceptedStart with a letter or underscore; use only permitted characters; do not use reserved keywords
Style conventionProgrammers prefer this because it improves readabilityUse snake_case for variable names
Other naming conventionsDifferent kinds of names commonly use different patternsPascalCase for class names; UPPERCASE_WITH_UNDERSCORES for constants

Required syntax versus preferred naming style

Python convention uses snake_case for variable names: lowercase words separated by underscores. This convention is not the same as a syntax requirement. For example, studentGPA is valid because its characters are allowed, but student_gpa better matches the usual Python style. PascalCase is used by convention for class names, and UPPERCASE_WITH_UNDERSCORES is used by convention for constants.

Names That Explain Purpose

xvague namestudent_agemeaningful namestudent ageunclear from xstudent agepurpose is cleardoes not explaincommunicates
How does replacing a vague variable name with a meaningful one make the value's purpose easier to understand?

Meaningful names make code more self-documenting. student_age tells a reader what kind of information the variable represents. total_revenue communicates a different purpose immediately. By contrast, x and data are generic names that reveal little about the value they hold.

Worked example

Choosing Between Legal Names

Choose the clearer name for a value representing a student's age.

  1. 1
    x

    This name is technically legal, but it does not communicate what the value represents.

  2. 2
    student_age

    This name is legal and follows snake_case. It communicates the value's purpose immediately.

Result

Prefer student_age because it is both valid Python and meaningful to readers.

Mistakes to Catch

  • Common mistake

    Starting a variable name with a digit

    What it looks like

    3rd_attempt

    Why it fails

    Python requires the first character to be a letter or an underscore.

    Do this instead
    Use a name such as third_attempt.
  • Common mistake

    Using punctuation in a variable name

    What it looks like

    price$ or total-cost

    Why it fails

    Special characters such as $ and punctuation such as a hyphen are not allowed in variable names.

    Do this instead

    Use letters, numbers, and underscores, such as price or total_cost.

  • Common mistake

    Using a reserved keyword

    What it looks like

    class or return

    Why it fails

    These words have special meanings in Python and cannot be used as variable names.

    Do this instead

    Choose a different name that is not a reserved keyword.

  • Common mistake

    Assuming every valid name is a good style choice

    What it looks like

    studentGPA

    Why it fails

    The name is technically valid, but it does not follow the usual snake_case convention for Python variable names.

    Do this instead

    Prefer student_gpa for an idiomatic Python variable name.

  • Common mistake

    Choosing a name that hides the value's purpose

    What it looks like

    x or data

    Why it fails

    Generic names communicate little to other programmers or to your future self.

    Do this instead

    Choose a meaningful name such as student_age or total_revenue.

Edge case

A name can satisfy the technical character rules and still be a poor choice. studentGPA is valid, but student_gpa follows the usual Python convention more closely. Validity answers whether Python accepts the name; style answers whether the name is clear and idiomatic.

Naming Practice

MEDIUM

Classify each name as valid, invalid, or valid but not idiomatic Python style. For every invalid name, identify the rule it breaks. For every valid but non-idiomatic name, rewrite it using snake_case: accountBalance, 2024_sales, _cache, total$cost, class, user_score.

Hints
  • Check the first character before checking the remaining characters.
  • Look for special characters and reserved keywords.
  • A valid name does not automatically follow the preferred snake_case convention.
  1. 1
    To evaluate a Python variable name, inspect it in this order: first check whether it begins with a letter or underscore; then check that later characters are letters, numbers, or underscores; then check that it is not a reserved keyword. If it passes, improve readability by choosing a meaningful name and following snake_case.

Key Takeaways

  • Python variable names must start with a letter or underscore.
  • Later characters may be letters, numbers, or underscores, but special characters such as @, #, and $ are not allowed.
  • Reserved keywords such as class, if, def, and return cannot be used as variable names.
  • Meaningful names such as student_age and total_revenue make code easier to understand than generic names such as x or data.
  • Technical naming rules are enforced by Python, while conventions such as snake_case are preferred practices for readable code.

More concepts starting with C