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

Question:

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.

Asked By: tryingmybest

||

Answers:

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)
Answered By: NIKUNJ PATEL
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.