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

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.

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

Checking Character Positions

Determine whether each name follows the positional character rules.

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

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

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

price$: 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

accepted namesrejected namesuser_namevalid3rd_attemptstarts with a digit_private_datavalidtotal-costcontains a hyphenMAX_ATTEMPTSvalidimportreserved keyword
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

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

does not explaincommunicatesxvague namestudent_agemeaningful namestudent ageunclear from xstudent agepurpose is clear
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.

Choosing Between Legal Names

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

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

student_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

  • Starting a variable name with a digit

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

    Fix: Use a name such as third_attempt.

  • Using punctuation in a variable name

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

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

  • Using a reserved keyword

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

    Fix: Choose a different name that is not a reserved keyword.

  • Assuming every valid name is a good style choice

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

    Fix: Prefer student_gpa for an idiomatic Python variable name.

  • Choosing a name that hides the value's purpose

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

    Fix: Choose 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

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. 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.