liveBook · Manning

Variable naming

As explained in Python How-To

Variable naming is the practice of choosing identifiers that clearly indicate the values or roles they represent.

Variable naming means choosing identifiers that show what values or roles they represent. Prefer names such as total_score, subject_count, and average_score over vague names like x or temp_var; readable names help others understand and maintain the code. section 1.1.1 section 2.1.3

Use variable names that make each step and its data easy to follow:

  • Name values according to their meaning or role, not their temporary storage location. section 1.1.1
  • Split complicated expressions into named intermediate values when the names clarify the computation. section 2.1.3
  • Use sensible identifiers consistently because clear names reduce the likelihood of handling the wrong data. section 2.5.3

Naming a calculation

Instead of embedding the entire calculation in formatted output, give each result a role-based name: scores = [95, 98, 97, 96, 97, 93] total_score = sum(scores) subject_count = len(scores) average_score = total_score / subject_count summary_text = f"Your Average Score: {average_score}." Each identifier tells the reader what the value represents. section 2.1.3

Listing 2.9 Using named groups to extract data
regex = re.compile(r"(?P<task_id>\d{3}), (?P<task_title>\w+); (?P<task_desc>.+)")
tasks = []
for line in text_data.split("\n"):
   match = regex.match(line)
   if match:
       task = (match.group('task_id'), match.group('task_title'), 
 match.group('task_desc'))
       tasks.append(task)

Named groups extend the same practice beyond ordinary variables: task_id, task_title, and task_desc identify extracted data more clearly than numeric group positions. section 2.5.3

How Python How-To covers it

How deep it goes
Explains naming through vague-name contrasts, calculated intermediates, and regular-expression groups, without prescribing a broader naming convention.
Examples
Uses total_score, subject_count, average_score, task_id, task_title, and task_desc as meaningful identifiers.
What it assumes
Assumes basic Python variables and identifiers while clarifying that variables are expressions evaluated to values or objects.
What you can do after
Apply it by replacing vague identifiers with names that reveal the represented data or computational role.
How it connects
Connects variable naming with readability, maintainability, f-strings, expressions, regular expressions, and data processing.

Also explained in

Compare how 3 books explain variable naming →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.