Is it possible to create new variables from user input? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Is it possible to create new variables from user input?

I was just fooling around and experimenting with random stuff when I thought of this question. Specifically, can you take user input, create new variables that are named whatever was entered as input, and assign them with their own values, as the code is running? This might be silly, but if this were possible, wouldn't we be able to make self-generating code? Here's an(almost) illustration: x = input() if x != x: #This is just a throw away condition print("eh") else: x = x[0:(len(x))] x[0:(len(x))] = "Hello World!" print(x[0:(len(x))]) I know the last bit does not work, but hopefully this helps explain what I mean

12th Feb 2024, 5:01 AM
Aza
Aza - avatar
2 Answers
+ 2
You can, but you could just use dictionaries instead, they are more flexible and of course you can add whatever you want while the code is running, coming back to the topic, just use globals() or locals() to assign new variables at runtime, these functions are pretty self-explanatory, they both return a dictionary that you can modify, globals() returns a dictionary with the global variables, these that you can import in other python files, in other words, these that are outside functions and classes, locals(), on the other hand, when you're inside functions or classes, it returns the local variables there while the function is running or the class is being created, if you call locals() outside functions and classes it will return the same dictionary as globals(), because technically the globals would be the locals there, but if you call globals() inside functions or classes it will still return the globals
14th Feb 2024, 5:10 AM
Gabi_kun :3
Gabi_kun :3 - avatar
12th Feb 2024, 5:58 AM
Rain
Rain - avatar