When you hit a wall, take a break from the exercise and go back over the previous units to refresh your knowledge. On top of that, for this sort of exercise take a moment to brush up on the math concept that applies here. Prime numbers have special properties by which we can identify them.
After you have done some brushing up and research, take a break and get some air. Take a walk with the dog (if you have one), toss some balls and loosen up. Now you will have a clear head and your brain will have been able to sort things out in the process.
To clarify this definition for the following, Natural numbers are integers that are greater than zero (positive). We sometimes refer to them as counting numbers. Zero is not a natural number.
Prime Number Properties
- All primes are natural numbers.
- 1 is not prime.
- Primes are divisible only by self and 1.
- Except for 2, all primes are odd numbers.
- All natural numbers have prime factors (by degrees).
- Primes do not follow a pattern (at defined intervals).
- Despite the previous point, they can occur with some regularity.
That's enough points for our purposes. A study of the nature of Primes can lead all the way to a PhD, so you can be sure there is lots to know about them and how they fit into nature and science in all sorts of ways. But that is for another day.
From the list above, this exercise draws upon the first four points. Set the others aside, for now.
So we've already said that 1 is not a Prime and 0 is not Natural which leads us to our first test assertion: x is not less than 2 since nothing less than 2 can be a Prime.
That means we can reject said values at the get go.
if x < 2:
We also know that 2 is the only even number that is prime so we can shield it from the loop by not having sufficient range for the loop to execute.
for n in range(2, x):
x is excluded from the list that
range returns, the highest value in the range will
x - 1 (which is what I believe the instructions meant to convey).
By starting the range with
2 we effectively reject every even number on the first iteration of the loop. That means we don't need to keep iterating. In other words, get out of the loop by
False and don't have an
if x % n == 0:
That is all that needs to be inside the loop. The fall-through values (those that are not divisible) will drop to the return statement, the same one that
2 drops down to.