upgrade
upgrade

🐍Intro to Python Programming

Python Variable Naming Conventions

Study smarter with Fiveable

Get study guides, practice questions, and cheatsheets for all your subjects. Join 500,000+ students with a 96% pass rate.

Get Started

Why This Matters

Variable naming might seem like a minor detail, but it's one of the first things that separates readable, professional code from confusing spaghetti. You're being tested on your ability to write code that works and code that communicates—naming conventions directly impact both. Understanding these rules helps you avoid frustrating syntax errors, collaborate effectively with other programmers, and write self-documenting code that you'll actually understand when you revisit it weeks later.

These conventions connect to broader programming principles: code readability, maintainability, debugging efficiency, and community standards. Python's philosophy emphasizes that "readability counts" (it's literally in the Zen of Python), and naming conventions are your first tool for achieving that. Don't just memorize the rules—understand why each convention exists and when to apply it. That's what separates coders who can answer exam questions from programmers who can build real projects.


Syntax Rules: What Python Actually Requires

These aren't suggestions—they're enforced by the Python interpreter. Break these rules and your code won't run at all.

Start with a Letter or Underscore

  • Valid starting characters are letters (a-z, A-Z) or underscores (_)—numbers at the start will crash your code immediately
  • Syntax errors occur when you try names like 2fast or 99problems; Python's interpreter can't parse them
  • The underscore prefix has special meaning in Python—single underscore suggests "internal use," double underscore triggers name mangling in classes

Avoid Special Characters

  • Only letters, numbers, and underscores are permitted in variable names—no exceptions
  • Characters like @, #, $, and % serve other purposes in Python and will trigger syntax errors if used in names
  • Hyphens (-) are especially tricky because Python interprets them as minus signs, turning my-variable into a subtraction operation

Don't Use Reserved Keywords

  • Python reserves 35 keywords like if, for, while, class, and return that cannot be used as variable names
  • Using keywords causes unpredictable behavior—sometimes errors, sometimes silent bugs that are harder to track down
  • Check keywords with import keyword; print(keyword.kwlist) to see the complete list in your Python version

Compare: Starting with a number vs. using a keyword—both cause errors, but number-starts fail immediately at parsing while keyword conflicts may produce confusing error messages. If debugging a "why won't this run" question, check both.


Style Conventions: What the Community Expects

These won't break your code, but they'll make experienced Python developers cringe—and cost you points on style-focused assessments.

Use Lowercase with Underscores (snake_case)

  • snake_case is Python's standard for variables and functions—write user_name not userName or UserName
  • Underscores improve readability by creating visual separation between words, especially in longer names like total_monthly_revenue
  • This distinguishes variables from classes, which use CamelCase—mixing them up signals inexperience to code reviewers

Use SCREAMING_SNAKE_CASE for Constants

  • All uppercase with underscores signals immutability—names like MAX_CONNECTIONS or API_TIMEOUT tell other programmers "don't change this"
  • Python doesn't enforce constants technically, but this convention creates a strong social contract in codebases
  • Place constants at module level (top of your file) so they're easy to find and modify in one location

Use CamelCase for Class Names

  • Each word starts with a capital letter with no separators—StudentRecord, HttpConnection, GameCharacter
  • This visual distinction lets you instantly identify classes versus variables and functions in code
  • Acronyms in class names typically stay uppercase: HTTPServer rather than HttpServer (though both appear in practice)

Compare: user_score (variable) vs. USER_SCORE (constant) vs. UserScore (class)—same words, completely different meanings. Exam questions love testing whether you can identify what type of identifier each represents.


Readability Principles: What Makes Code Self-Documenting

These conventions separate code that merely works from code that communicates intent clearly.

Choose Descriptive, Meaningful Names

  • Names should reveal purposecustomer_email beats ce, and calculate_tax() beats do_stuff()
  • Self-documenting code reduces comment clutter because the names themselves explain what's happening
  • Context matters: temp is fine for a temporary swap variable but terrible for storing temperature data

Avoid Single-Letter Names (Usually)

  • Loop counters are the exceptioni, j, k are universally understood in for i in range(10) contexts
  • Mathematical code sometimes warrants single letters when mimicking formulas: y = m * x + b is clearer than result = slope * input_value + intercept
  • Short-lived variables in comprehensions can use brief names, but anything that persists deserves description

Follow PEP 8 Consistently

  • PEP 8 is Python's official style guide—it's not optional in professional settings or graded assessments
  • Consistency trumps personal preference—a codebase mixing camelCase and snake_case is harder to read than either alone
  • Tools like pylint and flake8 automatically check PEP 8 compliance, catching naming issues before submission

Compare: x = 5 in a loop vs. x = 5 storing a user's age—identical syntax, completely different appropriateness. The key question: "Will someone reading this code (including future you) immediately understand what this variable holds?"


Quick Reference Table

ConceptBest Examples
Valid syntax startersLetters (a-z, A-Z), underscore (_)
snake_case variablesuser_name, total_count, is_valid
CONSTANT namingMAX_SIZE, DEFAULT_TIMEOUT, PI
CamelCase classesStudentRecord, GameEngine, HttpRequest
Acceptable single lettersi, j, k (loops), x, y (coordinates/math)
Reserved keywords to avoidif, for, while, class, return, import
Forbidden characters@, #, $, %, -, spaces
Style guide referencePEP 8

Self-Check Questions

  1. You see three identifiers: user_data, USER_DATA, and UserData. What type of Python element (variable, constant, or class) does each naming convention suggest?

  2. Why would 2nd_place cause a syntax error while second_place works fine? What's the underlying rule?

  3. Compare calculate_average(numbers) versus calc(n). Which follows Python conventions better, and what readability principle does this demonstrate?

  4. A classmate names their loop counter current_iteration_index instead of i. Is this technically wrong? What would you advise them and why?

  5. FRQ-style: Given a program tracking student grades, propose appropriate variable names for: (a) a single test score, (b) a constant representing the maximum possible score, and (c) a class representing a student. Explain which naming convention applies to each.