In this lesson, you will learn how to choose names for your variables and functions that make your code explain itself, so you don't have to rely on extra comments to describe what is happening.
The Problem with "Clever" Names
When you write code, you might be tempted to use short names like x, d, or temp. While these are fast to type, they are a mystery to anyone else—or even to you a week later! If your code needs a comment to explain what a variable holds, that is a sign that your variable name needs an upgrade.
Consider this example:
# Poor naming
t = 25.0
c = 1.8
f = (t * c) + 32
print(f)
Looking at this, you might guess it’s a temperature conversion, but the names t, c, and f don't tell the whole story.
Making Code Self-Documenting
Self-documenting code uses descriptive, intent-revealing names. By replacing those single letters with clear, descriptive words, the logic becomes obvious at a glance:
# Self-documenting naming
celsius_temperature = 25.0
fahrenheit_conversion_factor = 1.8
fahrenheit_temperature = (celsius_temperature * fahrenheit_conversion_factor) + 32
print(f"The temperature is {fahrenheit_temperature} degrees Fahrenheit.")
Now, the code reads almost like a sentence. You don't need a comment to explain that celsius_temperature stores a measurement or that fahrenheit_temperature is the result of the calculation.
Rules of Thumb for Better Names
- Be descriptive: Use nouns for variables (e.g.,
user_ageinstead ofa). - Be active: Use verbs for functions (e.g.,
calculate_tax()instead oftax()). - Avoid redundancy: Since we already know it’s a variable, you don't need to add
varorvalto the name. - Consistency is key: If you start using
snake_case(all lowercase with underscores) as suggested by PEP 8, stick to it throughout your entire project.
When your names describe exactly what data is stored and what action is being performed, your code becomes a professional, easy-to-read tool that explains its own purpose.
Key Takeaway: Choose descriptive names that reflect the intent of your data and actions, turning your code into a clear story that requires no extra comments to understand.