Amir Rouatbi - 9 months ago 61

Python Question

This function is supposed to return True if a number is prime and False if it's not. The problem is that

`is_prime(9)`

`True`

`def is_prime(x):`

if x<2:

return False

elif x==2:

return True

elif x==3:

return True

else:

for i in range(2,x):

if x%i==0:

return False

break

else:

return True

Answer Source

Because if you write

```
for i in range(2,x):
if x%i==0:
return False
break
else:
return True
```

if `x`

is `9`

then `9%2 != 0`

, so it takes `else`

path and returns `True`

`odd_number % 2`

is always `= 1`

You have to remove the last line and replace it with `return True`

after the `for`

has finished:

```
def is_prime(x):
if x<2:
return False
elif x==2:
return True
elif x==3: #<-- This one is useless, it will be already checked within the for
return True
else:
for i in range(2,x):
if x%i==0:
return False
break
return True
print is_prime(9)
print is_prime(11)
```