leafleafleafDocy banner shape 01Docy banner shape 02Man illustrationFlower illustration

Python variable naming rules

Estimated reading: 2 minutes 88 views
Python variable naming rules

Variable names can include letters, numbers, and underscores, but numbers cannot start variables. For example, name1 is a legal variable name, but 1name is not, as follows:

>>> name1 = 5
>>> 1name = 3

SyntaxError. invalid syntaxWe can see that when there is a problem with the variable name, a red error message “SyntaxError: invalid syntax” will appear, which means a syntax error has occurred. Python variable names are case-sensitive, for example, name and Name are treated as two different variables, not the same variable.

As you can see below, the content in the variable name is “John” and the content in the variable Name is “Johnson”, which are two different quantities.

>>> name="John"
>>> Name="Johnson"
>>> name
'John'
>>> Name
Johnson'

Also, do not use Python keywords and functions as variable names. For example, if we use the keyword if as a variable and assign a value to it, the system will report an error directly.

>>> if = 3
SyntaxError. invalid syntax

Tip: When the interpreter loads the context, if it encounters some preset variable values, it will trigger some built-in operations of the interpreter. These preset variable values ​​are keywords.

Variable names cannot contain spaces, but underscores can be used to separate words within them. For example, the variable name greeting_message is OK, but the variable name greeting message raises an error.

>>> greeting_message="Hello"
>>> greeting message="Hello"
SyntaxError.invalid syntax


To summarize the naming rules for Python variables:

  • Variable names can consist of letters, numbers and underscores, but cannot start with a number;
  • Variables cannot have the same name as keywords;
  • Variable names are case-sensitive;
  • Variable names cannot contain spaces, but underscores can be used to separate words within them.

Usually, we’re used to variables starting with a small letter and capitalizing the first letter of all words except the first, like numberOfCandies.

In addition to the above variable naming methods, camel spelling is also commonly used. Just capitalize the first letter of each word, just like NumberOfCandies. This spelling is called camel spelling because it looks a bit like the hump of a camel, as shown in the image below.

python variable camel case
python variable camel case
CONTENTS