6. is_Prime


#1

Y’all help me out, in lamens terms, whats wrong with this code?

https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/isprime?action=lesson_resume



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



#2

there are two problem with your code: negative number, zero and 1 are not prime numbers and your program currently can’t handle this. Maybe make an if condition before the for loop to handle this?

9 is not a prime number, yet for x=9 your program returns True. This is incorrect. To understand why, we need to talk about return

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. Thus, the function ends when a return keyword is reached

which means, in your is_prime function ends at the first iteration of the loop

but to successfully determine that a number is a prime number, the for loop in your function needs to make all iterations (then x is not divisible by any number in range 2 till x), then after the loop return True

what do you need to change to make the program return True after the for loop?


Scrabble_score
#3

right so because 0 and 1 are not prime, the if statement would be like:

if x < 2:
  return False

then i have to take it out of the ‘if’ statement…

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


#4

this if statement (if x < 2) also catches negative numbers (-1, -2 till minus infinity). Negative numbers can never be prime numbers

take it out, it refers to else i assume? Then yes. Seems you did, seems my explanation came across very well :slight_smile:

All clear now?


#5

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