Constants and Naming Conventions
5 min ยท The Basics
Constants in Python
Unlike some programming languages, Python doesn't have a built-in constant type that prevents values from being changed. However, Python programmers use a naming convention to indicate that certain variables should be treated as constants - values that shouldn't change during program execution.
By convention, we use SCREAMING_SNAKE_CASE (all uppercase letters with underscores) to indicate a variable is a constant. While Python won't prevent you from changing these values, other programmers will understand they shouldn't be modified.
When to Use Constants
Constants are perfect for values that are used multiple times throughout your program and shouldn't change. They make your code more maintainable:
Python Naming Conventions
Python follows specific naming conventions that make code more readable and help other programmers understand your code. These conventions are part of PEP 8, Python's official style guide:
snake_caseโ for variables and functions:my_variable,calculate_total,user_nameSCREAMING_SNAKE_CASEโ for constants:MAX_VALUE,PI,API_KEYPascalCaseโ for classes:MyClass,UserAccount,DatabaseConnection_privateโ leading underscore for internal use:_internal_var,_helper_function__special__โ double underscores for special methods (rarely used):__init__
Naming Convention Examples
Here are practical examples of each naming convention:
Reserved Keywords
Python has reserved keywords that cannot be used as variable names. These words have special meaning in Python:
โ ๏ธ Python Keywords (Cannot Use as Variables)
False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield
Best Practices for Naming
โ Good Naming Practices
โข Use descriptive names: user_age instead of x
โข Be consistent: use the same naming style throughout
โข Use meaningful abbreviations: num for number, temp for temperature
โข Avoid single letters except in loops: i, j, k for iterators
โ Naming Mistakes to Avoid
โข Too short: n, d, x - unclear what they represent
โข Too generic: data, value, temp - not specific enough
โข Using reserved keywords: if, class, def - will cause errors
โข Inconsistent casing: mixing camelCase and snake_case
Common Naming Patterns
Here are some common patterns you'll see in Python code:
Why Naming Matters
Good naming makes your code self-documenting. Compare these examples:
The second version clearly shows you're calculating a total price with tax, while the first version is cryptic.