Prac makes perfect 6 - is Prime. Don't understand


#1

Hi,
Here's mine. I don't understand and the hint didn't help.

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


#2

The only way for a number to determined False in your if statement is if it is a decimal number.

For instance, 3 % 1 would return False, as 3 is divisible by 1. So you are practically checking if your number is an integer.

You have to make it check if your number x is divisible by any of the numbers in the range 2, x - 1.
You have already set up a for loop that goes through the necessary numbers.

You also have to make sure that if x is less than 2, it will return False.

Apologies if my explanation is clunky, english is not my first language. Feel free to ask me about parts you didnt understand


#3

Hi, your English is fine but I am new at this and maths is not a language I understand. Can you tell me very simply line by line what's wrong with this?

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

I got this error message:
File "python", line 2
for i range(2,x-1):
^
SyntaxError: invalid syntax


#5

first off, I would appreciate it if you indented your code, like so:

def is_prime(x): 
    for i range(2,x-1):
        if x % 1==0:           #no integers will get past this statement!
            return False        #all integers return "False"
        elif x < 2:
            return False
        else:
            return True

Looking at the code, we can see that your first if statement returns False if the x is evenly divisible by 1. There are no integers that get past this if statement.

Your elif statement is only activated if your if statement failed, meaning x was not divisible by 1.

Your function is_prime should do all the following:

  1. return False if x is less than 2
  2. return False if x is divisible by any number in the range(2, x - 1)
  3. return True if none of the if statements were activated

Now, you could start off by creating an if statement that returns False if x is less than 2.

What I am proposing could look a bit like this:

def is_prime(x):
    if x < 2:
        return False
    else:

This way, any numbers that are below two get filtered out. All the numbers that get to the else statement are above 2.

From there, you can check if it is evenly divisible by any number in the range 2, x - 1.
This means looping through all the numbers between 2 and x - 1, and checking if x is divisible by them.

Hope this helps.