for-else in python when for loop is not executed
What is the best way for me to use for - else if I only want to go into else break when for loop is not executed? I want to raise Exception when x is 0. all i can think about is add one more if logic inside for loop any better way to do it?
x = 1 for i in range(1, x + 1): print(i) if i == x: break else raise Exception
Use a flag:
in_loop = False for i in range(1, x + 1): in_loop = True print(i) if not in_loop: raise Exception()
I would separate that from the loop altogether. Test the condition first, then execute the loop:
if x <= 1: raise Exception for i in range(1, x + 1): ...
if/elseblock to check the value of
xbefore your loop
x = 1 if x == 0: raise Exception else: for i in range(1, x + 1): print(i) if i == x: break