Shromann
Shromann

Reputation: 1

any() in python coding issue

I am trying to make a function that tells you if a number is prime or not using the any() method. This is what I have:

def prime(n):
    if any(n % i == 0 for i in range(1, n + 1)) != True:
        print("Prime")
    else:
        print("Not Prime")

prime(5)

However it is giving me:

Not Prime

every single time, even when I give a prime number.

Can someone please help me out?

Upvotes: 0

Views: 72

Answers (1)

Carcigenicate
Carcigenicate

Reputation: 45750

Everything is divisible by 1, so that check will consider everything as non-prime. You need to set the lower bound to check to 2 instead.

As pointed out in the comments by @ForceBru, the upper bound is incorrect as well. You don't want to check if n is divisible by itself, since it always will be.

Change your range in the comprehension to just:

range(2, n))

Upvotes: 1

Related Questions