Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

def primecheck(num): 
if num > 1:  
    for i in range(2, num): 
        if (num % i) == 0: 
            return False 
            break
        else: 
            return True

Im trying to make a function that checks if an input is prime or not. This code does return True if I enter a prime number, but it also enters true whenever I enter a multiple of a prime number? Why is this happening

thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
127 views
Welcome To Ask or Share your Answers For Others

1 Answer

The problem with your code is that you have return statements in the first iteration of the loop. Also break statement is not needed. Moving return True outside the loop gives the solution:

def primecheck(num):
    for i in range(2, num):
       if num % i == 0:
           return False
    return True

I leave num = 0 or 1 for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...