Amir Rouatbi - 1 year ago 89
Python Question

# Codecademy Python “is_prime” exercise in “Practice Makes Perfect”-Is it really iterating?

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)`
returns
`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
``````

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)
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download