Python Basics Tutorial 4 – Python Illegal Variable Names
Notes from the video ‘Python Course Singapore | Learn Python Programming |Python Tutorial 4 – Python Illegal Variable Names’:
Let’s first look at some variable names:
What do all of these variable names have in common?
They are all illegal variable names!
Let’s learn why these variables are illegal:
The first variable 1variable is illegal because it starts with a number. You can’t use a number or begin with a number, but you can include numbers from the second character onward. For example, the variable name variable1 is a legal variable name.
The second variable total$ is illegal because it contains $. A variable name can only contain lowercase and uppercase letters, numbers and underscores. So, you can consider changing the name to the dollar sign to the word ‘money’ instead.
The third variable “randomvariable” is illegal because variables are not enclosed by quotes. Only strings are enclosed by quotes.
The fourth variable Distance Travelled is illegal because there shouldn’t be a space between the variable name.
The last variable print is illegal because print is one of the keywords in Python. Python’s keywords define the language’s syntax rules and structure.
Although naming the variable name as one of the keywords is illegal, a variable name can contain one of the keywords. For example, numberofpagesprinted is a legal variable name but the variable name print isn’t.
Next, we will go though some of the best practices when naming your variables:
Variable names are case sensitive. For example, the variable age with a lowercase a is not the same as the variable Age with an uppercase A.
One good way to avoid remembering which keywords are in uppercase or lowercase is to name all variable names in lowercase.
Another good practice for naming variables is to make it descriptive so when you come back to the code or when someone look at your code, it’s easier to figure out what the code means.
For example, the variable name language is better than the variable name x.
Another good practice for naming variable with multiple words is to break up each word with a underscore so it’s more readable.
For example, the variable name country_of_birth is easier to read than the variable name countryofbirth.