Write an is_prime function in Python

  • Context: Python 
  • Thread starter Thread starter brushman
  • Start date Start date
  • Tags Tags
    Function Python
Click For Summary
SUMMARY

The discussion focuses on creating an is_prime function in Python that determines if a given integer is prime. The initial implementation contains logical errors, particularly in the loop structure and exit conditions. A corrected approach involves iterating from 2 to the square root of n and checking for factors. Debugging techniques, such as using print statements, are recommended to trace the function's execution.

PREREQUISITES
  • Understanding of Python programming, specifically function definitions
  • Familiarity with control flow statements in Python (loops and conditionals)
  • Basic knowledge of prime numbers and their properties
  • Experience with debugging techniques in Python, such as using print statements
NEXT STEPS
  • Implement an optimized version of is_prime that checks divisibility only up to the square root of n
  • Learn about Python's doctest module for testing functions
  • Explore other algorithms for prime number generation, such as the Sieve of Eratosthenes
  • Investigate performance profiling tools in Python to analyze function efficiency
USEFUL FOR

Python developers, computer science students, and anyone interested in algorithm optimization and debugging techniques.

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?
 
Technology 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:

Similar threads

  • · Replies 29 ·
Replies
29
Views
3K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 15 ·
Replies
15
Views
2K
  • · Replies 11 ·
Replies
11
Views
1K
  • · Replies 34 ·
2
Replies
34
Views
6K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 9 ·
Replies
9
Views
3K
  • · Replies 22 ·
Replies
22
Views
6K
Replies
55
Views
7K
  • · Replies 28 ·
Replies
28
Views
5K