In my last post I offered two different examples for generating prime numbers using python. The first script in that post generated every prime (except 2) from 1 to 9,999,999 and the second script generated every prime in a user-supplied range.

It’s neat to be able to generate a bunch of prime numbers but what if you had a number and wanted to know if it was prime? The script below does that. It’s little more than a modification of the scripts offered in my previous post on Generating prime numbers using python.

The biggest lesson I learned from this is how much faster my computer is than I am. Manually determining if a number is prime is not difficult, it’s just time consuming. Once you know the why and how of prime number determination, having a script like this one sure is helpful.

### Here’s the code:

```
#!/usr/bin/env python
print ""
print "*************************************************"
print "** Prime Number Checker **"
print "*************************************************"
print "This script will test to see"
print "if a given number is prime."
print ""
while True:
number = int(raw_input("What number do you want to check?: "))
if number == 1:
print "1 is NOT considered prime"
break
if number == 0:
print "No. No. No."
break
num = range(2,number)
counter = 0.0
for each in num:
modulus = float(number % each)
if modulus == 0.0:
pass
else: # if the modulus is not zero,
# increase the counter by 1.
counter += 1
if len(num) == counter:
# if the total number of non-zero
# modulus' is equal to the
# number of numbers in the range of
# i-2, the number is prime.
# In other words, every number in
# the range has a non-zero
# modulus (i.e it's prime)
print ""
print " %i is prime." % number
print ""
else:
print ""
print " %i is NOT prime." % number
print ""
```

Some funk with my code:

I added a little bit of cheat code to keep 1 and 0 from being listed as prime when tested using the script. I am fully aware that this could be done in a much more attractive way. I figured someone who ponders whether or not a particular number is prime isn’t going to be asking about 1, 2, 3, 4, 5, 6, etc. If you want to know if 919223 is prime, this script will tell you (it is!). If you want to know if 9192233 is prime this script will tell you that, too (it’s not!).

Cheers,

Colin Weaver

Previous Post: Wrapped In Python – Edition 2 – Generating Prime Numbers Using Python

Next Post: Wrapped In Python – Edition 4 – Primitive Root Finder using Python

If you liked this post, please consider sharing it. Thanks!