Prime Numb


#1



Define a function called is_prime that takes a number x as input.


Oops, try again. Your function fails on is_prime(4). It returns True when it should return False.

def is_prime(x):
    if(x==0 or x==1):
        return False
        
    n= x-1
    while(n>1):
        if x%n==0:
            return False
            break
        else:
            return True
        n=n-1
    else:
        return True


#2

a function ends the moment a return keyword is reached

if a return keyword is reached in a loop, the loop will break in order for the function to be able to break

so your while loop breaks in its first iteration, a return keyword is reached in all cases

Is this desired?


#3

okay i didn't know that... But even after removing the break term im getting the same error.
Ok so my new code looks like this and the error is of is_prime(-10):
def is_prime(x):
if(x==0 or x==1):
return False

n= x-1
while(n>1):
    if x%n==0:
        return False
    n=n-1
else:
    return True

#4

the return keyword breaks the loop, so removing the break keyword has no effect

i know, its confusing, but break keyword and return keyword breaking the loop are two different things.

If you have a better term, loved to hear it

@nitesh.sudhanshu, edit, negative numbers can't be prime numbers. Instead of checking of x equals 1 or 2, simply check if x is lesser then 2, this also covers all negative numbers


#5

I'm so dumb!! :slight_smile:thanks a lot


#6

this exercises are pretty tricky, nothing dumb about it. Can be very confusing


#7