Variable names in Python cannot start with a number or can they?

后端 未结 2 777
长情又很酷
长情又很酷 2020-12-17 08:18

This is somewhat academic, but nevertheless.

Python syntax forbids starting a variable name with a number, but this can be sidestepped like so:

>&         


        
2条回答
  •  庸人自扰
    2020-12-17 09:00

    Python parser forbids naming variables that way, for the sake of parsing numbers and variables separately, as naming a variable 1e1 would create a chaos - is it the number 10.0 or the variable 1e1?

    "Python, please output for me 1e1!" - "Why is it 10.0? I stored 100 over there!"

    But the variables are actually stored in a way that allows binding a string that starts with a number to a value, because that feature is no harm in hashing maps of any kind, and so using this "trick" you can achieve your wanted numeral-prefixed-name variable without hurting the parser severability.

    I would say that technically, naming variables in that manner is not a violation to python guidelines, but it is highly discouraged, and as a rule unnecessary. Using globals for injecting variables is known as a very bad practice and this case should not be an outstanding.


    Of course, python could have used an encloser to numerals like strings, say *123*, but I believe the intent of inventing python was to make programming easier, not stretching the limits of variable naming space.


    Practically speaking, if you must use number-headed names you better do it with your own dictionary, rather than globals:

    >>> number_headed_vars = {'1a': 100}
    >>> number_headed_vars['1a']
    100
    

    That way you can create your own variables system - and avoid abusing globals().

提交回复
热议问题