Writing Meaningful Variables and Why It Matters
This article is a complementary resource to the Learn Python Basics course.
This article is a complementary resource to the Learn Python Basics course.
As you know, a variable is a container for storing data that can change during program execution. For example:
temp = 5
Here, temp could represent anything—temperature, a temporary value, or something else.
While it may be clear when you're writing the code, it can become confusing when someone else reads it (or when you return to it after a few weeks).
Let's explore why it's so important and how to name variables effectively.
Good variable names improve readability, maintainability, and help avoid confusion.
When names are descriptive, they instantly convey what the variable represents, making it easier for others to understand and modify the code.
Good Names:
item_price = 50
tax_rate = 0.07
total_price = item_price + (item_price * tax_rate)
Bad Names:
x = 50
y = 0.07
z = x + (x * y)
It's not clear what x, y, or z represent. Clear names reduce confusion, especially as your project grows.
Be Descriptive
Use names that describe what the variable holds (e.g., student_name, purchase_amount).
Keep It Concise
While being descriptive is important, you should also try to keep variable names concise. Avoid excessively long names.
# Good
student_name
# Bad
student_full_name_for_registration_purposes
Avoid Abbreviations
Using abbreviations can make variable names harder to understand. For example:
# Good
first_name = "John"
count = 5
# Bad
fn = "John"
cnt = 5
Avoid Reserved Words
Don't use Python's reserved keywords like
class
,
sum
, or
all
as variable names.
Note: It's okay if you don't know all reserved words yet—just make sure to avoid the ones you do know.
Naming conventions help keep code consistent and readable. Choose a naming convention and stick with it:
Choose a convention that fits your language or team standards, and stick with it consistently.
Booleans:
Use names indicating true/false values:
is_active = True
can_edit = False
Counters:
Variables that act as counters should be named counter or index:
index = 0
counter = 5
Collections:
For lists or other collections, use plural names:
scores = [90, 80, 85]
users_list = ["John", "Jane", "Doe"]
Note: If you are unfamiliar with collections, they are variables that store more than one value. We've covered this in detail in Chapter 4 of our course.
Choosing meaningful variable names is essential for making your code:
Clarity in naming is a small effort that pays off in the long run, making your code more understandable for you and others.