Correct Notation for Naming Variables in Python

When writing Python code, choosing the right variable names is crucial for readability, maintainability, and consistency. Python follows specific rules and conventions for naming variables, and adhering to these guidelines will make your code easier to understand and work with.

Rules for Naming Variables in Python

Before diving into examples, let’s go over the official rules for variable naming in Python. These rules are defined by the Python language syntax and must be followed, or else you’ll get a syntax error.

  1. Variables must start with a letter (a-z, A-Z) or an underscore (_). You cannot start a variable name with a number or any special character like @, #, or $.
  • Valid: my_variable, _counter, data2
  • Invalid: 2data, @var, -count

2. Subsequent characters can be letters, numbers, or underscores. After the first character, the name can include digits and underscores.

  • Valid: price1, data_23, name_
  • Invalid: var@name, a-b

3. Variable names are case-sensitive. This means that name and Name are considered two different variables in Python.

  • Example: data = 5 is different from Data = 10.

Reserved words (keywords) cannot be used as variable names. Python has a list of keywords that are reserved for special functions, like if, else, for, while, etc. You cannot use these as variable names.

  • Invalid: if = 5, class = "Math"

    You can check Python’s reserved keywords using this snippet:

    import keyword
    print(keyword.kwlist)
    

    Conventions for Naming Variables in Python

    In addition to the basic rules, Python has naming conventions that help make code more readable. These conventions aren’t strictly enforced, but they are widely followed to maintain consistency and readability in Python codebases.

    1. Snake Case (lower_case_with_underscores): This is the most commonly used convention in Python. Variable names are written in all lowercase, with words separated by underscores for readability.
      • Example: total_price, student_name, num_of_items
    2. Avoid Single-Letter Variables (Unless in Specific Contexts): While it’s tempting to use single-letter variables like x, y, or z, they should generally be avoided, except in small loops or mathematical expressions where they are commonly understood.
      • Avoid: a = 10, b = 20
      • Instead, use: length = 10, width = 20
    3. Descriptive Variable Names: Use meaningful, descriptive names that clearly indicate the purpose of the variable. This makes your code more readable and understandable, even to others.
      • Instead of: a = 10, b = 20
      • Use: length = 10, width = 20
    4. Constants in All Caps: If you are defining a constant (a variable whose value will not change), use uppercase letters separated by underscores.
      • Example: PI = 3.14159, MAX_SIZE = 100
    5. Private Variables (Single Leading Underscore): By convention, a single leading underscore in a variable name (e.g., _var) indicates that it is intended for internal use within a module or class, though it’s not strictly private.
      • Example: _internal_counter, _cache
    6. Name Mangling for Class Variables (Double Leading Underscore): If you use two leading underscores (__var), Python performs name mangling, where the interpreter changes the variable’s name to prevent accidental access from outside the class. This is mainly used for class variables.
      • Example: __private_var

    Coding Examples

    Now, let’s go through several coding examples to see these rules and conventions in action.

    Example 1: Valid and Invalid Variable Names
    # Valid variable names
    username = "Swarna"
    age = 25
    is_student = True
    total_price = 150.75
    
    # Invalid variable names (will raise syntax errors)
    # 2name = "John"  # Cannot start with a digit
    # my-name = "Doe"  # Hyphen is not allowed
    # class = "Python"  # 'class' is a reserved keyword
    

    Explanation:

    • username, age, is_student, and total_price follow the correct naming rules.
    • 2name, my-name, and class violate the rules of variable naming in Python.
    Example 2: Snake Case Convention
    # Snake case variable names
    first_name = "Khushbu"
    last_name = "Sharma"
    total_items_sold = 100
    price_per_item = 5.99
    

    Explanation:

    • Here, all variables are named using the snake case convention, which is preferred in Python for readability.
    Example 3: Constants in Python
    # Constants
    PI = 3.14159
    MAX_USERS = 500
    MIN_PASSWORD_LENGTH = 8
    
    # Use of constants
    radius = 5
    area = PI * radius ** 2  # Using constant PI for area calculation
    

    xplanation:

    • PI, MAX_USERS, and MIN_PASSWORD_LENGTH are constants, and by convention, they are written in all caps.
    Example 4: Case-Sensitive Variables
    # Case-sensitive variables
    counter = 10
    Counter = 20
    
    print(counter)  # Output: 10
    print(Counter)  # Output: 20
    

    Explanation:

    • counter and Counter are two different variables due to Python’s case sensitivity. Changing the case of a letter makes it a completely different variable.
    Example 5: Private Variables with a Single Underscore
    class Student:
        def __init__(self, name, age):
            self.name = name
            self._age = age  # Intended to be a private variable
    
        def display_info(self):
            print(f"Name: {self.name}, Age: {self._age}")
    
    student = Student("John", 21)
    student.display_info()  # Output: Name: John, Age: 21
    

    Explanation:

    • _age is intended as a private variable, which is indicated by the leading underscore. This is a convention, not enforced by Python.
    Example 6: Name Mangling with Double Underscore
    class BankAccount:
        def __init__(self, balance):
            self.__balance = balance  # Name mangling
    
        def get_balance(self):
            return self.__balance
    
    account = BankAccount(1000)
    print(account.get_balance())  # Output: 1000
    # print(account.__balance)  # Will raise an AttributeError due to name mangling
    

    Explanation:

    • __balance is a variable that is name-mangled by Python to avoid being accessed directly from outside the class. Attempting to access it as account.__balance will result in an error.

    Best Practices for Variable Naming

    • Be Consistent: Always stick to one naming convention throughout your code. For Python, it’s typically snake case.
    • Keep It Descriptive: Variable names should reflect the purpose of the variable.
    • Avoid Reserved Words: Make sure you aren’t using reserved keywords for variable names.
    • Follow Conventions: Although Python allows flexibility in naming, adhering to conventions helps maintain readable and consistent code.

    Conclusion

    Understanding the correct notation for naming variables in Python is essential for writing clean, readable, and maintainable code. By adhering to Python’s rules and conventions, you create a structure that not only avoids errors but also improves the clarity of your code. Starting variable names with letters or underscores, avoiding reserved keywords, and respecting case sensitivity are fundamental aspects of variable naming that ensure your code adheres to Python’s syntax rules.

    Using conventions such as snake case for variable names and uppercase for constants further enhances code readability and consistency. Descriptive variable names allow others (or even yourself when revisiting the code later) to easily understand the purpose of each variable, reducing confusion and errors in larger projects. Moreover, adopting conventions like single and double leading underscores for internal and private variables helps signal intent, especially when working in object-oriented programming contexts.

    Name mangling, while not frequently used, is an additional tool Python provides to prevent accidental modification of class attributes from outside the class, giving you control over class design and protecting essential variables. By following these practices and naming conventions, you create more intuitive, maintainable, and reliable codebases that can be understood and managed by teams of developers.

    In summary, proper variable naming is about more than just following rules—it’s about writing code that’s easy to understand, modify, and collaborate on. By consistently applying Python’s naming standards and best practices, you enhance the overall quality of your projects, making them easier to debug, extend, and share with others in the Python community.

    Author

    Sona Avatar

    Written by

    Leave a Reply

    Trending

    CodeMagnet

    Your Magnetic Resource, For Coding Brilliance

    Programming Languages

    Web Development

    Data Science and Visualization

    Career Section

    <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
         crossorigin="anonymous"></script>