<In what way does your code behave incorrectly? Include ALL error messages.> Oops, try again. Your function fails on is_prime(3). It returns None when it should return True.
<What do you expect to happen instead?>
i have been struggling through most of practice section but i was almost sure this was right. it makes sense to me if i read it out loud would like to see if someone could also explain why i am off and how close was it to a good answer
```python
def is_prime(x):
if x < 2:
return False
if x == 2:
return True
if x > 2:
for n in range(2,x):
if x % n == 0:
return False
else:
return True
def is_prime(x):
if x < 2:
return False
if x > 2:
for n in range(2,x):
if x % n == 0:
break
else:
return True
return False
return True
If the loop completes, the code in the else block runs, otherwise the next line runs (break skips the else block). The last line only runs when x == 2. Notice that the else is paired up with for not if.
I’ve only given this code as an example, not a solution, even though it does work. With a small change we can write this without an else block.
def is_prime(x):
if x < 2:
return False
if x > 2:
for n in range(2,x):
if x % n == 0:
return False
return True
Notice we don’t have to check if x == 2 in either example. That state falls right through the function to the final return statement.
Olá, observe o que o laço for faz dentro da função ( is_prime )
Defina uma função chamada is_prime que toma um número x como entrada
Para cada número n de 2 a x - 1, teste se x é divisível por n.
Se for, retorne False.
Se nenhum deles for primo, retorne True.
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for n in range(2, x - 1): / # Para cada número n de 2 a x - 1
if x % n == 0: / # se x é divisível por n.
return False / # retorne False.
else:
return True / # Se nenhum deles for primo, retorne True.
The placement of the else was the issue. When the loop completed it did not see the return statement. Something to consider about testing for 2… If x == 2 then return True does not need to be followed by another if. It’s not less than or equal to 2, so it must be greater. That’s a given.
def is_prime(x):
if x < 2:
return False
if x == 2:
return True
for n in range(2,x):
if x % n == 0:
return False
# this runs after the loop
return True