Example
✅ Python Variable Naming Rules with Examples
🧩 Basic Syntax Rules:
- Start with a letter or underscore (
_):
name = "Alice"
_value = 42
- Cannot start with a number:
# 1name = "Bob" ❌ Invalid
- Can include letters, numbers, and underscores:
user1_name = "Charlie"
score_2025 = 100
- Cannot contain spaces:
# user name = "David" ❌ Invalid
user_name = "David" # ✅
- No special characters (
@,$, etc.):
# user$name = "Eve" ❌ Invalid
- Cannot use Python keywords:
# class = "Physics" ❌ Invalid
class_name = "Physics" # ✅
- Case-sensitive:
age = 25
Age = 30
print(age) # 25
print(Age) # 30
- No punctuation marks:
# price! = 50 ❌ Invalid
- Any length is allowed:
this_is_a_very_long_variable_name_for_learning_purposes = "Long but valid"
- No hyphens (
-):
# my-variable = 5 ❌ Invalid
my_variable = 5 # ✅
🧠 Best Practices Examples:
- Descriptive names:
total_price = 299.99 # ✅
tp = 299.99 # ❌ (unclear)
- Use lowercase with underscores (snake_case):
user_age = 21
- Constants in all caps (by convention):
PI = 3.14159
MAX_USERS = 100
- Avoid single-character names unless used in loops:
for i in range(5):
print(i)
- Avoid names of built-in functions:
# list = [1, 2, 3] ❌ Avoid shadowing built-in
my_list = [1, 2, 3] # ✅
- Use
_for private/internal variables:
_internal_count = 5
- Avoid double underscores unless for special methods:
class MyClass:
def __init__(self, name):
self.name = name
- Consistent naming style:
user_name = "Ali"
# Avoid mixing: userName, User_name ❌
- Avoid unclear acronyms:
user_id = 1023 # ✅
uid = 1023 # Less clear ❌
- Add comments for clarity:
monthly_payment = 1500 # Amount paid by user every month
Do it
Python naming is important because it directly affects the readability, maintainability, and clarity of your code. Clear and meaningful variable names help both the programmer and others understand what each part of the code does without needing extra comments. Proper naming reduces confusion, especially in large programs, and makes debugging easier. Following consistent naming rules and conventions, such as using snake_case for variables and avoiding reserved keywords, also helps prevent syntax errors and logical mistakes.
Snake case is a naming convention in Python (and many other programming languages) where all letters are lowercase, and words are separated by underscores (_).