Last updated: Apr 8, 2024
Reading time·2 min
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.
Here is an example of how the error occurs.
# ⛔️ SyntaxError: invalid decimal literal 3_characters = ['a', 'b', 'c'] # ⛔️ SyntaxError: invalid decimal literal def 2_characters(): return ['a', 'b']
The name of a variable must start with a letter or an underscore.
Literals in Python are values such as numbers, strings and booleans.
a_str = 'bobbyhadz.com' an_int = 100 a_bool = True
One way to solve the error is to move the digits toward the end of the variable name.
characters_3 = ['a', 'b', 'c'] def characters_2(): return ['a', 'b']
A variable name can contain alpha-numeric characters (a-z
, A-Z
, 0-9
) and
underscores _
.
You could also name your variable something else.
three_characters = ['a', 'b', 'c'] def two_characters(): return ['a', 'b']
Variable names in Python are case-sensitive.
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.
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.
The error also occurs when characters are mixed with numbers when using literal values.
# ⛔️ 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.
age = '30yo' print(age) # 👉️ 30yo another = '123abc' print(another) # 👉️ 123abc
Alternatively, you can remove the characters.
age = 30 print(age) # 👉️ 30 another = 123 print(another) # 👉️ 123
You can learn more about the related topics by checking out the following tutorials: