is there any way to create a variable from a command in python? Example: x = while, x(True): | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

is there any way to create a variable from a command in python? Example: x = while, x(True):

24th Apr 2018, 11:07 PM
ArTombado
ArTombado - avatar
5 Answers
+ 11
thanks! :)
4th May 2018, 9:23 PM
ArTombado
ArTombado - avatar
+ 10
I tried to do this, but I did not quite understand how to set the command to the variable, could you explain me better? Sorry, I'm still starting to study in-depth programming.
1st May 2018, 9:43 PM
ArTombado
ArTombado - avatar
+ 6
As far as I know, you are limited. You could: x="while (y < 3):\n print(y)\n y+=1" y=0 exec(x) which would output 0, 1, and 2.
24th Apr 2018, 11:47 PM
John Wells
John Wells - avatar
+ 2
Let me ask you back. You want to, as the result of a method's execution, instantiate a variable at runtime, or assign a value to an existing variable based on some method's return value? If it's the first case, my previous answer addresses your problem. "self." variables are global variables, meaning that they will exist during the entire class existence and can be accessed by any of its class' methods. Variables declared without "self." prefix only exist inside the scope they belong to (a loop, an if-else, etc.), being destroyed as soon as the scope ends. Understand "self" as "a class variable that is a property of itself" and, like so, ia accessible anywhere in the class. Hope that this explanation helps a little more!
4th May 2018, 9:21 PM
Diego Benincasa
Diego Benincasa - avatar
+ 1
Haven't tried yet, but I came up with a suggestion that might work. Try creating a method that defines the variable as a global, with "self". See below. def criaVariavel(self, k): if k == True: self.x = k And then you could test if self.x was created, by using try/except. try: a = self.x '''if the variable exists, this assignment is possible. If doesn't,, python raises an exception and goes to the next block.''' except: a = 2 Worth a try!
1st May 2018, 7:27 PM
Diego Benincasa
Diego Benincasa - avatar