Write an is_prime function in Python

  • Context: Python 
  • Thread starter Thread starter brushman
  • Start date Start date
  • Tags Tags
    Function Python
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 reply · 5K views
brushman
Messages
112
Reaction score
1

Homework Statement



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:
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?
 
Physics news on Phys.org
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:
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: