Stopping an iteration

I have a loop iterating through a list:

for i in up_to_n:
    if n%i == 0:
        print("the number isn't prime")
        ***how do I stop the code right here?***

in case the condition is true I want the iteration to stop immediately. how do I do it?

Hi, @temimam,

Use a break statement inside the if block to terminate the loop.

a what!?
I’m not sure I know what a break is.

Try this:

    if n%i == 0:
        print("the number isn't prime")
        ***how do I stop the code right here?***
        break
1 Like

When executed, a break statement will immediately terminate execution of the innermost loop that contains it.

is it really that simple?
and I had no Idea!
thanks a lot @appylpye!

1 Like

This topic was automatically closed 18 hours after the last reply. New replies are no longer allowed.