2

I am new to python and i am still strugling to understand how the sytnax works, how you need to allign your If and else to make it work correctly. How do i really know which else goes with which if? especially when using nested code blocks.

In the code below for the else followed by the comment Prime! from what i understand that else goes with the statement if (n % div == 0): but then why is it alligned with the FOR statement instead?

the last else statement i think goes with if n == 2: but the else is not alligned with it, instead it is after. For the same statement if n == 2: why is n += 1 alligned before pime_count +=1 and not after it.

I understand that the placement of the Else and if is very important because if i decided to move any of them the code stops working. What i can't seem to understand is how does python know which else goes with which if, if the allignment doesnt seem to be consistent.

#!/usr/bin/env python
#
# Problem Set 1a
#
# A program that computes and prints the 1000th prime number.
# Finds primes using trial division (least efficient method)
#------------------------------------------------------------

prime_count = 0
n = 2 

while (prime_count <= 1000):
  #if even, check for 2, the only even prime
  if (n % 2 == 0):
    if n == 2:
      prime_count += 1
    n += 1
  else:
    # number is odd, possible prime
    for div in range(3, n, 2):
      if (n % div == 0):
        # not a prime
        n += 1
        break
    else:
      # prime!
      prime_count += 1
      if prime_count == 1000:
        print "The 1000 prime is", n
      else:
        n += 1
Adrian Sultu
  • 330
  • 5
  • 16
  • The indentation **should** be consistent, I'd question the validity of that code snippet. – Anthony Grist Mar 07 '13 at 15:53
  • 4
    You can also `else` a `for` loop in python, so that may be confusing you here. – Silas Ray Mar 07 '13 at 15:54
  • I agree with @AnthonyGrist , it looks like the last 7 lines should be tabbed over. – chase Mar 07 '13 at 15:55
  • 3
    Using a 4 space indentation would make this a whole lot more readable. – Martijn Pieters Mar 07 '13 at 15:56
  • Thanks @MartijnPieters - the 'rule' for python is 4 space indentation. See http://www.python.org/dev/peps/pep-0008/. If you want to be taken seriously, do so – KevinDTimm Mar 07 '13 at 15:59
  • Thank you, i understand that part now but there is one more thing i fail to understand in that code, when the value of n reaches 4, where does it go after if n == 2: comes out false? The else that is aligned here is else: # number is odd, possible prime but 4 is not odd? the next else after that is for the for statement, which leaves the last else at the bottom which is not aligned to the if n == 2 statement but instead to the if prime_count == 1000: statement. So i keep looking at that code and can't figure out what happens when n becomes 4 or any other even number for that matter. – Adrian Sultu Mar 07 '13 at 17:39

5 Answers5

10

The rule is very simple: the else clause must have the same indentation as the statement it refers to (most commonly, an if statement).

Now, here:

for div in range(3, n, 2):
  if (n % div == 0):
    # not a prime
    n += 1
    break
else:
  ...

you are not using if-else, you are using for-else!

This construct means "execute the else block unless the loop has terminated through a break".

See for ... else in Python for a discussion.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • then if that else is joined to that for, what triggers the else? from what i understand a false will trigger the else but here the for looks like it is assigning a value to the variable div. Or is it that if the condition of the for fails then the for statement is false? also the last else at the bottom of the code seems to be alligned with if prime_count == 1000: but i thought it was going with if n == 2:. If it gets to number 4 and passes the odd or even test but the fails the test to check if its 2, where does it go after that in the code if that last else is not for that? – Adrian Sultu Mar 07 '13 at 16:22
  • Thank you, i understand that part now but there is one more thing i fail to understand in that code, when the value of n reaches 4, where does it go after if n == 2: comes out false? The else that is aligned here is else: # number is odd, possible prime but 4 is not odd? the next else after that is for the for statement, which leaves the last else at the bottom which is not aligned to the if n == 2 statement but instead to the if prime_count == 1000: statement. So i keep looking at that code and can't figure out what happens when n becomes 4 or any other even number for that matter. – Adrian Sultu Mar 07 '13 at 17:39
  • @AdrianSultu: If you're unsure about the flow of your code, I recommend either using a debugger (http://stackoverflow.com/questions/4929251/can-you-step-through-python-code-to-help-debug-issues) or inserting `print` statements in strategic locations. – NPE Mar 07 '13 at 17:40
  • i did that, i inserted prints almost everywhere and cannot figure out what it does with 4, it's as if it skips even numbers but i don't see which part of the code tells it to skip even numbers besides the last else which is not even alligned correctly to do that – Adrian Sultu Mar 07 '13 at 17:58
  • i found my answer, it was the n += 1 that follows the prime_count += 1 for the if n == 2: statement. The n += 1 is alligned before the prime_count += 1 and that's where even numbers get ruled out, the prime_count += 1 only comes in effect if the value of n is 2 and thats why it is after the n += 1 statement.. – Adrian Sultu Mar 07 '13 at 18:08
0

An if goes with an else at the same indentation, so long as there are no other things at lower indentation between them. They have to be in the same "block". However, in your case, the else that's followed by # prime! is not actually joined to an if at all, but rather to the for div in range(3, n, 2): loop before it!

Henry Keiter
  • 16,863
  • 7
  • 51
  • 80
0

An else attached to a for loop means "execute this code if the for loop completed without hitting a break statement". It can be useful sometimes, but it is often confusing for people who haven't encountered it before!

Weeble
  • 17,058
  • 3
  • 60
  • 75
0

I think this can help you to understand how python indentation works http://psung.blogspot.com/2007/12/for-else-in-python.html

In a construct like this one:

for i in foo:
  if bar(i):
    break
else:
  baz()

the else suite is executed after the for, but only if the for terminates normally (not by a break).

In other situations else goes after if

user232343
  • 2,008
  • 5
  • 22
  • 34
0

There are 2 rules which are fairly simple,

  1. The indent of the if and else have to be the same

    for x in range(15):
        if x > 10:
            print 'x is more than 10'
        else:
            print 'x is less than or equal to 10'
    
  2. Nothing with an indent lower than or equal to that of if and elseshould come in between them So, this is invalid/ will raise a SyntaxError.

    for x in range(15):
        if x > 10:
            print 'x is more than 10'
        print x
        else:
            print 'x is less than or equal to 10'
    

Also, As stated in PEP 8

Use 4 spaces per indentation level.

for div in range(3, n, 2):
  if (n % div == 0):
    # not a prime
    n += 1
    break
else: # at same indent as for
  # prime!

Also, your indent above means for...else loop is made (here else clause is executed if the for loop is exited using break), not if..else.

pradyunsg
  • 18,287
  • 11
  • 43
  • 96