nagisa
nagisa

Reputation: 720

Variable as loop's expression

Lets say I have string which changes according to input:

expression=True

or

expression="a>1"

How can I use this variable as loop's expression in the way, so I won't need to repeat myself writing double loop. (and without using eval)?

Well pseudo code:

expression="a<2"
a=1
while expression:
    print a,
    a+=0.1

would print something like that: 1 1.1 1.2 <...> 1.9

EDIT: No, I don't want to print numbers, I want to change loop condition(expression) dynamically.

CODE THAT works:

a="b==2"
b=2
while eval(a):
    //do things.

Upvotes: 0

Views: 317

Answers (3)

Denilson S&#225; Maia
Denilson S&#225; Maia

Reputation: 49377

Sample code:

somevar = 3
expression = lambda: somevar < 5
while expression():
    ...
    if continue_if_even:
        expression = lambda: (somevar % 2) == 0
    ...

Maybe using lambda might be the solution for your problem. And it's way better (more elegant, more bug-free, more secure) than using eval.

Of course, there are some very special cases where eval is still needed.

Upvotes: 4

user395760
user395760

Reputation:

You're asking how to run user input. The answer is eval (or - not here, but generally - exec). Of course this is a bad answer, but it's the only answer. And if the only answer is bad, the question is bad.

What are you really trying to do? There are few programs (most notably programming language implementations) that need to give the user this much power. Yours propably doesn't. Chances are you can do what you want to do without running user input. But we need to know what you're trying to do to suggest viable alternatives.

Upvotes: 4

unwind
unwind

Reputation: 399833

You seem to want to change the condition of the loop dynamically, but you're not providing a very good use case so it's hard to understand why. If you just want to print the numbers between 1 and 1.9 with an increment of 0.1, there are easy ways to do that:

for x in xrange(10):
  print "1.%d" % i

is one. There's no need for this dynamic expression magic. Also, you seem to want the same value (a) to have two very different meanings at the same time, both the value to print and the expression that controls how many values to print. That's perhaps a source of some of the confusion.

Upvotes: 0

Related Questions