As with any OOP language, you can use Python to conduct calculations and gather information about numbers. One cool thing you can do with Python is test if a number is prime or not. A prime number, as you may remember from math class way back when, is any whole number (it must be greater than 1), whose only factors are 1 and itself, meaning it can't evenly be divided by any number (apart from 1 and itself, of course). Prime numbers include 2, 3, 5, 7, 11, 13, and so on until infinity.

In Python, we can test for prime numbers pretty easily using the snippet below.

if num > 1:

for i in range(2,num):
 if (num % i) == 0:
 print(num,"is not a prime number")
 print(i,"times",num//i,"is",num)
 break
 else:
 print(num,"is a prime number")
 
else:
 print(num,"is not a prime number")

First, the code checks to make sure that the number is greater than 1 (anything less than one can't be a prime number because it isn't whole). Then it checks to see if the number is divisible by any number between 2 and the number you're checking. If it is divisible, then you'll see from the output that the number is not prime. If it isn't divisible by any of those numbers, then the message on the output will read "[num] is not a prime number."

To Practice: Try this interactive course on the basics of Lists, Functions, Packages and NumPy in Python.

  • Robert Sackmann

    Above code snippet (as of 2017-05-19) can make false statemente as:
    10017 is a prime number
    10017 is not a prime number
    3 times 3339 is 10017

    This slightly enhanced code:

    if num > 1:
    i = 1
    for i in range(2, num):
    if (num % i) == 0:
    print(num, “is not a prime number”)
    print(i, “times”, num//i, “is”, num)
    break
    elif i < num:
    print(".")
    elif i == num:
    print(num, "is a prime number")

    else:
    print(num, "is not a prime number")

    ..makes only correct statements on tested (non-prime) number 10017:
    .
    10017 is not a prime number
    3 times 3339 is 10017

  • Robert Sackmann

    CORRECTION: below code snippet also doesn’t work 100%; now also prime numbers are indicated correcty (test prime number 7919 e.g.):

    if num > 1:
    i = 1
    for i in range(2, num):
    if (num % i) == 0:
    print(num, “is not a prime number”)
    print(i, “times”, num//i, “is”, num)
    break
    elif i < num – 1:
    print(".")
    else:
    print(num, "is a prime number")

    else:
    print(num, "is not a prime number")

  • Robert Sackmann

    One more improvement for higher numbers (test 15485863 for being prime e.g.):
    replace the waiting indicator (which may cause trouble for high numbers):

    print(“.”)

    with the Python no operation command:

    pass

  • num not define ERROR is obvious.

  • num not define ERROR is obvious.

  • num not define ERROR is obvious.