I understand that this is not a forum for statements but for questions, but this exercise seems to be the one where everyone stucks, not because the programming is challenging, but the concept of the prime number can sometimes lead to logic errors, rather than syntax ones.
Ok, fellow learners, if you are here you probably stuck on this one, and judging from the questions about it on this forum it’s challenging.
Truth is, i was stuck on it for a day or two, but i got the idea today, and ofcourse I won’t just post a code, I’ll explain.
Step 1. Prime Number:
“A prime number is a positive integer greater than 1 that has no positive divisors other than 1 and itself.”
Which means, that it’s not just a number that can’t be divided by 2, as some people say. It means that it cannot be divided with any other number other than 1 and itself.
Step 2. What the exercise asks for:
The exercise wants us to create a function “is_prime” with x as an argument.
Then, we should check if x is EVENLY divisible by any number from 2 to x-1.
If it is, return False
If it’s not divisible by any of them, which means that it’s only divisible by 1 and itself, the return True
Step 3. Actual Code:
Let’s start the code:
def is_prime(x): #function is_prime with argument x
if x < 2: #A number less than 2 is not a prime number
return False
for n in range(2, x-1): #The loop, as the exercise asked for it, from 2 to x-1
if x % n == 0: #if x is evenly divisible by n
return False
else: #See explanation for this one
return True
Explanation
The else statement MUST NOT be nested under the if statement. It’s a common mistake, and it’s usually what ruins the exercise. Exercise hints that saying “If none of them are, then return True”, which means that the for loop should end first, then if x wasn’t evenly divisible with any of the n numbers, then you return True.
Common mistakes:
As you already saw, I did not use “if x == 3” or “if x == 2”. Even though range(2, x-1) for x = 2 and x =3 returns an empty list, the program still works, since the for loop will not return anything, and else will go ahead and give us True, and 2 and 3 are both prime numbers.
So, you don’t need these if statements
Hope I helped, please feel free to ask me if something bothers you