Variable Names
Naming Rules
Python has specific rules for variable names:
- Must start with a letter (a-z, A-Z) or underscore (_)
- Can contain letters, numbers, and underscores
- Case-sensitive (`age`, `Age`, and `AGE` are different)
- Cannot be a Python keyword (`if`, `for`, `while`, etc.)
- No special characters (!, @, #, etc.)
⚠️ Warning: Avoid single-character names except for counters or math variables.
Naming Conventions
ℹ️ Note: PEP 8 is Python's official style guide for naming conventions.
Style | Example | When to Use |
---|---|---|
snake_case | user_name | Variables, functions |
PascalCase | ClassName | Classes |
CAPS_SNAKE | MAX_SIZE | Constants |
_private | _internal_var | Non-public variables |
__dunder | __init__ | Special methods |
Good vs Bad Names
Example
# Good names
customer_count = 100
account_balance = 500.50
is_logged_in = True
# Bad names
a = 100 # What does 'a' represent?
bal = 500.50 # Abbreviation unclear
flag = True # What does this flag indicate?
Good names should:
- Clearly indicate purpose
- Be pronounceable
- Use consistent style
- Avoid abbreviations unless well-known
Special Cases
Python has some special naming scenarios:
⚠️ Warning: Avoid shadowing built-in names as it can cause subtle bugs.
Example
# Name mangling for class privates
class MyClass:
def __init__(self):
self.public = 1
self._protected = 2
self.__private = 3 # Gets renamed to _MyClass__private
# Reassigning built-in names (not recommended)
str = "Hello" # Shadows built-in str() function
list = [1,2,3] # Now can't use list() constructor