Python Program to Check Prime Numbers

« Previous Program Next Program »

Check Prime Numbers in Python

To check whether the input number is a prime number or not in python, you have to ask from user to enter a number and start checking the number for prime number as shown in the program given here.

Python Programming Code to Check Prime Numbers

Following python program ask from user to enter any number to check whether it is a prime number or not:

# Python Program - Check Prime Number or Not

print("Enter 'x' for exit.")
num = input("Enter any number: ")
if num == 'x':
    number = int(num)
except ValueError:
    print("Please, enter a number...exiting...")
    for i in range(2, number):
    	if number%i == 0:
    	    print(number, "is not a prime number.")
        print(number, "is a prime number.")

Here is the sample run of the above Python program illustrating how to check whether a number is a prime number or not a prime number:

Below is the initial output asking from the user to enter any number to check what the number is:

check prime or not python

Now type any number say 7 to check for prime or not. As 7 is a prime number, therefore the above program will print that it is a prime number as shown in the below sample run:

python check prime or not

Try another run and type 20 this time to check it again. As 20 is not a prime number, therefore this time, you will see it is not a prime number as output as shown here in the given screenshot:

check prime number python

Below is the same program written and run directly on python shell.

python check prime number

Same Program in Other Languages

You may also like to learn or practice the same program in other popular programming languages:

« Previous Program Next Program »


Quick Links
Signup - Login - Give Online Test