-2

As an example: diameter = 7

next is where I would want to give the a value a variable name of 7

7 = 21

Community
  • 1
  • 1

2 Answers2

2

Yes you can do it by modifying locals():

my_var = 'vla'
locals()[locals()['my_var']] = 'some_value'
# or use setdefault if you don't wan't to override variable if it already exist
locals().setdefault(locals()['my_var'], 'some_value')
print vla
# some_value

NOTE: value of my_var should be a valid python variable name. Which is the uppercase and lowercase letters A through Z, the underscore _ and, except for the first character, the digits 0 through 9 ( shortly use pattern /[a-z_][a-z0-9_]*/i as @hjpotter suggested).

For your case you have to add some prefix before creating new variable from value, because your value is invalid variable name, see code below:

diameter = 7
# diameter value is invalid name for our new variable,
# let's add `_` prefix to value to  be sure name is valid:
locals()['_' + str(locals()['my_var'])] = 'some_value'
# Note that i've applied str function to value of diameter variable
# to avoid TypeError (cannot concatenate 'str' and 'int' objects) 
Andriy Ivaneyko
  • 15,838
  • 3
  • 43
  • 65
1

No. If you are attempting to assign a value to a numeral, that is not valid. Variable names must:

  • Start with either a letter or an underscore like:

    _varname 
    varname
    
  • Numerals may exist in the remainder of the variable name like:

    _varname1
    varname1
    

As a side note, variables are case sensitive too. Thus varname and Varname are two different variables.

A bit more detail can be found in this (non-python specific) question about why variables can't start with a number.

Community
  • 1
  • 1
Andy
  • 43,170
  • 54
  • 150
  • 214