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

3 answers

  • answered 2018-10-11 18:52 Daniel

    Use a flag:

    in_loop = False
    for i in range(1, x + 1):
        in_loop = True
        print(i)
    
    if not in_loop:
        raise Exception()
    

  • answered 2018-10-11 18:56 chepner

    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):
        ...
    

  • answered 2018-10-11 18:57 vash_the_stampede

    Use an if/else block to check the value of x before your loop

    x = 1
    if x == 0:
        raise Exception
    else:
        for i in range(1, x + 1):
            print(i)
            if i == x:
                break