http://docs.python.jp/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops
>>> 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
The else clause of a loop is more like an else in a try statement than an else in an if statement. The else clause of the try statement is executed when no exception is thrown, and the else clause of the loop is executed when it is not broken. See Handling Exceptions for more information on try statements and exceptions.
I haven't learned how to use else like this.
Recommended Posts