variables

Variables are the names that you use to refer to data and objects in your programs. How you choose and use those names has a big impact on your code’s readability and how easy the code is to reason about.

Descriptive, stable variable names help you track state through your code. In contrast, careless name reuse or type changes can quickly turn into confusing and buggy code.

When working with variables, these best practices can improve clarity and maintainability:

  • Follow PEP 8 naming conventions for variables. Use snake_case for regular variables. Following common Python naming conventions makes your intent clear to others when they read your code. See the recommendations in PEP 8.
  • Use descriptive, unambiguous names. Favor descriptive names that clearly communicate the intent of your variables. This practice will make your code more readable, clearer, and easier to reason about.
  • Avoid single-letter names and abbreviations unless they’re common practice. Use full names for your variables rather than single-letter names or abbreviated names, unless they’re commonly used, such as x and y to represent coordinates.
  • Keep variable types stable. Avoid reusing the same variable name for values of different types, such as storing a number first and then a string. Stable types make your code easier to follow, reduce surprising behaviors, and prevent type-related errors.
  • Limit variable scope and avoid global state. Prefer local variables inside functions and methods, and pass values explicitly instead of relying on global variables for shared state. Overusing globals often leads to code that’s harder to understand, debug, and test.

To see some of these ideas in action, consider the following code example:

🔴 Avoid this:

Python
def summarize_sales(rows):
    total = 0
    for row in rows:
        total += row["amount"]

    total = f"${total:,.2f}"  # Change the type
    return total

This function works, but total changes type partway through the function. The variable name also doesn’t match well what the value actually holds.

Favor this:

Python
def summarize_sales(rows):
    total_sales = sum(row["amount"] for row in rows)
    formatted_total = f"${total_sales:,.2f}"
    return formatted_total

In this version, each name matches the value it holds, and both variables keep a stable type during the function execution. You also use the built-in sum() to make clearer what operation is taking place.

Tutorial

Variables in Python: Usage and Best Practices

In this tutorial, you'll learn how to use symbolic names called variables to refer to Python objects, and gain an understanding of how to effectively use these fundamental building blocks in your code to store, manipulate, and retrieve data.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Feb. 3, 2026