Do you have additional loop conditions ... based on the condition?

Variable a can take any number of values. The value a represents the number of additional predefined conditions for the while loop.

This can be done with a few elif statements, but is there a cleaner way to do this?

 if a == 0: while condition_1: ... elif a == 1: while condition_1 or condition_2: ... elif a == 2: while condition_1 or condition_2 or condition_3: ... 
+6
source share
3 answers

The general way to do what other languages ​​do with the switch is to create a dictionary containing a function for each of your cases:

 conds = { 0: lambda: condition_1, 1: lambda: condition_1 or condition_2, 2: lambda: condition_1 or condition_2 or condition_3 } 

Then:

 while conds[a](): # do stuff 

Using lambdas (or named functions if your conditions are especially complex), the corresponding condition can be evaluated every time through the loop, and not once, when the dictionary is defined.

In this simple case, when your a has sequential integer values ​​starting at 0, you can use a list and save a bit of input. For further simplification, you can define each of your conditions in terms of the previous one, since you simply add a condition every time:

 conds = [ lambda: condition_1, lambda: conds[0]() or condition_2, lambda: conds[1]() or condition_3 ] 

Or, as Julien suggested in a comment:

 conds = [ lambda: condition_1, lambda: condition_2, lambda: condition_3 ] while any(cond() for cond in conds[:a+1]): # do stuff 
+10
source

Have you tried something like this:

 while (a >= 0 and condition_1) or (a >= 1 and condition_2) or (a >= 2 and condition_3) ... 
+3
source

You can define a function to be evaluated for while :

 def test(a): if a == 1: return condition1(...) elif a == 2: return condition2(...) or condition1(...) elif a == 3: return condition2(...) or condition1(...) or condition3(...) else: return False # test(a) will check the conditions ... define additional arguments if you need them while test(a): do_stuff 

It still has elifs, but you do not need to write while -loop several times.

+2
source

All Articles