(continues on next page) 19 4.4. $_{break}$and$_{continue}$ Statements, and$_{else}$Clauses on Loops Python Tutorial, Release 3.9.5 >>> sum(range(4)) # 0 + 1 + 2 + 3 6 >>> list(range(4)) [0, 1, 2, 3] >>> for n in range(2,10 ): ... for x in range(2, n): ... if n %x ==0: ... print(n,'equals', x,'*', n//x) ... break ... else : ... # loop fell through without finding a factor ... print(n,'is a prime number') ... 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 >>> for num in range(2,10 ): ... if num %2==0: ... print("Found an even number ", num) ... continue ... print("Found an odd number", num) ... Found an even number 2 Found an odd number 3 Found an even number 4 Found an odd number 5 Found an even number 6 Found an odd number 7 The$_{continue}$statement, also borrowed from C, continues with the next iteration of the loop: (Yes, this is the correct code. Look closely: the$_{else}$clause belongs to the$_{for}$ loop, not the$_{if}$ statement.) When used with a loop, the$_{else}$clause has more in common with the$_{else}$clause of a$_{try}$ statement than it does with that of$_{if}$ statements: a$_{try}$statement’s$_{else}$clause runs when no exception occurs, and a loop’s$_{else}$clause runs when no$_{break}$ occurs. For more on the$_{try}$ statement and exceptions, see Handling Exceptions . Loop statements may have an$_{else}$clause; it is executed when the loop terminates through exhaustion of the iterable (with$_{for}$) or when the condition becomes false (with$_{while}$), but not when the loop is terminated by a$_{break}$ statement. This is exemplified by the following loop, which searches for prime numbers: The$_{break}$ statement, like in C, breaks out of the innermost enclosing$_{for}$ or$_{while}$ loop. In chapter Data Structures , we will discuss in more detail about$_{list()}$ . Later we will see more functions that return iterables and take iterables as arguments. Lastly, maybe you are curious about how to get a list from a range. Here is the solution: We say such an object is iterable , that is, suitable as a target for functions and constructs that expect something from which they can obtain successive items until the supply is exhausted. We have seen that the for statement is such a construct, while an example of a function that takes an iterable is$_{sum()}$ : 4.4 $_{break}$and$_{continue}$ Statements, and$_{else}$Clauses on Loops