Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shouldn't else be indented in the below code

Tags:

python

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'
...
like image 533
aWebDeveloper Avatar asked Dec 21 '25 11:12

aWebDeveloper


2 Answers

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:
like image 131
Abgan Avatar answered Dec 23 '25 02:12

Abgan


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.

like image 28
Kuf Avatar answered Dec 23 '25 00:12

Kuf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!