Why can't you declare variables that start with a number in Python?

Question:

Why can't you declare variables that start with a number in Python?

Example:

prueba1 = "hola mundo" #bien
1prueba = "hola mundo" #mal

Answer:

Almost no programming language [*] supports identifiers (variable names) that begin with numeric digits.

As they explain here , accepting such identifiers would introduce ambiguities in the syntax.

For example, it would not be clear whether in

x = 1600L

we mean a variable with name 1600L , or a numeric literal with the suffix L (long). Worse still, if we accept identifiers made up of digits only, it would be impossible to distinguish them from numeric literals.

x = y + 20  # qué tal si hay una variable llamada "20" ?

Of course one could introduce restrictions, such as "we accept identifiers that start with digits if they contain at least one letter and if they cannot be confused with a numeric literal …" but this would be very ugly and fragile. The simplest and most elegant thing is to agree to prohibit them from entering.


[*] The only exception I know of is Perl – because in this language variables are distinguished by a prefix ("sigil") like $ . Thus, there is no danger of ambiguity.

[**] The restriction is present even on element identifiers in HTML4 ( id attribute ), although in this case it is more difficult to justify it. In fact, in HTML5 the restriction was lifted.

Scroll to Top