When using Python, you will frequently need to name variables and functions. However, there are certain rules and best practices to follow.
Some of them are mandatory (imposed by the language), and others are simply conventions you can follow.
Let’s look at the rules and best practices for naming variables in Python.
Specific Rules
Case Sensitive: Variable names in Python are case-sensitive. For example,
variable,Variable, andVARIABLEare considered different.Name Start: The variable name must start with a letter (a-z, A-Z) or an underscore (
_). It must not start with numbers or other characters.
variable = 42
_private_variable = "Python"
1variable = "Error" # Incorrect, should not start with a number
Copied!
- Allowed Characters: Variable names can contain letters (a-z, A-Z), digits (0-9), and underscores (
_). Other special characters such as spaces, punctuation marks, or symbols are not allowed.
my_variable = "Python"
age3 = 30
my_variable@ = "Error" # Incorrect, @ symbol is not allowed
Copied!
- Reserved Words: You cannot use Python’s reserved words as variable names. For example,
if,else,for,while, among others.
if = 10 # Incorrect, if is a reserved word
my_if = 10 # Correct, adding a prefix or suffix to the reserved word
Copied!
- Readability and Meaning: It is important to choose variable names that are descriptive and reflect their use in the program’s context. This improves code readability and understanding.
total_purchases = 100
num = 100 # Less descriptive, purpose is unclear
Copied!
Style Conventions
Python’s PEP 8 (Style Guide for Python Code) suggests additional conventions to improve code readability:
- snake_case: For variable, function, and method names. For example,
my_variable,calculate_total(). - CamelCase: For class names in Python. For example,
MyClass,MySpecialClass.
# Examples of snake_case
full_name = "Luis Pérez"
calculate_total = lambda x, y: x + y
# Examples of CamelCase (for class names)
class MyClass:
def __init__(self):
self.attribute = None
Copied!
- Uppercase for constants, separated by underscores, following the style
EXAMPLE_CONSTANT.
