Language: EN

convenciones-nombres-en-python

Rules for naming variables in Python

During the use of 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), while others are simply conventions you can adhere to.

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, and VARIABLE are considered different.

  • Name Start: The variable name must start with a letter (a-z, A-Z) or an underscore (_). It should not begin with numbers or other characters.

    variable = 42
    _private_variable = "Python"
    1variable = "Error"  # Incorrect, cannot 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 marks, or symbols are not allowed.

    my_variable = "Python"
    age3 = 30
    my_variable@ = "Error"  # Incorrect, @ symbol is not allowed
  • Reserved Words: Reserved words in Python cannot be used as variable names. For example, if, else, for, while, among others.

    if = 10  # Incorrect, if is a reserved word
    my_if = 10  # Correct, adding 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 = "Juan 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.

  • Consistency: Maintain consistency in the choice of variable names throughout the code and among different collaborators in a project.