Variable names in Python
A variable is simply a place in a computer’s memory that is named i.e. the variable name, and contains some information. A variable could be thought of as a box where we can put or store different types of things inside. Variables can be created and edited as much as we need in the course of performing our tasks and these variables return the value or values stored inside of it when it is called upon.
There are rules guiding naming of variables in python programming language. These rules must be adhered to when naming variables to avoid causing errors when running your code. The rules are:
Variable names should consist of only letters(a-z, A-Z), numbers(0–9) and underscores(_).
Sample variable names are: ball, Bookkeeper, _medium, Bond007, etc. Underscores should not be mistaken for hyphens(-), as they are not the same and the latter will cause an error.
It should also be noted that variable names cannot have whitespaces in its composition. Pretty obvious but worth the shout ;).
Variable names should not start with numbers
Variable names can consist of numbers anywhere except at the start of the word. Variable names like 009, 7UP, 3xperience, etc. is not accepted and will cause errors in your code.
Variable names are case sensitive
A variable name starting with a capital letter is different from the same name written in all lowercase. ‘name’ and ‘Name’ can be used to store different values in the same code, although this is not the best practice.
Reserved words
Python has some reserved words, that is, these words have been used to define the syntax and the structure of the language therefore cannot be used again in naming variables. Some examples of reserved words in python are break, if, else, continue, str, int, etc. Using these words to name a variable will throw an error. Capitalizing any of these words and using it to name a variable e.g. ‘Break’, would not throw any error although this not advised to avoid confusion.
To get the full list of keywords, type help(‘keywords’) in your command prompt as shown in the image below.
Note that you have to have python installed in your device to be able to access the keywords.
Multi words Variable names
Naming a variable with more than one word can be tricky. They might not be easy to read if not done correctly. There are several techniques to use when writing multi words variable names to make them readable. They are:
Snake case
In this case, each word is separated by an underscore. Think of the underscore as white spaces you leave after writing a word in a sentence. Example:
my_favorite_anime_character = ‘Gilgamesh’
Camel case
In this case, each word is capitalized apart from the first. Example:
myFavoriteAnimeCharacter = ‘Gilgamesh’
Pascal case
In this case, each word is capitalized including the first. Example:
MyFavoriteAnimeCharacter = ‘Gilgamesh’
Conclusion
Naming variables correctly will make your code readable and neat.
Thanks for reading :).