Search code examples
pythonnumbers

Why is this code outputting multiple of the same prime numbers?


Hi everyone :) (I am very new at this)

I am playing around with a simple piece of code which should print the prime numbers in a given range.

nums = range(1, 11)

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

The output I get is as follows...

5
5
5
7
7
7
7
7
9

I can't understand why it is printing the prime numbers multiple times.

I expected it to print the numbers...

3,5,7,9

But cannot seem to understand why it is printing 5 3 times and 7 5 times etc.


Solution

  • You only need to move the print(number) statement outside of the else block,

    nums = range(1, 11)
    
    for number in nums:
        if number > 1:
            for i in range(2, number):
                if (number % i) == 0:
                    break
            else:
                print(number)