Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I have written a program that will check if the entered number is a prime number or not:

def main():

n = input("Please enter a number:")

is_prime(n)

def is_prime(a):

    x = True 

    for i in (2, a):

            while x:

               if a%i == 0:

                   x = False

               else:

                   x = True

    if x:

        print "prime"

    else:

        print "not prime"

main()

If the entered number is not a prime number, it displays "not prime", as it is supposed to, but if the number is a prime number, it doesn't print anything. Could you please help me with it?

1 Answer

0 votes
by (107k points)
edited by

There are many different ways to test primality, but the loop you wrote can be concisely revised in Python:

def is_prime(a):

    return all(a % i for i in xrange(2, a))

The variable is prime if all numbers between 2 and a (not inclusive) give a non-zero remainder when divided into a.

If you are a beginner and want to know more about Python, then do check out the below Python tutorial video that will help you in understanding the topic in a better way:

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...