hey everyone im making a program that takes a number (n) from the user and then decides if it is prime or not and prints that decision to the screen

from math import *
def main():
    n=eval(input("please enter the number you wish to check:"))
    n=abs(n)
    if n < 2:
         print("this is not a prime number")
    if n == 2:
        print("this is a prime number")
    if not n & 1:
        print("this is not a prime")
    for x in range (3, int(n**0.5)+1,2):
        
        if n%x!=0:
            print("this is a prime number")
        else:
            print("this is not a prime number")
    
main()

my problem is that when i enter the number 2 it prints both that its a prime and not a prime. and when i use a number like 3 or 5 it doesnt print anything and if i use numbers like 100 it prints every print statement. any idea on what im doing wrong/and tips or hints to fix it? thanks

Recommended Answers

All 3 Replies

For a start, use 'elif'. This will fix the problem with input of '2'.

from math import *
def main():
    n=input("please enter the number you wish to check:")
    n=abs(n)
    if n < 2:
         print("this is not a prime number")
    elif n == 2:
        print("this is a prime number")
    elif not n & 1:
        print("this is not a prime")
    else:
      for x in range (3, int(n**0.5)+1,2):
        
        if n%x!=0:
            print("this is a prime number")
        else:
            print("this is not a prime number")
    
main()
n=input("Enter the number: ")
prime=True

if n==1:
    print "It is neither prime nor composite"
else:
    for i in range(2,n):
        if n%i==0:
            prime=False

if prime==True:
    print "It is a prime number"
else:
    print "It is a composite number"

`#Without using functions

@Akash_8, nice effort. Works well with Python27 for smaller numbers.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.