+ 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... :(
17 odpowiedzi
+ 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
𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 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])