Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: Write an is_prime function in Python

  1. Apr 12, 2010 #1
    1. The problem statement, all variables and given/known data

    Write a function, is_prime, which takes a single integral argument and returns True when the argument is a prime number and False otherwise. Add doctests to your function as you develop it.

    2. The attempt at a solution

    Code (Text):
    def is_prime(n):
        x = 1
        while x<=n:
            x+=1
            if n%x==0:
                return False
            elif x==n:
                return True

    if __name__ == '__main__':
        import doctest
        doctest.testmod()

    I figure x goes from 2 to n, and if it finds a factor it returns false; otherwise, true. Why doesn't this work?
     
  2. jcsd
  3. Apr 12, 2010 #2
    a) are you sure that you're calling the function? I tried to run your code but couldn't, so instead I just called the function to test it:
    Code (Text):

    for i in range(10):
        print is_prime(i)
     
    b) try to print out x, n, true, and false at every iteration of the loop

    c) returns throw you out of a function, so think about your exit conditions for the while loop

    I got your code working with a little tweak, so just step through the logic (which is what print statements-the most basic debugging tool-are for).
     
    Last edited: Apr 12, 2010
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook