MrJanx
MrJanx

Reputation: 123

Python: While Loops, Executing the same code under different conditions. Elegance and overhead

In python: I am looking to execute the same block of code in a while loop, but under different conditions, with a flag for which condition should be checked. Also, the flags will not, in this case, change during execution, and only one flag will be active for this segment of the program.

I could do this as follows:

#user inputs flag
if flag == "flag1": flag1 = True
elif flag == "flag2": flag2 = True
#...
#define parameters    
while (flag1 and condition1) or (flag2 and condition2) ... or (flagN and conditionN):
    #do stuff #using parameters

This method is OK, seeing as it will only check the flags, and not calculate the conditions for each bracket every time, due to the way "and" works in python.

or

def dostuff(parameters):
    #do stuff

#user inputs flag
if flag == "flag1": flag1 = True
elif flag == "flag2": flag2 = True
#...

#define parameters

if flag1:
    while(condition1):
        dostuff(parameters)
elif flag2:
    while(condition2):
        dostuff(parameters)
etc... down to N

would accomplish the same thing, probably the same overhead.

I was just wondering if anyone can suggest a better method, in terms of programming practice and readability,or if this is the best general approach.

Thanks

Upvotes: 3

Views: 753

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180492

You could use any:

while any((flag1 and condition1),(flag2 and condition2),(flagN and conditionN))

There is also a difference between your two methods, if any condition can affect another then the two examples can behave differently.

You could also make a container of pairings and iterate:

data = ((flag1, condition1),(flag2, condition2),(flagN,conditionN))

for flag, cond in data:
   if flag:
       while cond:
         do_stuff(parameters)

It will avoid repeating code and is readable.

Upvotes: 4

Maxime Chéramy
Maxime Chéramy

Reputation: 18851

You can use a dict of lambda expressions:

conditions = {
    flag1: lambda: cond1,
    flag2: lambda: cond2,
    flag3: lambda: cond3}

while conditions[flag]():
    do_stuff(parameters)

Example:

conditions = {
    "flag1": lambda: x < 10,
    "flag2": lambda: x < 3,
    "flag3": lambda: x < 5}

x = 0
while conditions["flag2"]():
    print(x)
    x += 1

output:

0
1
2

Upvotes: 4

Related Questions