def is_prime(x):

if x>3:

for n in range(2,x-1):

if x%n==0:

return False

else:

return True

elif x==2 or x==3:

return True

else:

return False

print is_prime(15)

def is_prime(x):

if x>3:

for n in range(2,x-1):

if x%n==0:

return False

else:

return True

elif x==2 or x==3:

return True

else:

return False

print is_prime(15)

By default, a function returns None at the end of the function. If we want to return something else at the end of the function, we can use the return keyword.

Given return is the last thing a function does, when a return keyword is reached, the function ends

so your for loop ends in the first iteration of the loop, which can’t be right for determining prime number

def is_prime(x):

if x < 2:

return False

else:

for n in range(2, x-1):

if x % n == 0:

return False

return True

//why in this case it doesn’t end in the first iteration (for the if condition in for loop)?

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

I’ve tried this one too, but it doesn’t work

```
def is_prime(x):
if x<2:
return False
else:
n = 2
while n<(x/2):
if x % n == 0:
return False
break
n = n + 1
else:
return True
```

None of them works, why?

Why did you make these changes? Why do you think they would work? What error message are you getting? Maybe a new error message can lead to new insight

```
def is_prime(x):
if x<2:
return False
elif x==2 or x==3:
return True
else:
for n in range(2,x):
if x%n==0:
return False
return True
```

Your function fails on is_prime(9). It returns True when it should return False.

If it is about returning True in the very first iteration and then exiting the function, then why this one below is working?

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

because in the last code, `return True`

is outside the loop. Indention determines nesting.

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