dežko123
dežko123

Reputation: 19

how to make input variable inside of loop?

Ok, so i want the "y = x/2" part assign to "operation" input, so i can change that equation through the console.

operation = input("operation: ")


y = 0
axis_x = list(range(10))
axis_y = []
for x in axis_x:
    y = x/2
    print(y)
    axis_y.append(y)

when i change it to this:

operation = input("operation: ")


y = 0
axis_x = list(range(10))
axis_y = []
for x in axis_x:
    operation
    print(y)
    axis_y.append(y)

nothing happends, i just want to make equations thru the console, i want to type in the console "y = x/2", but that just doesnt work. I tried .format() too, but the same problem. somebody help, thanks!

Upvotes: 0

Views: 36

Answers (3)

10o
10o

Reputation: 90

You could achieve this by calling the exec() function on your string. At the moment you are just calling a string.

But note that calling exec on user given input has security implications! A malicious user could execute any code!

Upvotes: 0

Chrispresso
Chrispresso

Reputation: 4071

You need to ask for user input and then evaluate what is happening:

In [773]: x_s = list(range(10))                                                                                           

In [774]: y_s = []                                                                                                        

In [775]: eq = input('enter equation: ')                                                                                  
enter equation: y=x/2

In [776]: while eq and len(y_s) <= len(x_s): 
     ...:     func = eq.replace('y=', 'lambda x:') 
     ...:     y_s.append(func) 
     ...:     eq = input('enter equation: ') 
     ...:                                                                                                                 
enter equation: y=x*2
enter equation: y=x+10
enter equation: 

In [777]: y_s                                                                                                             
Out[777]: ['lambda x:x/2', 'lambda x:x*2', 'lambda x:x+10']

In [778]: x_s = x_s[:len(y_s)]                                                                                            

In [779]: x_s                                                                                                             
Out[779]: [0, 1, 2]

Then you just need to eval them like so:

In [787]: [eval(func)(x) for func, x in zip(y_s, x_s)]                                                                    
Out[787]: [0.0, 2, 12]

Upvotes: 0

Barmar
Barmar

Reputation: 780724

If you want to execute a statement from a string, you have to use the exec() function.

for x in axis_x:
    exec(operation)
    print(y)
    axis_y.append(y)

Upvotes: 1

Related Questions