My question is on control flows with if-statements and arrays, basically, I am extracting some information to an array x (given conditions a,b) and the flow gets executed depending on whether there is some information extracted or there was no information. My code looks like that:
if a:
x = ...
if not x:
if b: #repeated
x = ...
if not x:
raise Exception
elif b: #repeated
x = ...
if not x:
raise Exception
Is there any elegant way to skip to elif condition automatically after 'if not x'? My primary focus is on a, if a is not present or doesn't contain any information, I am checking existence of b and whether it's empty. If b empty I am raising an exception (here i might actually proceed to else: raise Exception however it's the same thing as above and I don't know how to control such a flow i.e. redirect to another statement).
I've tried 'break' however it doesn't work for statements not nested in the for/while loops.
Thanks in advance!
Some clarification based on comments:
- x gets assigned to an xmltree element and the element is different for a and b,
- The 'if a' is about checking if item1 is present in an array, then I am checking if the element in xml tree assigned to it contains some information, if not I fall back on the default option b, and also checking if item2 now exists and if it contains information; if none of the abovementioned cases - the program should exit at this point
CodePudding user response:
Assuming the assignment to x is the same (or at least varies only in the value a or b used, you can use a loop with an else clause:
for thing in [a,b]:
if not thing:
continue
x = ... # can depend on thing
if x:
break
else:
raise Exception
The else clause is only executed if the loop terminates due to exhaustion of the iterable, not if a break statement is executed.
CodePudding user response:
Since there is limited context I can only imagine what you want. If you use python 3.10, you might be able to use the match statement for your use case. Here's what I imagine this could look like but we can refurbish this further in the comments:
class XMLNode:
def __init__(self, subnode, label):
self.subnode = subnode
self.label = label
node = ...
match node
case XMLNode(subnode=a, label=_):
pass
case XMLNode(subnode=b, label=_):
pass
