Check a number is Prime or not in Python

0 votes

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 display anything. Could you please help me with it?

Oct 26, 2018 in Python by findingbugs
• 3,140 points
115 views

1 answer to this question.

0 votes

There is an efficient way to write the same program. 

The loop you wrote can be concisely rewritten in Python:

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

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

answered Oct 26, 2018 by Priyaj
• 56,160 points

Related Questions In Python

0 votes
1 answer

How do I check if input string is a valid regular expression or not in Python?

Hi. Good question! Well, just like what ...READ MORE

answered Feb 12 in Python by Nymeria
• 3,500 points
39 views
0 votes
2 answers

How to check whether a string contains alphabets or number in Python?

By using isAlpha () to check whether ...READ MORE

answered 5 days ago in Python by Sheik janibasha
30 views
0 votes
1 answer

How does Python know whether a variable in the class is a method or a variable?

In python objects/variables are wrapped into methods ...READ MORE

answered Sep 18, 2018 in Python by ariaholic
• 7,320 points
37 views
0 votes
1 answer

How do I use urllib to see if a website is 404 or 200 in Python?

For Python 3, try doing this: import urllib.request, ...READ MORE

answered Nov 29, 2018 in Python by Nymeria
• 3,500 points

edited Dec 11, 2018 by Nymeria 288 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 128 views
+4 votes
6 answers
+1 vote
1 answer

How to check if a string is null in python

Try this: if cookie and not cookie.isspace(): # the ...READ MORE

answered Aug 20, 2018 in Python by Priyaj
• 56,160 points
1,575 views
0 votes
1 answer

Is there a label/goto in Python?

No, Python does not support labels and ...READ MORE

answered Aug 1, 2018 in Python by Priyaj
• 56,160 points
105 views