In Python, we can name a variable almost whatever we want. There are a few rules though:
_
)This still leaves us with a lot of options when naming a variable. However, not all options are equally good!
As a general rule, you should try to name your variables in a meaningful, yet succinct manner. For example, let's take a look at the following code:
ucst = 2.99 q = 20 T = q * uprc
Looking at the code snippet above, does this make immediate sense to you? It is hard to understand what each variable represents, and even though the calculation is simple, we can't immediately tell what is the purpose of the code.
Now let's look at another version of the code above, but now with the variables named in a more user friendly way:
unit_cost = 2.99 quantity = 20 total_cost = quantity * unit_cost
This is much easier to understand: while the calculations are the same, we now understand that the purpose of the code is to calculate the total cost based on a quantity and a unit cost.
In addition to this principle, there are Python specific conventions on how to name different types of variables. These are not critical to understand at this stage, but a safe approach
is to name your variables using lowercase letters, with different words separated by an underscore _
(for example, unit_cost
).