Previous Post
Python Variables: How to Create, Name, and Use Them Effectively
Introduction
Variable naming may look simple—but it is one of the most important foundations of writing clean, readable, and bug-free Python code. When your names are clear, descriptive, and follow Python’s conventions, your code becomes easier to understand not just for others—but also for your future self.
In this expanded guide, you’ll learn all the rules, best practices, PEP 8 guidelines, common mistakes, naming patterns, and advanced professional tips.
We’ll also clarify the important concept of identifiers and how they relate to variables.
What Are Identifiers in Python?
Before discussing variable names, you need to understand a broader idea: identifiers.
Identifiers are names used to identify anything in a Python program, such as:
- variables
- functions
- classes
- modules
- objects
- attributes
Examples:
age = 20 # 'age' is an identifier for a variable
def greet(): # 'greet' is an identifier for a function
pass
class Student: # 'Student' is an identifier for a class
passConclusion: A variable is one type of identifier, but identifiers also include names of classes, functions, etc.
Types of Identifiers in Python:
- Variable identifiers:
age,count,total_score,user_list - Function identifiers:
greet,calculate_total(),validate_email() - Class identifiers:
Student,DatabaseConnection - Module identifiers:
math,os,custom_module
Identifiers act as “handles” or labels that the Python interpreter uses to locate and manipulate these entities in memory. Think of them as the sticky notes you put on boxes in a warehouse—they don’t contain the goods (data), but they tell you where to find them. In technical terms, identifiers are tokens in the Python lexer that map to objects in the namespace.
Variables as a Subset of Identifiers
A variable, on the other hand, is a specific type of identifier that stores data. It’s an identifier bound to a value in memory, which can change during execution. Variables are mutable references—reassigning them points to new data without changing the identifier itself.
Difference Between Identifiers and Variables
The Key Difference:
- A variable is a storage location in memory that holds data which can change during program execution
- An identifier is the name you use to refer to that variable.
See the below table for more differences:
| Feature | Identifier | Variable |
|---|---|---|
| Meaning | Name given to anything in Python | Identifier used specifically to store data |
| Examples | greet, Student, math, is_valid | x, user_name, count |
| Is it mandatory for storing? | No | Yes |
| Are all variables identifiers? | ✔ Yes | — |
| Are all identifiers variables? | ✖ No | — |
| Mutability | Can reference mutable or immutable things | Always reference mutable data (values can change via reassignment) |
| Scope | Broader: includes functions, classes, modules, etc. | Narrower: only data storage (e.g., x = 5) |
| Lifetime | Persists as long as the entity exists (e.g., function def is static) | Tied to execution flow; can be garbage-collected when unreferenced |
| Change Over Time | Identifiers stay fixed, whereas variables can change what value they point to over time. | The value it holds can be reassigned (e.g., x = 1; x = 2) or mutated (e.g., lists) |
| Common Use Case | Naming anything referenceable | Storing temporary or persistent data during runtime |
Example:
# Basic variable
counter = 0 # 'counter' holds an integer
# More complex
user_data = {"name": "Alice", "age": 30} # Dictionary variable
user_data["age"] += 1 # Mutable content changesHere, counter and user_data are both identifiers and variables because they hold changeable data. But not all identifiers are variables:
- A function name like
def greet():is an identifier but not a variable—it’s a reference to executable code, and redefining it shadows the original. - A class name like
class Car:is an identifier for a blueprint, not mutable data. - Module names (e.g.,
import sys) are identifiers pointing to loaded modules.
Common mistake: Beginners often use “variable” interchangeably with “identifier,” leading to confusion when discussing code reviews. For instance, saying “this function name is a bad variable” mixes terms. Always specify—e.g., “This variable name lacks clarity” vs. “This function identifier should follow CamelCase.”
Why Variable Naming Matters
Beginners often overlook naming, but good variable names make code:
- Readable
- Maintainable
- Self-documenting
- Easier to debug
- Easier for teams to understand
Compare this:
Bad code example:
x = 500
y = x * 0.18
print(y)What is x? What is y? What is 0.18?
Good code example:
product_price = 500
gst_rate = 0.18
gst_amount = product_price * gst_rate
print(gst_amount)Variable Naming Rules in Python (Mandatory Must Follow)
Python has strict rules that you must follow when naming variables. Violating these will raise a SyntaxError at parse time. We’ll cover each rule in detail, with expanded examples of valid and invalid names, explanations of why the rule exists, and real-world implications.
Rule 1: Variable names must start with a letter or underscore
Variable names can begin with an uppercase letter (A-Z), a lowercase letter (a-z), or an underscore (_). They cannot start with a number.
Valid Examples:
my_variable = 10
_private_data = "confidential"
UserName = "Alice"Invalid Examples:
1st_number = 5 # SyntaxError: invalid decimal literal
#@invalid_char = "hello" # SyntaxError: invalid character in identifierRule 2: After the first character, you can use letters, numbers, and underscores
Valid Examples:
value1 = 10
user_name2 = "A"
total_3 = 300Invalid Examples:
user-name = "A"
price%off = 50Rule 3: Variable names are case-sensitive
Python treats uppercase and lowercase letters as distinct. This allows flexibility but demands consistency to avoid subtle bugs.
count = 10
Count = 20
COUNT = 30All three are different.
Rule 4: Variable names cannot be Python keywords
Python has 35+ reserved words (e.g., if, for, class) that are part of the language syntax. Using them as variable names triggers a SyntaxError.
Keywords are reserved words like:
class, def, for, while, return, pass, break, continue, True, False, NoneInvalid Examples:
class = 5Valid Examples:
class_num = 5Rule 5: Should Not Be Built-in Function Names (Strongly Recommended)
It’s highly discouraged to use the names of Python’s built-in functions (like print, input, len, sum) as variable names. Doing so will override the original function, making it unusable in that scope.
Example of what NOT to do:
print = "This is a string"
# print("Hello") # This will now cause a TypeError!- Here,
printis a valid identifier according to the naming rules (starts with a letter, no spaces, no special characters). - But
printis also the name of a built-in function in Python. - When you assign a value to
print, you shadow (override) the built-in function. - So Python now treats
printas a string variable, not a function.
That’s why calling:
print("Hello")Causes:
TypeError: 'str' object is not callableBecause Python tries to call the string "This is a string" as if it were a function.
Rule 6: No spaces allowed
You cannot use a space in a variable name.
Invalid Examples:
user name = "PyCoder"Valid Examples:
user_name = "PyCoder"Rule 7: No special characters allowed
Not Allowed: Special characters like @, #, $, %, &, *, -
Invalid Examples:
user-name = "dash_not_allowed" # SyntaxError
user@email = "test@test.com" # SyntaxError
$amount = 100 # SyntaxErrorRule 8: Name must be meaningful and not overly long
Even though Python allows long names, avoid excessive length.
Bad Example:
totalNumberOfUsersWhoLoggedInToday = 55Good Example:
logged_in_users = 55Python Naming Conventions (Recommended by PEP 8)
If the rules are the “laws,” then the conventions are the “etiquette.” They are not enforced by the interpreter, but they are critically important for writing clean, professional, and collaborative code. These conventions are defined in Python’s official style guide, PEP 8.
Following PEP 8 makes your code instantly recognizable and easy to read for any other Python developer.
1. Variable and Function Names: snake_case
For regular variables and functions, the convention is to use all lowercase letters with underscores (_) to separate words. This is known as “snake_case.”
Good Example:
# Variables
user_name = "charlie"
account_balance = 1050.75
is_logged_in = True
# Functions
def calculate_area(length, width):
return length * width
def get_user_data(user_id):
# ... function logic
passBad (Non-Pythonic) Examples:
# camelCase (common in JavaScript/Java, but not Python)
userName = "charlie"
calculateArea(l, w)
# PascalCase (reserved for Classes)
UserName = "charlie"
# All one word (hard to read for long names)
accountbalance = 1050.752. Constant Names: UPPER_SNAKE_CASE
Python does not have true constants like other languages (e.g., const in JavaScript). However, there is a strong convention to indicate that a variable is intended to be a constant and should not be changed.
Write these names in all uppercase letters with underscores separating words.
Good Examples:
PI = 3.14159
GRAVITY = 9.8
MAX_CONNECTION_ATTEMPTS = 5
API_BASE_URL = "https://api.example.com/v1/"By using this convention, you signal to other developers (and yourself) that these values are meant to be configuration settings or fixed values.
3. “Private” Internal Variables: _leading_underscore
If you have a variable in a class or module that is intended for internal use and should not be accessed from outside, you can prefix it with a single leading underscore.
This is a strong convention, but it’s important to understand that Python does not enforce this privacy. It’s more of a signal to other developers: “You probably shouldn’t touch this, as it might change in the future.”
class ApiClient:
def __init__(self, api_key):
self.api_key = api_key
self._internal_cache = {} # Intended for internal use only
def _make_request(self, endpoint):
# An internal helper method
pass4. Special “Magic” Variables: __dunder_variables__
You will often see identifiers with double leading and trailing underscores. These are called “dunder” (double underscore) variables or methods. They have special meaning to Python and are part of the language’s data model.
You should not invent your own dunder (double-underscore) names. Use them only when Python already defines their purpose.
__name__ # A special variable that indicates the context of a module's execution
__init__ # The initializer method for a class
__str__ # The method to get a user-friendly string representation of an object5. Single Underscore for Unused Variables
When writing code (especially loops or tuple unpacking) where the syntax requires a variable but the value of that variable will be intentionally ignored, it’s conventional to use a single underscore (_) as a throwaway name.
# Iterating 5 times, but we don't need the loop counter
for _ in range(5):
print("Hello!")
# Unpacking a tuple where we only need the middle value
_, middle_name, _ = ("John", "Fitzgerald", "Kennedy")
print(middle_name) # Output: Fitzgerald6. Use Descriptive, Meaningful Names
Choose names that describe the variable’s purpose and content.
Bad Example:
d = 10
temp = 5
info = "python"Good Example:
download_speed = 10
retry_limit = 5
language_name = "Python"7. Avoid one-letter names except for loop counters
Single letters are acceptable in specific contexts.
Valid usages:
for i in range(10):
print(i)Avoid:
x, y, z # unclear purpose8. Use nouns for variables, verbs for functions
Variables:
user_list
file_path
login_statusFunctions:
get_user()
insert_data()
validate_email()Naming Suggestions in Different Contexts
Naming For strings
user_name = "PyCoder"
city_name = "Earth"Naming For numbers
age = 21
max_retries = 3Naming For Lists
prices_list = [100, 200]Naming For booleans
is_logged_in = True
has_permission = False
can_execute = TrueNaming For Function and Method
def calculate_total():
pass
def get_user_info():
pass
def validate_email_format():
pass
def send_notification():
passNaming For Data Science/Machine Learning
# Common conventions in ML:
X = features_matrix # Capital X for feature matrix
y = target_values # Lowercase y for target
X_train, X_test = split # Training and test sets
y_pred = model.predict(X) # PredictionsPython Naming Style Variations
When writing Python code, you’ll encounter several naming “cases” used across variables, functions, classes, and constants. Although Python technically allows many styles, PEP 8 recommends specific ones to keep your code clean, readable, and consistent. Understanding these naming styles helps you choose the right form for the right purpose and avoid patterns that look un-Pythonic or confusing.
1. snake_case (PEP 8 Recommended)
Used for variables, functions, and methods.
file_name = "data.txt"
calculate_total()2. PascalCase (PEP 8 Recommended for Classes)
Used only for class names.
class UserProfile:
pass3. camelCase (Allowed but Not Pythonic)
Common in Java/JavaScript, rarely used in Python.
userName = "charlie"4. SCREAMING_SNAKE_CASE (Constants)
Used for module-level constants.
MAX_RETRIES = 55. single_leading_underscore (Internal/Private)
Signals “internal use” or “not part of the public API.”
_internal_value = 106. double_leading_underscore (Name Mangling)
Triggers name mangling inside classes to protect internal attributes.
class Example:
def __secret(self):
pass7. double_underscore_prefix_and_suffix (Dunder Methods)
Reserved for Python’s special methods — do not create your own.
__init__, __str__, __len__8. UPPERCASE (Rare Alternative for Constants)
Sometimes used, but SCREAMING_SNAKE_CASE is preferred.
PI = 3.149. kebab-case (Not Allowed)
Invalid for variables because - is the subtraction operator.
user-name = "abc" # ❌ SyntaxError10. Mixed Styles (Allowed but Unclean)
Technically valid, but not recommended.
user_Name = "abc"Common Naming Anti-Patterns: A “What Not to Do” Guide
1. The Peril of Vague Names
Names like data, info, val, process, or handle are the junk food of variable naming. They might seem easy in the moment, but they provide zero nutritional value to the next person who reads your code.
def process(data):
val = data[0]
info = data[1]
# ... 50 lines of code ...
return val * infoWhat does process do? What is data? What is the relationship between val and info? You have to read the entire function to find out.
def calculate_total_price(items_in_cart):
price_of_first_item = items_in_cart[0]
quantity_of_first_item = items_in_cart[1]
# ... 50 lines of code ...
return price_of_first_item * quantity_of_first_itemNow, the function’s purpose and the variables’ roles are crystal clear.
2. Don’t Shadow the Built-ins
Python comes with a rich set of built-in functions and types (list, dict, str, sum, max, etc.). Using these names for your variables is called “shadowing,” and it can lead to confusing and hard-to-debug errors.
Bad Example:
items = [1, 2, 3]
list = items.append(4) # Now list() is broken!
print(list([5, 6])) # TypeError: 'NoneType' object is not callableGood Fix:
item_list = [1, 2, 3]
item_list.append(4)
new_list = list(range(5)) # Built-in intact3. The Danger of Ambiguous Single-Letter Names
While single-letter variables are acceptable for loop counters (i, j, k) or mathematical coordinates (x, y), some letters should be avoided at all costs.
The Worst Offenders: l, O, I
In many fonts, these letters are indistinguishable from the numbers 1 and 0.
Bad Example:
l = 1 # Is that 'l' or '1'?
O = 0 # Is that 'O' or '0'?
I = l # Is that 'I' or '1'?Reading this code is a nightmare. It forces the reader to stop and decipher characters, completely breaking their flow.
Good Example:
index = 1
offset = 0
item_count = indexBe explicit. Your future self, who is debugging this code at 2 AM, will thank you.
4. Keep naming consistent across files
If you use user_name somewhere, don’t use username in another place.
5. Avoid abbreviations
Bad Example:
usrnm, amt, qtyGood Example:
user_name, amount, quantity6. Avoid plurals confusion
Bad Example:
users = "PyCoder" # confusingGood Example:
user = "PyCoder"
users = ["PyCoder", "Python"]Real-World Code Comparison
Before (Poor Naming):
def p(d):
t = 0
for i in d:
t += i
return t / len(d)
data = [10, 20, 30, 40]
result = p(data)
print(result)After (Good Naming):
def calculate_average(numbers):
total = 0
for number in numbers:
total += number
return total / len(numbers)
test_scores = [10, 20, 30, 40]
average_score = calculate_average(test_scores)
print(f"Average score: {average_score}")Common Beginner Mistakes
Mistake 1: Using hyphens instead of underscores
first-name = "PyCoder"Mistake 2: Using confusing or unclear names
data1 = 10
data2 = 20Mistake 3: Using reserved keywords as variables
for = 10 # ErrorMistake 4: Overwriting built-in names
list = [1, 2, 3] # Avoid!
sum = 10Mistake 5: Using misleading names
is_valid = "Yes" # should be boolean, not stringMistake 6: Reusing the same variable for different types
score = 100
score = "High" # confusingTools and Automation for Naming Enforcement
Here are some tools that can help check variable naming conventions:
- Linters: pylint, flake8—flag violations.
- Formatters: black—auto-applies snake_case.
- Static Analyzers: mypy for type hints, influencing names (e.g., List[int] vars).
IDE Integration: Most modern IDEs (PyCharm, VSCode, etc.) will:
- Highlight naming convention violations
- Suggest better variable names
- Warn about shadowing built-in names
Final Best Practices Summary
- Start with letters or underscores
- Follow snake_case for variables and functions
- Use meaningful names
- Use UPPER_SNAKE_CASE for constants
- Use booleans with is_/has_ prefixes
- Avoid abbreviation and confusion
- Follow PEP 8
- Avoid overwriting built-in names
- Keep names consistent
- Variables should make code self-explanatory
Conclusion
Variable naming is a simple skill on the surface—but mastering it can dramatically improve the quality of your Python code. By following Python’s rules, PEP 8 guidelines, and professional naming practices, you make your code clean, readable, and maintainable.
And always remember:
Variables are identifiers—but identifiers also include classes, functions, and more.
Next Post
Python Variables: Assigning Multiple Values And Unpacking Collections
Suggested Posts
1. Python Variables: How to Create, Name, and Use Them Effectively
2. Python Variables: Assigning Multiple Values And Unpacking Collections
3. Python Variables: The Complete Frequently Asked Questions (FAQ) Guide

Nice and friendly explanation of identifiers vs variables and the PEP 8 conventions with clear examples. It really helps me understand proper naming.