Sometimes it’s useful to have a simpe program around to answer if a certain number is a prime number or not. With a few lines of Python this is easy to build. The following small program prompts for a number and answer if it’s a prime or not. You can also read the exit code of the program in case you want to implement it in another program or a shell script. The program will quit with exit code 0 if it’a prime number, and 1 if it’s not. This program only works for numbers greater than 1, since it starts checking by dividing by 2. I think this is okay, since we all know (or nowdays consider) 1 to be the first prime number.

#!/usr/bin/env python3

n = int(input("Enter a number: "))
    
for i in range(2, n):
    if (n%i == 0):
        quit (str(n) + " is not a prime")
print (n, "is a prime")

How it works

To find out if a number is a prime number or not one can divide every number from two and up to the number itself minus 1. If none of these divisions get a whole number (no remainder), it’s a prime number. Let’s start with 5 as an example.

\[\frac{5}{2} = 2.5\] \[\frac{5}{3} = 1.666\] \[\frac{5}{4} = 1.25\]

As we can see from above we didn’t get any integers, or whole numbers, and hence it’s a prime number. Now let’s try 9 for example.

\[\frac{9}{2} = 4.5\] \[\frac{9}{3} = 3\]

We don’t need to go any further here, since we got a whole 3, and hence the number 9 is not a prime number.