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 the condition should be checked. In addition, the flags in this case will not change at runtime, and only one flag will be active for that program segment.
I could do it like this:
#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 fine as it checks the flags and does not evaluate the conditions for each parenthesis every time due to the "and" being working 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
will do the same, possibly the same overhead.
I'm just wondering if anyone can suggest a better method, in terms of programming practice and readability, or if this is a better general approach.
thank
source to share
You can use dict
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
source to share
You can use any:
while any((flag1 and condition1),(flag2 and condition2),(flagN and conditionN))
There is also a difference between your two methods, if one condition can affect the other, then the two examples may behave differently.
You can also create a container of pairs and iterate:
data = ((flag1, condition1),(flag2, condition2),(flagN,conditionN))
for flag, cond in data:
if flag:
while cond:
do_stuff(parameters)
This will avoid repetition of code and is readable.
source to share