Python Write an is_prime function in Python

  • Thread starter Thread starter brushman
  • Start date Start date
  • Tags Tags
    Function Python
Click For Summary
The discussion revolves around creating a function, is_prime, that determines if a number is prime. The initial implementation incorrectly checks for factors by starting from 1, which leads to logical errors. Key issues identified include the need to start checking from 2, proper exit conditions for the while loop, and ensuring the function is called correctly for testing. Suggestions for debugging include using print statements to track variable values during iterations. The conversation emphasizes the importance of refining the logic and structure of the function to ensure accurate results.
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:
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

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
5K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 9 ·
Replies
9
Views
3K
  • · Replies 22 ·
Replies
22
Views
6K
Replies
55
Views
6K
  • · Replies 28 ·
Replies
28
Views
4K