SyntaxError: invalid decimal literal in Python

avatar

Borislav Hadzhiev

Last updated: Apr 25, 2022

banner

Photo from Unsplash

SyntaxError: invalid decimal literal in Python #

The Python "SyntaxError: invalid decimal literal" occurs when we declare a variable with a name that starts with a digit. To solve the error, start the variable name with a letter or an underscore as variable names cannot start with numbers.

syntaxerror invalid decimal literal

Here is an example of how the error occurs.

main.py
# ⛔️ SyntaxError: invalid decimal literal 3_characters = ['a', 'b', 'c']
The error is caused because variable names cannot start with numbers in Python.

The name of a variable must start with a letter or an underscore.

One way to solve the error is to move the digits towards the end of the variable name.

main.py
characters_3 = ['a', 'b', 'c']

A variable name can contain alpha-numeric characters (a-z, A-Z, 0-9) and underscores _.

You could also name your variable something like:

main.py
three_characters = ['a', 'b', 'c']

Variable names in Python are case-sensitive.

main.py
CHARACTERS_3 = ['a', 'b', 'c'] characters_3 = ['d', 'e', 'f'] print(CHARACTERS_3) # 👉️ ['a', 'b', 'c'] print(characters_3) # 👉️ ['d', 'e', 'f']

The 2 variables in the example are completely different and are stored in different locations in memory.

The error message "invalid decimal literal" is a bit confusing.

Note that underscores can be used as the thousands separator.

main.py
my_num = 1_000 print(my_num) # 👉️ 1000

So when we declare a variable with a name such as 3_characters, Python interprets it to be a decimal literal.

Conclusion #

The Python "SyntaxError: invalid decimal literal" occurs when we declare a variable with a name that starts with a digit. To solve the error, start the variable name with a letter or an underscore as variable names cannot start with numbers.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.