🐍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.
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
2fastor99problems; 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-variableinto a subtraction operation
Don't Use Reserved Keywords
- Python reserves 35 keywords like
if,for,while,class, andreturnthat 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_namenotuserNameorUserName - 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_CONNECTIONSorAPI_TIMEOUTtell 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:
HTTPServerrather thanHttpServer(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 purpose—
customer_emailbeatsce, andcalculate_tax()beatsdo_stuff() - Self-documenting code reduces comment clutter because the names themselves explain what's happening
- Context matters:
tempis fine for a temporary swap variable but terrible for storing temperature data
Avoid Single-Letter Names (Usually)
- Loop counters are the exception—
i,j,kare universally understood infor i in range(10)contexts - Mathematical code sometimes warrants single letters when mimicking formulas:
y = m * x + bis clearer thanresult = 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
camelCaseandsnake_caseis harder to read than either alone - Tools like
pylintandflake8automatically 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
| Concept | Best Examples |
|---|---|
| Valid syntax starters | Letters (a-z, A-Z), underscore (_) |
| snake_case variables | user_name, total_count, is_valid |
| CONSTANT naming | MAX_SIZE, DEFAULT_TIMEOUT, PI |
| CamelCase classes | StudentRecord, GameEngine, HttpRequest |
| Acceptable single letters | i, j, k (loops), x, y (coordinates/math) |
| Reserved keywords to avoid | if, for, while, class, return, import |
| Forbidden characters | @, #, $$, %, -, spaces |
| Style guide reference | PEP 8 |
Self-Check Questions
-
You see three identifiers:
user_data,USER_DATA, andUserData. What type of Python element (variable, constant, or class) does each naming convention suggest? -
Why would
2nd_placecause a syntax error whilesecond_placeworks fine? What's the underlying rule? -
Compare
calculate_average(numbers)versuscalc(n). Which follows Python conventions better, and what readability principle does this demonstrate? -
A classmate names their loop counter
current_iteration_indexinstead ofi. Is this technically wrong? What would you advise them and why? -
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.