Reputation: 38352
In the python tutorial is an example (copied below), shouldn't else
be indented? I ran the code and it didn't work but I indented it (else
) and it worked. Is, what I am saying right? If the documentation is wrong, then how do I report it as a bug to python doc guys?
>>> 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'
...
Upvotes: 2
Views: 141
Reputation: 17828
Tha example is working and the indented is fine, have a look here:
# Ident level:
>>> for n in range(2, 10): # 0
... for x in range(2, n): # 1
... if n % x == 0: # 2
... print n, 'equals', x, '*', n/x # 3
... break # 3
... else: # 1
... # loop fell through without finding a factor
... print n, 'is a prime number' # 2
As you can see, the else
relates to the second for
by following this rule:
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.
In the example, it means that the else will be called if the second for (in the second line) will finish running but will never run the break command - only if n % x == 0
never eval to TRUE
.
If (n % x == 0)
at any point the break will be called the second for will stop, n
from the first for will grow by 1, (n = n + 1) and the second for will be called again with a new n
.
Upvotes: 6
Reputation: 3716
See docs you linked:
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (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:
Upvotes: 7
Reputation: 20126
This is an example of Python's for ... else
http://psung.blogspot.co.il/2007/12/for-else-in-python.html
It basically invokes the code in the else
part after the for loop is over and terminated normally (not broke, in any way)
Upvotes: 0