Reputation: 371
This seems like a very basic question... But I can't think straight for some reason...
How do I write the following without copying the "else" statement twice? (and without needing to put this in a function)
I wrote print("a") and print("b"), but it originally has 4-6 statements.
if os.path.exists(new_output_folder) and os.path.exists(prev_output_folder):
subdirs_lastrun = [os.path.basename(x[0]) for x in os.walk(new_output_folder)]
subdirs_prevrun = [os.path.basename(x[0]) for x in os.walk(prev_output_folder)]
if not "ref" in subdirs_lastrun and "ref" in subdirs_prevrun:
print("a")
else:
print("b")
else:
print("b")
Upvotes: 0
Views: 69
Reputation: 462
while(True):
if os.path.exists(new_output_folder) and os.path.exists(prev_output_folder):
subdirs_lastrun = [os.path.basename(x[0]) for x in os.walk(new_output_folder)]
subdirs_prevrun = [os.path.basename(x[0]) for x in os.walk(prev_output_folder)]
if not "ref" in subdirs_lastrun and "ref" in subdirs_prevrun:
print("a")
break
# else case
print("b")
break
Upvotes: 0
Reputation: 881503
You could just use a boolean value to decide the complex stuff that has to happen at the end, something like:
do_a = os.path.exists(new_output_folder) and os.path.exists(prev_output_folder)
if do_a:
subdirs_lastrun = [os.path.basename(x[0]) for x in os.walk(new_output_folder)]
subdirs_prevrun = [os.path.basename(x[0]) for x in os.walk(prev_output_folder)]
do_a = not "ref" in subdirs_lastrun and "ref" in subdirs_prevrun
if do_a:
print("a")
else:
print("b")
Obviously this becomes advantageous if (as you state) the a/b paths are more complicated that a simple print.
Upvotes: 1