I've been doing Leetcode problems in Python and I sometimes use numbers in my variable names for convenience, for example, acc1 or temp2. I use these for algorithms that require keeping track of more than one index like The Two Pointer Algorithm and I was wondering if this is a big no-no in Python naming conventions so I don't make a habit of it early on. The PEP 8 style guide recommends "lowercase with words separated by underscores as necessary" and it sounds like it's implicitly forbidding numbers but I'm not 100% sure and wanted to know what others thought.
In most of the languages, the regex for variables is something like /[a-zA-z_]+[a-zA-Z0-9_]*/ (but in python you can even use cyrillic letters in variables). For the tokenization reasons, a variable cannot start with a number.
Style. It's better to make easily distinguishable names for variables. In any language. Because you won't accidentally misuse a variable. It is harder to write first_acc instead of second_acc than acc1 instead of acc2. So in my opinion, in the production code use meaningful names without trying to use as little symbols as possible.
Python (and also other languages, such as C) allow numbers as part of a variable name, but not as the first character in a variable name. To me, that already shows that there is no absolute rule against numbers in variable names generally. Yes, I know, good style is not the same thing as what technically works with the interpreter or compiler, but it is an indication that numbers should not be considered as per se prohibited. The paramount rule is that variable names should be meaningful in the sense of making it clear to the reader what the variable is for and what kind of information it holds. There are many cases where including numbers in a variable name is in line with this principle. If your use case is one of these cases, go for it. Of course, things like var1 are bad style, but that's because of the non-descriptive text var, not because of the 1. In many cases, you may also be better off with an indexable data structure such as a set (temperature[0], temperature[1] etc.) instead of numbers as part of a variable name (temperature1 etc.). But I think that still leaves the possibility of legitimate use cases for numbers in variable names.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With