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
, andVARIABLE
are considered different.Name Start: The name of the variable must begin with a letter (a-z, A-Z) or an underscore (
_
). It should not start with numbers or other characters.variable = 42 _private_variable = "Python" 1variable = "Error" # Incorrect, should not start with a number
Allowed Characters: Variable names can contain letters (a-z, A-Z), digits (0-9), and underscores (
_
). Other special characters such as spaces, punctuation, or symbols are not allowed.my_variable = "Python" age3 = 30 my_variable@ = "Error" # Incorrect, @ symbol is not allowed
Reserved Words: You cannot use Python 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
Readability and Meaning: It is important to choose variable names that are descriptive and reflect their use in the context of the program. This improves the readability and understanding of the code.
total_purchases = 100 num = 100 # Less descriptive, purpose is unclear
Style Conventions
Python PEP 8 (Style Guide for Python Code) suggests additional conventions to improve code readability:
- snake_case: For variable names, functions, and methods. 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
- Uppercase for constants, separated by underscores, following the style
EXAMPLE_CONSTANT
.