Skip to content Skip to sidebar Skip to footer

Shouldn't Else Be Indented In The Below Code

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 righ

Solution 1:

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:

Solution 2:

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.


Solution 3:

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)


Post a Comment for "Shouldn't Else Be Indented In The Below Code"