Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 843
MrJanx Avatar asked Jan 18 '26 02:01

MrJanx


1 Answers

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
like image 113
Maxime Chéramy Avatar answered Jan 19 '26 16:01

Maxime Chéramy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!