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 $.
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
- 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.
- For each assignment, evaluate the complete right side first, looking every name up in the variable table as it is now.
- 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).
- 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.
- 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.
- 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.
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.
Checking Character Positions
Determine whether each name follows the positional character rules.
- 1my_var_123
It begins with a letter and later contains letters, underscores, and numbers, so it follows the technical character rules.
- 2_private_data
It begins with an underscore and then uses letters and another underscore, so it follows the technical character rules.
- 33rd_attempt
It begins with a digit, so Python does not accept it as a variable name.
- 4price$
It contains the special character $, which is not allowed in a variable name.
A valid name must begin with a letter or underscore, and its remaining characters must be letters, numbers, or underscores.
Accepted and Rejected Names
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.
| Name | Result | Reason |
|---|---|---|
| user_name | Valid | Begins with a letter and uses letters and an underscore |
| 3rd_attempt | Invalid | Begins with a digit |
| _private_data | Valid | Begins with an underscore |
| total-cost | Invalid | Contains a hyphen |
| MAX_ATTEMPTS | Valid | Uses letters and underscores |
| import | Invalid | Reserved keyword |
| studentGPA | Valid but not idiomatic Python | Its characters are allowed, but it does not follow the usual snake_case convention |
| price$ | Invalid | Contains $ |
| my_var_123 | Valid | The number appears after the first character |
| return | Invalid | Reserved keyword |
Examples of Python naming rules and conventions
Rules and Conventions
| Category | What it means | Examples |
|---|---|---|
| Technical rule | Python requires this for the name to be accepted | Start with a letter or underscore; use only permitted characters; do not use reserved keywords |
| Style convention | Programmers prefer this because it improves readability | Use snake_case for variable names |
| Other naming conventions | Different kinds of names commonly use different patterns | PascalCase 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
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.
Choosing Between Legal Names
Choose the clearer name for a value representing a student's age.
- 1x
This name is technically legal, but it does not communicate what the value represents.
- 2student_age
This name is legal and follows
snake_case. It communicates the value's purpose immediately.
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 like3rd_attempt
Why it failsPython requires the first character to be a letter or an underscore.
Do this insteadUse a name such as third_attempt.Common mistake Using punctuation in a variable name
What it looks likeprice$ or total-cost
Why it failsSpecial characters such as $ and punctuation such as a hyphen are not allowed in variable names.
Do this insteadUse letters, numbers, and underscores, such as price or total_cost.
Common mistake Using a reserved keyword
What it looks likeclass or return
Why it failsThese words have special meanings in Python and cannot be used as variable names.
Do this insteadChoose a different name that is not a reserved keyword.
Common mistake Assuming every valid name is a good style choice
What it looks likestudentGPA
Why it failsThe name is technically valid, but it does not follow the usual
snake_caseconvention for Python variable names.Do this insteadPrefer student_gpa for an idiomatic Python variable name.
Common mistake Choosing a name that hides the value's purpose
What it looks likex or data
Why it failsGeneric names communicate little to other programmers or to your future self.
Do this insteadChoose a meaningful name such as student_age or total_revenue.
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
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_caseconvention.
- 1To 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_ageandtotal_revenuemake code easier to understand than generic names such as x or data. - Technical naming rules are enforced by Python, while conventions such as
snake_caseare preferred practices for readable code.