1

I have written a python code to find prime numbers between 2 and 30. But my code is not evaluating for 2 and 3. Can anyone tell me what is wrong in this code?

for i in range(2, 30):
    for j in range(2, i-1):
        if ((i % j) == 0):
            print(i, "is not a prime number")
            break
        else:
            print(i, "is a prime number")
        break
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
Lax_Sam
  • 1,099
  • 2
  • 14
  • 32

3 Answers3

2

The logic of your code is wrong. The else clause should be attached to the inner for loop, so it's only executed if the loop is exhausted without finding a divisor.

for i in range(2, 30):
    for j in range(2, i-1):
        if ((i % j) == 0):
            print(i, "is not a prime number")
            break
    else:
        print(i, "is a prime number")

Also note that the outer loop only runs up to 29, since the upper boundary is not included in a range. The inner loop does not include i - 1, but that's totatlly fine, since any non-trivial divisor is less than i - 1.

The inner loop won't be entered at all for 2 and 3, since the range will be empty in these cases. This is fine as well, since the else clause will be immediately entered.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
1
for i in range(2, 30):
    prime = True
    for j in range(2, i-1):
        if ((i % j) == 0):
            prime = False
            # print(i, "is not a prime number")
            break
        # else:
        #  print(i, "is a prime number")
        # break
    if prime:
        print(i, "is a prime number")
    else :
        print(i, "is not a prime number")

There are lot of online link to solve the prime number problem. To improve yourself search yourself and understand the. Hope this and this link help you a lot. Happy codding

R.A.Munna
  • 1,699
  • 1
  • 15
  • 29
0

It isn't working because the nested for declaration:

for i in range(2, 30):
    for j in range(2, i-1):

Uses range(2, i-1) and until i is 4, range returns no value:

i = 2 --> range(2, 1) # No value
i = 3 --> range(2, 2) # No value
i = 4 --> range(2, 3) # 2

This is because the range function returns values from the first parameter (included) to the second parameter (not included).

Strinnityk
  • 548
  • 1
  • 5
  • 17