How to create a variable through the user-typed response in Python?

0

For example, we can use this code to assign the value to a variable:

idade = input('Digite sua idade: ')

What I would like to know is if, instead of assigning a value to a variable, is it possible to create a variable by naming it with a value entered by the user?     

asked by anonymous 30.12.2016 / 16:58

3 answers

2

The variable is just a name to reference an object that occupies a memory location. At runtime the variable name is completely irrelevant since no one is viewing it at any given time.

The name of the variable is important for the programmer to develop their logic correctly, so there is no reason to change their name at runtime.

    
30.12.2016 / 20:28
2

As colleagues reported this may not be the best way to solve your problem, but in python you can assign a variable with the value of the other sim with exec .

Note that this will not change the name of the variable, but create another one from the value typed.

Here's an example:

foo = "bar" //criando a variável foo com o valor "bar"
exec(foo + " = 'Valor da variavel bar'")
print (bar) // saída: Valor da variavel bar
    
30.12.2016 / 20:48
2

If the idea is to use variable variables you will have to use a dictionary to do this, as mentioned by @LuizVieira. However, it's not the same thing as PHP and I do not know a mechanism in Python that can do this.

See a small example:

meudic = {}
varnome = "variavelDoGato"
meudic[varnome] = "meow"
print(meudic["variavelDoGato"])

Output:

  

Meow

Source: How do I create a variable number of variables?

    
31.12.2016 / 13:32