Is_prime(x)


#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/isprime?action=lesson_resume&link_content_target=interstitial_lesson

<In what way does your code behave incorrectly? Include ALL error messages.>
I don’t understand why the answer code is right.

<What do you expect to happen instead?>
I expect the range to supposed to be range(2, x) since range will test all the numbers from 2 to x - 1. So if x = 7, the range would be 2, 3, 4, 5, 6. In the answer code they have range(2, x-1) which means the range would be 2, 3, 4, 5. Wouldn’t they have to test 6 as well to see if it is a prime number. With my code, when x = 2, it returns nothing when it should return True. With the answer code, wouldn’t the range become 2, 1, 0?

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

#2

i would personally use range(2, x) but with range(2,x-1) it will also work, if you use for/else, given then else runs when loop condition evaluate to false, which happens when x=2 even with x-1


#3

Okay I just tried changing to for/else. Shouldn’t that work for if/else too? I was thinking it x % n != 0 then it would just go straight to else and return True.


#4

no, it won’t work for if/else.

By default, at the end of a function, the function returns None, if we want to return something else at the end of the function, we can use the return keyword, so when a return keyword is reached, the function ends

so using if/else, will cause the function to end in the first iteration of the loop, so your function will not properly determine prime numbers


#5

Thank you for your help!


#6

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