1

I'm trying to write a simple Python (ver 3.5) code for testing a given integer for primality. When I input 97 (for example) I get four True outputs. What am I doing wrong?

# Testing for primality: True or False 25.11.2015
# True means prime, False means divisible

num = int(input('Input an integer for primality test: '))

if num < 2 or num % 2 == 0:
    print('False')
else:
    for i in range(3, int(num ** (1/2)) + 1, 2):
        if num % i == 0:
            print('False')
            break
        else:
            print('True')
jub0bs
  • 60,866
  • 25
  • 183
  • 186
Yehuda Katz
  • 177
  • 1
  • 8

2 Answers2

1

Just unindent the last two lines:

# Testing for primality: True or False 25.11.2015
# True means prime, False means divisible

num = int(input('Input an integer for primality test: '))

if num < 2 or num % 2 == 0:
    print('False')
else:
    for i in range(3, int(num ** (1/2)) + 1, 2):
        if num % i == 0:
            print('False')
            break
    else:
        print('True')

In Python, for can have an else clause that only is called when the for loop naturally exhausts its iteration. So if you break from a for loop it won't print True. It prevents what other languages need a flag for that is tested outside the loop as seen in another answer.

You have an additional error, though, in that 2 returns False.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
0

You can't print True in the else statement .Instead you should use a flag and set it to 1 on failing of test and then break the loop

flag = False
for i in range(3, int(num ** (1/2)) + 1, 2):
    if num % i == 0:
        flag = True
        break
if flag:
    print('False')
else:
    print('True')
bugwheels94
  • 30,681
  • 3
  • 39
  • 60
  • 1
    If you defined a function, there would be no need for an extra flag. You could just return `False` as soon as you find a divisor. – jub0bs Nov 27 '15 at 21:15
  • @Jubobs yes there can be tons of ways but this is to provide the OP the reason for multiple printings of `True` – bugwheels94 Nov 27 '15 at 21:16