0

I am playing with python3.5 right now. I was working on a simple code, to find the prime numbers less than a given integer. I solved the code more by mistake and I don't know why. This is the code:

n=int(input('Enter a numeric value: '))

for num in range(2, n+1):
    if num>1:
        for i in range(2, num):
            if (num%i)==0:
                break
        else:   
            print(num)

What I don't seem to understand is why if i write the code like above it gives a correct answer, and if i write the else statement with one more indentation, the output is different. Ex:

Enter a numeric value: 10

3

5

5

5

7

7

7

7

7

9

for:

...if num>1:
    for i in range(2, num):
        if (num%i)==0:
            break
        else:   
            print(num)

I feel the need to mention that I just started to learn python so please take me slow:D

Claudiu B
  • 35
  • 7
  • You don't need to write `if num>1:` since `num` will iterate in the range 2..(n+1) which means that `num` will _always` be greater than 1. – Thomas Baruchel Nov 14 '15 at 14:40
  • I mostly let it there so I can fastly modify the code if I want a prime no. in a certain range. Ex. I enter `low=input()` for the bottom value of the range. – Claudiu B Nov 14 '15 at 14:44

1 Answers1

0

The else is associated with the for. Indenting it farther associates it with the if.

  • An else after an if runs if the if didn’t
  • An else after a for runs if the for didn’t break

You want the latter behaviour, since you break if you found a factor for the number.

Ry-
  • 218,210
  • 55
  • 464
  • 476