SyntaxError: invalid decimal literal in Python [Solved]

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
2 min

banner

# 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'] # ⛔️ SyntaxError: invalid decimal literal def 2_characters(): return ['a', 'b']

variable name starts with integer

The error is caused because variable and function names cannot start with numbers in Python.

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

Literals in Python are values such as numbers, strings and booleans.

main.py
a_str = 'bobbyhadz.com' an_int = 100 a_bool = True

# Moving the digits toward the end of the variable name

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

main.py
characters_3 = ['a', 'b', 'c'] def characters_2(): return ['a', 'b']

move digits toward end of variable name

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

# Picking a different name

You could also name your variable something else.

main.py
three_characters = ['a', 'b', 'c'] def two_characters(): return ['a', 'b']

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']

variable names are case sensitive

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

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

# Literal values cannot contain characters and numbers

The error also occurs when characters are mixed with numbers when using literal values.

main.py
# ⛔️ SyntaxError: invalid decimal literal str(123abc) # ⛔️ SyntaxError: invalid decimal literal age = 30yo

One way to get around this is to declare a string by wrapping the value in quotes.

main.py
age = '30yo' print(age) # 👉️ 30yo another = '123abc' print(another) # 👉️ 123abc

Alternatively, you can remove the characters.

main.py
age = 30 print(age) # 👉️ 30 another = 123 print(another) # 👉️ 123

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.