6. is prime


#1

def is_prime(x):
    for n in range (2,x-1):
        if x % n == 0:
            return False
        else:
            return True

May I please have some feedback on what I'm doing wrong here?


6 is_prime
#2

You have if - else inside the for loop, and each of those have a return, so no matter what, you're going to return during the very first run of the for, i.e. for 2, even though you want to test other numbers.

edit: a better solution: ONLY worry about returning False inside the loop. If you reach the end of the loop, you'll know it to be True, so you can just return True after the loop!

(Remember that return ends the function, immediately giving the value given by the return, so any code after in the function won't run.)

I just did the exercise now so I solved it with

def is_prime(a):
    if a < 2:
        return False
    if a == 2:                # Oops, copied an old version
        return True
    for b in range(2, a):
        if a % b == 0:
            return False
    return True

#3

Nicely done! Makes sense too. Out of curiosity, why is an else: statement not necessary before returning the Boolean?


#4

I think that @trigonometrical mentioned it when he(she?) said that the function ends when something is returned. So if the if statement returns something, that's the end of the function, we don't have to worry about an else statement, because after that, it doesn't matter what happens.
In all honestly, it's an issue of preference.


#5

Clap clap. Here's my working overcomplication:

def is_prime(x):
    if x in (0,1) or x<0:
        return False
    elif x==2:
        return True
    else:
        n=2
        check=[]
        while n < x:
            if x % n == 0:
                check.append(1)
            elif x % n != 0:
                check.append(0)
            n+=1
    if sum(check)>0:
        return False
    else:
        return True

#6

This is my code,straightforward
def is_prime(x):

for n in range(2,x-1):
    if x%n==0:
        return False
if x<2:
    return False
else:
    return True

print is_prime(5)


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.