1

I am creating a function which returns True when a number(here X) is Prime.

So I am checking whether the given number is evenly divisible by integers from 2 to X-1.

But the while loop breaks when the check returns True.

Help

def is_prime(x):
    n = 2

    if x < 2:
        return False

    elif x == 2:
        return True

    else:
        while True and n < x:
            if x % n == 0:
                return False

            else:
                n += 1
                return True    #--The loop is breaking here--
Hax0
  • 103
  • 2
  • 8
  • 1
    Yes, returning from a function breaks a loop inside that function. You only want to `return True` after the loop has finished. And btw. `while True and n < x` is the same as `while n < x`. – dhke Jun 19 '17 at 05:45

2 Answers2

2

You code should look like this:

def is_prime(x):
    n = 2

    if x < 2:
        return False

    elif x == 2:
        return True

    else:
        while n < x:
            if x % n == 0:
                return False

            else:
                n += 1
        # Put the return True after the loop
        return True

print('{}: {}'.format(10, is_prime(10)))
print('{}: {}'.format(11, is_prime(11)))
print('{}: {}'.format(0, is_prime(0)))
print('{}: {}'.format(1, is_prime(1)))
print('{}: {}'.format(2, is_prime(2)))
print('{}: {}'.format(113, is_prime(113)))

Output:

10: False
11: True
0: False
1: False
2: True
113: True
Nurjan
  • 5,889
  • 5
  • 34
  • 54
1

Well You used return statment in loop, so it exited from method. You need to change the logic of this loop. Check here: Python Prime number checker