Python Variables Naming Rules and Conventions Explained
Python Variables Naming Rules
Python Tutorial > Python Variables > Python Naming Conventions > Python Variables: Naming Rules and Conventions Explained
Posted in

Python Variables: Naming Rules and Conventions Explained

Learn Python variable naming rules and conventions with clear examples. Understand identifiers vs variables, PEP 8 styles, mistakes to avoid, and best practices.

Previous Post
Python Variables: How to Create, Name, and Use Them Effectively

Introduction

What Are Identifiers in Python?

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
    pass

Types of Identifiers in Python:

Variables as a Subset of Identifiers

Difference Between Identifiers and Variables

  • variable is a storage location in memory that holds data which can change during program execution
FeatureIdentifierVariable
MeaningName given to anything in PythonIdentifier used specifically to store data
Examplesgreet, Student, math, is_validx, user_name, count
Is it mandatory for storing?NoYes
Are all variables identifiers?✔ Yes—
Are all identifiers variables?✖ No—
MutabilityCan reference mutable or immutable thingsAlways reference mutable data (values can change via reassignment)
ScopeBroader: includes functions, classes, modules, etc.Narrower: only data storage (e.g., x = 5)
LifetimePersists as long as the entity exists (e.g., function def is static)Tied to execution flow; can be garbage-collected when unreferenced
Change Over TimeIdentifiers 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 CaseNaming anything referenceableStoring temporary or persistent data during runtime
# Basic variable
counter = 0  # 'counter' holds an integer

# More complex
user_data = {"name": "Alice", "age": 30}  # Dictionary variable
user_data["age"] += 1  # Mutable content changes

Why Variable Naming Matters

x = 500
y = x * 0.18
print(y)
product_price = 500
gst_rate = 0.18
gst_amount = product_price * gst_rate
print(gst_amount)

Variable Naming Rules in Python (Mandatory Must Follow)

Rule 1: Variable names must start with a letter or underscore

my_variable = 10
_private_data = "confidential"
UserName = "Alice"
1st_number = 5   # SyntaxError: invalid decimal literal
#@invalid_char = "hello" # SyntaxError: invalid character in identifier

Rule 2: After the first character, you can use letters, numbers, and underscores

value1 = 10
user_name2 = "A"
total_3 = 300
user-name = "A"
price%off = 50

Rule 3: Variable names are case-sensitive

count = 10
Count = 20
COUNT = 30

Rule 4: Variable names cannot be Python keywords

class, def, for, while, return, pass, break, continue, True, False, None

Rule 5: Should Not Be Built-in Function Names (Strongly Recommended)

print = "This is a string"
# print("Hello") # This will now cause a TypeError!
TypeError: 'str' object is not callable

Invalid Examples:

user-name = "dash_not_allowed"  # SyntaxError
user@email = "test@test.com"    # SyntaxError  
$amount = 100                   # SyntaxError
totalNumberOfUsersWhoLoggedInToday = 55

Python Naming Conventions (Recommended by PEP 8)

# 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
    pass
# 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.75
PI = 3.14159
GRAVITY = 9.8
MAX_CONNECTION_ATTEMPTS = 5
API_BASE_URL = "https://api.example.com/v1/"
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
        pass
__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 object
# 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: Fitzgerald
d = 10
temp = 5
info = "python"
download_speed = 10
retry_limit = 5
language_name = "Python"
for i in range(10):
    print(i)
x, y, z   # unclear purpose
user_list
file_path
login_status
get_user()
insert_data()
validate_email()

Naming Suggestions in Different Contexts

user_name = "PyCoder"
city_name = "Earth"
age = 21
max_retries = 3
prices_list = [100, 200]
is_logged_in = True
has_permission = False
can_execute = True
def calculate_total():
    pass

def get_user_info():
    pass

def validate_email_format():
    pass

def send_notification():
    pass
# 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)  # Predictions

Python Naming Style Variations

file_name = "data.txt"
calculate_total()
class UserProfile:
    pass
class Example:
    def __secret(self):
        pass
__init__, __str__, __len__
user-name = "abc"   # ❌ SyntaxError

Common Naming Anti-Patterns: A “What Not to Do” Guide

1. The Peril of Vague Names

def process(data):
    val = data[0]
    info = data[1]
    # ... 50 lines of code ...
    return val * info
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_item
items = [1, 2, 3]
list = items.append(4)  # Now list() is broken!
print(list([5, 6]))    # TypeError: 'NoneType' object is not callable
item_list = [1, 2, 3]
item_list.append(4)
new_list = list(range(5))  # Built-in intact

The Worst Offenders: l, O, I

l = 1 # Is that 'l' or '1'?
O = 0 # Is that 'O' or '0'?
I = l # Is that 'I' or '1'?
index = 1
offset = 0
item_count = index

4. Keep naming consistent across files

5. Avoid abbreviations

user_name, amount, quantity
users = "PyCoder"   # confusing
user = "PyCoder"
users = ["PyCoder", "Python"]

Real-World Code Comparison

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

first-name = "PyCoder"
list = [1, 2, 3]    # Avoid!
sum = 10
is_valid = "Yes"   # should be boolean, not string
score = 100
score = "High"    # confusing

Tools and Automation for Naming Enforcement

Final Best Practices Summary

Conclusion

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

4 thoughts on “Python Variables: Naming Rules and Conventions Explained

Leave a Reply

Your email address will not be published. Required fields are marked *