how can i change a variable name while the code is running? | SoloLearn: Learn to code for FREE!

+2

how can i change a variable name while the code is running?

i want to name a variable with an input(), but i dont know any way that would let me. like this: a = input() 'a' + 'added_name' = 1 the variable should be named with the string a, followed by 'added_name'... but id doesn't work this way... :(

5/18/2020 3:37:27 PM

salamelek

17 Answers

New Answer

+9

a = input() #input 1 vars()['a'+a] = 100 print(a1) # ouputs 100

+2

Samuel Sluga Replace line 3 with this print(vars()['a'+a])

+1

CeePlusPlus it is possible in python. See my code

+1

Ore Adeleye oh I did not know that! Very interesting! Thanks! :)

+1

Samuel Sluga I must add, Manipulating variables this way is a bad practice and I would advice that you do it just for fun. Not in a production environment where memory management is important.

+1

Ore Adeleye pretty interesting... Thanks for sharing! 𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 it is;)

0

As I know of, you cannot do that. :(

0

Ore Adeleye ok... but how do i print the new named variabile if i dont know how it will be named yet?

0

Ore Adeleye ok, i am dumb. thanks!

0

Ore Adeleye ok, thanks for the advice, but i see this as my only option for now

0

Ore Adeleye your suggested code is not working

0

G B yeah it's working only for 1, not for all numbers It should work for all nmbrs

0

𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 for it to work, you must change all the parameters in the right way. it worked with me, so...

0

𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 as the variable is named a1 it it pretty clear to only work with 1... As Ore Adeleye already mentioned, such "tricks" should be handled very carefully...

0

𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 yeah but then he said print(vars()['a' + a])

0

do you mean changing the variable value and output? i only know cpp you can do this: int dude = 1; cout << dude; cin dude; system(“cls”); cout<<dude; find a system cls for python idk lol.