In my examples, I’ve picked the general name result
, but you can choose any name you deem appropriate. As a general rule, always pick a variable name that best describes its contents. This practice makes your code more readable and easy to understand, not just for others, but also for future you. Trust me when I say that, if you read back your own code a few weeks or months later, you’ll be surprised at how much effort it requires you to grasp what’s going on.
If we were calculating the total price of a shopping cart here, for example, a good name would be shopping_cart_total
.
Don’t skimp on the number of characters in your variable names. It’s better to have clean, readable names like shopping_cart_total
instead of an abbreviation like sct
. Even total
is probably too short, because you’ll need to spend time finding of what the total is calculated. As you’ll soon learn, a good code editor auto-completes things like variable names, so you don’t have to type them in completely, if that’s what you’re worried about.
Some characters are not allowed in a variable name; there are a few rules we need to abide by. Let’s start with the complete list of valid characters that can appear in a variable name:
Additionally, there are these two rules:
Here are some valid variable names:
name_1
, name_2
, _database_connection
These are invalid names:
1tomany
(don’t start with a number)my-number
(- is not allowed)my number
(spaces are not allowed)And these variables are not the same, due to case sensitivity:
cartTotal
carttotal
This is for those that come from another programming language, like C# or Java. Many programming languages make use of camel-case to name variables. With camel-case, we use uppercase letters to more clearly separate words.
In Python, we can use camel-case, but we prefer underscores for variable names. So instead of shoppingCartTotal
, we Pythonistas use shopping_cart_total
. However, camel-case is the norm for class names. If you don’t know what that means, don’t worry, we’ll get to those later on.