Imagine what happens if the last number in range(3, int(n**0.5), 2) not an integer divisor of n :
if n % x ==0: prime = False # not this else: prime = True # this
So, even if all previous checks are evaluated False , you call n prime. The minimum change for your code to fix is:
prime = prime and True # or 'prime &= True'
So, if prime already False , it remains False .
However, keep in mind that for primitiveness, if any of these checks are False n not simple. You can use this with Python and and all (which are evaluated lazily, i.e. Do not check as soon as you find False ) to implement it much more efficiently:
def rand_prime(): while True: p = randint(10000, 100000) if (r % 2 != 0 and all(p % n != 0 for n in range(3, int(((p ** 0.5) + 1), 2))): return p
For even better performance, note that randrange contains a step argument, like range , so you can skip all even numbers (which is definitely not easy!):
def rand_prime(): while True: p = randrange(10001, 100000, 2) if all(p % n != 0 for n in range(3, int((p ** 0.5) + 1), 2)): return p
Note: sqrt(n) (from math ), in my opinion, is a bit clearer for other, less technical readers than n ** 0.5 (although it may or may not be more efficient ).